DEVEL15-linux-nfstrans-updates-20080630
[openafs.git] / src / afs / afs_daemons.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include "afs/param.h"
12
13 RCSID
14     ("$Header$");
15
16 #ifdef AFS_AIX51_ENV
17 #define __FULL_PROTO
18 #include <sys/sleep.h>
19 #endif
20
21 #include "afs/sysincludes.h"    /* Standard vendor system headers */
22 #include "afsincludes.h"        /* Afs-based standard headers */
23 #include "afs/afs_stats.h"      /* statistics gathering code */
24 #include "afs/afs_cbqueue.h"
25 #ifdef AFS_AIX_ENV
26 #include <sys/adspace.h>        /* for vm_att(), vm_det() */
27 #endif
28
29
30 /* background request queue size */
31 afs_lock_t afs_xbrs;            /* lock for brs */
32 static int brsInit = 0;
33 short afs_brsWaiters = 0;       /* number of users waiting for brs buffers */
34 short afs_brsDaemons = 0;       /* number of daemons waiting for brs requests */
35 struct brequest afs_brs[NBRS];  /* request structures */
36 struct afs_osi_WaitHandle AFS_WaitHandler, AFS_CSWaitHandler;
37 static int afs_brs_count = 0;   /* request counter, to service reqs in order */
38
39 static int rxepoch_checked = 0;
40 #define afs_CheckRXEpoch() {if (rxepoch_checked == 0 && rxkad_EpochWasSet) { \
41         rxepoch_checked = 1; afs_GCUserData(/* force flag */ 1);  } }
42
43 /* PAG garbage collection */
44 /* We induce a compile error if param.h does not define AFS_GCPAGS */
45 afs_int32 afs_gcpags = AFS_GCPAGS;
46 afs_int32 afs_gcpags_procsize = 0;
47
48 afs_int32 afs_CheckServerDaemonStarted = 0;
49 #ifndef DEFAULT_PROBE_INTERVAL
50 #define DEFAULT_PROBE_INTERVAL 30       /* default to 3 min */
51 #endif
52 afs_int32 afs_probe_interval = DEFAULT_PROBE_INTERVAL;
53 afs_int32 afs_probe_all_interval = 600;
54 afs_int32 afs_nat_probe_interval = 60;
55 afs_int32 afs_preCache = 0;
56
57 #define PROBE_WAIT() (1000 * (afs_probe_interval - ((afs_random() & 0x7fffffff) \
58                       % (afs_probe_interval/2))))
59
60 void
61 afs_SetCheckServerNATmode(int isnat)
62 {
63     static afs_int32 old_intvl, old_all_intvl;
64     static int wasnat;
65
66     if (isnat && !wasnat) {
67         old_intvl = afs_probe_interval;
68         old_all_intvl = afs_probe_all_interval;
69         afs_probe_interval = afs_nat_probe_interval;
70         afs_probe_all_interval = afs_nat_probe_interval;
71         afs_osi_CancelWait(&AFS_CSWaitHandler);
72     } else if (!isnat && wasnat) {
73         afs_probe_interval = old_intvl;
74         afs_probe_all_interval = old_all_intvl;
75     }
76     wasnat = isnat;
77 }
78
79 void
80 afs_CheckServerDaemon(void)
81 {
82     afs_int32 now, delay, lastCheck, last10MinCheck;
83
84     afs_CheckServerDaemonStarted = 1;
85
86     while (afs_initState < 101)
87         afs_osi_Sleep(&afs_initState);
88     afs_osi_Wait(PROBE_WAIT(), &AFS_CSWaitHandler, 0);
89
90     last10MinCheck = lastCheck = osi_Time();
91     while (1) {
92         if (afs_termState == AFSOP_STOP_CS) {
93             afs_termState = AFSOP_STOP_BKG;
94             afs_osi_Wakeup(&afs_termState);
95             break;
96         }
97
98         now = osi_Time();
99         if (afs_probe_interval + lastCheck <= now) {
100             afs_CheckServers(1, NULL);  /* check down servers */
101             lastCheck = now = osi_Time();
102         }
103
104         if (afs_probe_all_interval + last10MinCheck <= now) {
105             afs_Trace1(afs_iclSetp, CM_TRACE_PROBEUP, ICL_TYPE_INT32, afs_probe_all_interval);
106             afs_CheckServers(0, NULL);
107             last10MinCheck = now = osi_Time();
108         }
109         /* shutdown check. */
110         if (afs_termState == AFSOP_STOP_CS) {
111             afs_termState = AFSOP_STOP_BKG;
112             afs_osi_Wakeup(&afs_termState);
113             break;
114         }
115
116         /* Compute time to next probe. */
117         delay = afs_probe_interval + lastCheck;
118         if (delay > afs_probe_all_interval + last10MinCheck)
119             delay = afs_probe_all_interval + last10MinCheck;
120         delay -= now;
121         if (delay < 1)
122             delay = 1;
123         afs_osi_Wait(delay * 1000, &AFS_CSWaitHandler, 0);
124     }
125     afs_CheckServerDaemonStarted = 0;
126 }
127
128 extern int vfs_context_ref;
129
130 void
131 afs_Daemon(void)
132 {
133     afs_int32 code;
134     struct afs_exporter *exporter;
135     afs_int32 now;
136     afs_int32 last3MinCheck, last10MinCheck, last60MinCheck, lastNMinCheck;
137     afs_int32 last1MinCheck;
138     afs_uint32 lastCBSlotBump;
139     char cs_warned = 0;
140
141     AFS_STATCNT(afs_Daemon);
142     last1MinCheck = last3MinCheck = last60MinCheck = last10MinCheck =
143         lastNMinCheck = 0;
144
145     afs_rootFid.Fid.Volume = 0;
146     while (afs_initState < 101)
147         afs_osi_Sleep(&afs_initState);
148
149 #ifdef AFS_DARWIN80_ENV
150     if (afs_osi_ctxtp_initialized)
151         osi_Panic("vfs context already initialized");
152     while (afs_osi_ctxtp && vfs_context_ref)
153         afs_osi_Sleep(&afs_osi_ctxtp);
154     if (afs_osi_ctxtp && !vfs_context_ref)
155        vfs_context_rele(afs_osi_ctxtp);
156     afs_osi_ctxtp = vfs_context_create(NULL);
157     afs_osi_ctxtp_initialized = 1;
158 #endif
159     now = osi_Time();
160     lastCBSlotBump = now;
161
162     /* when a lot of clients are booted simultaneously, they develop
163      * annoying synchronous VL server bashing behaviors.  So we stagger them.
164      */
165     last1MinCheck = now + ((afs_random() & 0x7fffffff) % 60);   /* an extra 30 */
166     last3MinCheck = now - 90 + ((afs_random() & 0x7fffffff) % 180);
167     last60MinCheck = now - 1800 + ((afs_random() & 0x7fffffff) % 3600);
168     last10MinCheck = now - 300 + ((afs_random() & 0x7fffffff) % 600);
169     lastNMinCheck = now - 90 + ((afs_random() & 0x7fffffff) % 180);
170
171     /* start off with afs_initState >= 101 (basic init done) */
172     while (1) {
173         afs_CheckCallbacks(20); /* unstat anything which will expire soon */
174
175         /* things to do every 20 seconds or less - required by protocol spec */
176         if (afs_nfsexporter)
177             afs_FlushActiveVcaches(0);  /* flush NFS writes */
178         afs_FlushVCBs(1);       /* flush queued callbacks */
179         afs_MaybeWakeupTruncateDaemon();        /* free cache space if have too */
180         rx_CheckPackets();      /* Does RX need more packets? */
181
182         now = osi_Time();
183         if (lastCBSlotBump + CBHTSLOTLEN < now) {       /* pretty time-dependant */
184             lastCBSlotBump = now;
185             if (afs_BumpBase()) {
186                 afs_CheckCallbacks(20); /* unstat anything which will expire soon */
187             }
188         }
189
190         if (last1MinCheck + 60 < now) {
191             /* things to do every minute */
192             DFlush();           /* write out dir buffers */
193             afs_WriteThroughDSlots();   /* write through cacheinfo entries */
194             ObtainWriteLock(&afs_xvcache, 736);
195             afs_FlushReclaimedVcaches();
196             ReleaseWriteLock(&afs_xvcache);
197             afs_FlushActiveVcaches(1);  /* keep flocks held & flush nfs writes */
198 #if 0
199 #ifdef AFS_DISCON_ENV
200             afs_StoreDirtyVcaches();
201 #endif
202 #endif
203             afs_CheckRXEpoch();
204             last1MinCheck = now;
205         }
206
207         if (last3MinCheck + 180 < now) {
208             afs_CheckTokenCache();      /* check for access cache resets due to expired
209                                          * tickets */
210             last3MinCheck = now;
211         }
212         if (!afs_CheckServerDaemonStarted) {
213             /* Do the check here if the correct afsd is not installed. */
214             if (!cs_warned) {
215                 cs_warned = 1;
216                 printf("Please install afsd with check server daemon.\n");
217             }
218             if (lastNMinCheck + afs_probe_interval < now) {
219                 /* only check down servers */
220                 afs_CheckServers(1, NULL);
221                 lastNMinCheck = now;
222             }
223         }
224         if (last10MinCheck + 600 < now) {
225 #ifdef AFS_USERSPACE_IP_ADDR
226             extern int rxi_GetcbiInfo(void);
227 #endif
228             afs_Trace1(afs_iclSetp, CM_TRACE_PROBEUP, ICL_TYPE_INT32, 600);
229 #ifdef AFS_USERSPACE_IP_ADDR
230             if (rxi_GetcbiInfo()) {     /* addresses changed from last time */
231                 afs_FlushCBs();
232             }
233 #else /* AFS_USERSPACE_IP_ADDR */
234             if (rxi_GetIFInfo()) {      /* addresses changed from last time */
235                 afs_FlushCBs();
236             }
237 #endif /* else AFS_USERSPACE_IP_ADDR */
238             if (!afs_CheckServerDaemonStarted)
239                 afs_CheckServers(0, NULL);
240             afs_GCUserData(0);  /* gc old conns */
241             /* This is probably the wrong way of doing GC for the various exporters but it will suffice for a while */
242             for (exporter = root_exported; exporter;
243                  exporter = exporter->exp_next) {
244                 (void)EXP_GC(exporter, 0);      /* Generalize params */
245             }
246             {
247                 static int cnt = 0;
248                 if (++cnt < 12) {
249                     afs_CheckVolumeNames(AFS_VOLCHECK_EXPIRED |
250                                          AFS_VOLCHECK_BUSY);
251                 } else {
252                     cnt = 0;
253                     afs_CheckVolumeNames(AFS_VOLCHECK_EXPIRED |
254                                          AFS_VOLCHECK_BUSY |
255                                          AFS_VOLCHECK_MTPTS);
256                 }
257             }
258             last10MinCheck = now;
259         }
260         if (last60MinCheck + 3600 < now) {
261             afs_Trace1(afs_iclSetp, CM_TRACE_PROBEVOLUME, ICL_TYPE_INT32,
262                        3600);
263             afs_CheckRootVolume();
264 #if AFS_GCPAGS
265             if (afs_gcpags == AFS_GCPAGS_OK) {
266                 afs_int32 didany;
267                 afs_GCPAGs(&didany);
268             }
269 #endif
270             last60MinCheck = now;
271         }
272         if (afs_initState < 300) {      /* while things ain't rosy */
273             code = afs_CheckRootVolume();
274             if (code == 0)
275                 afs_initState = 300;    /* succeeded */
276             if (afs_initState < 200)
277                 afs_initState = 200;    /* tried once */
278             afs_osi_Wakeup(&afs_initState);
279         }
280
281         /* 18285 is because we're trying to divide evenly into 128, that is,
282          * CBSlotLen, while staying just under 20 seconds.  If CBSlotLen
283          * changes, should probably change this interval, too. 
284          * Some of the preceding actions may take quite some time, so we
285          * might not want to wait the entire interval */
286         now = 18285 - (osi_Time() - now);
287         if (now > 0) {
288             afs_osi_Wait(now, &AFS_WaitHandler, 0);
289         }
290
291         if (afs_termState == AFSOP_STOP_AFS) {
292             if (afs_CheckServerDaemonStarted)
293                 afs_termState = AFSOP_STOP_CS;
294             else
295                 afs_termState = AFSOP_STOP_BKG;
296             afs_osi_Wakeup(&afs_termState);
297             return;
298         }
299     }
300 }
301
302 int
303 afs_CheckRootVolume(void)
304 {
305     char rootVolName[32];
306     struct volume *tvp = NULL;
307     int usingDynroot = afs_GetDynrootEnable();
308     int localcell;
309
310     AFS_STATCNT(afs_CheckRootVolume);
311     if (*afs_rootVolumeName == 0) {
312         strcpy(rootVolName, "root.afs");
313     } else {
314         strcpy(rootVolName, afs_rootVolumeName);
315     }
316
317     if (usingDynroot) {
318         afs_GetDynrootFid(&afs_rootFid);
319         tvp = afs_GetVolume(&afs_rootFid, NULL, READ_LOCK);
320     } else {
321         struct cell *lc = afs_GetPrimaryCell(READ_LOCK);
322
323         if (!lc)
324             return ENOENT;
325         localcell = lc->cellNum;
326         afs_PutCell(lc, READ_LOCK);
327         tvp = afs_GetVolumeByName(rootVolName, localcell, 1, NULL, READ_LOCK);
328         if (!tvp) {
329             char buf[128];
330             int len = strlen(rootVolName);
331
332             if ((len < 9) || strcmp(&rootVolName[len - 9], ".readonly")) {
333                 strcpy(buf, rootVolName);
334                 afs_strcat(buf, ".readonly");
335                 tvp = afs_GetVolumeByName(buf, localcell, 1, NULL, READ_LOCK);
336             }
337         }
338         if (tvp) {
339             int volid = (tvp->roVol ? tvp->roVol : tvp->volume);
340             afs_rootFid.Cell = localcell;
341             if (afs_rootFid.Fid.Volume && afs_rootFid.Fid.Volume != volid
342                 && afs_globalVp) {
343                 struct vcache *tvc = afs_globalVp;
344                 /* If we had a root fid before and it changed location we reset
345                  * the afs_globalVp so that it will be reevaluated.
346                  * Just decrement the reference count. This only occurs during
347                  * initial cell setup and can panic the machine if we set the
348                  * count to zero and fs checkv is executed when the current
349                  * directory is /afs.
350                  */
351 #ifdef AFS_LINUX20_ENV
352                 {
353                     struct vrequest treq;
354                     struct vattr vattr;
355                     cred_t *credp;
356                     struct dentry *dp;
357                     struct vcache *vcp;
358                     
359                     afs_rootFid.Fid.Volume = volid;
360                     afs_rootFid.Fid.Vnode = 1;
361                     afs_rootFid.Fid.Unique = 1;
362                     
363                     credp = crref();
364                     if (afs_InitReq(&treq, credp))
365                         goto out;
366                     vcp = afs_GetVCache(&afs_rootFid, &treq, NULL, NULL);
367                     if (!vcp)
368                         goto out;
369                     afs_getattr(vcp, &vattr, credp);
370                     afs_fill_inode(AFSTOV(vcp), &vattr);
371                     
372                     dp = d_find_alias(AFSTOV(afs_globalVp));
373                     
374 #if defined(AFS_LINUX24_ENV)
375                     spin_lock(&dcache_lock);
376 #if defined(AFS_LINUX26_ENV)
377                     spin_lock(&dp->d_lock);
378 #endif
379 #endif
380                     list_del_init(&dp->d_alias);
381                     list_add(&dp->d_alias, &(AFSTOV(vcp)->i_dentry));
382                     dp->d_inode = AFSTOV(vcp);
383 #if defined(AFS_LINUX24_ENV)
384 #if defined(AFS_LINUX26_ENV)
385                     spin_unlock(&dp->d_lock);
386 #endif
387                     spin_unlock(&dcache_lock);
388 #endif
389                     dput(dp);
390                     
391                     AFS_FAST_RELE(afs_globalVp);
392                     afs_globalVp = vcp;
393                 out:
394                     crfree(credp);
395                 }
396 #else
397 #ifdef AFS_DARWIN80_ENV
398                 afs_PutVCache(afs_globalVp);
399 #else
400                 AFS_FAST_RELE(afs_globalVp);
401 #endif
402                 afs_globalVp = 0;
403 #endif
404             }
405             afs_rootFid.Fid.Volume = volid;
406             afs_rootFid.Fid.Vnode = 1;
407             afs_rootFid.Fid.Unique = 1;
408         }
409     }
410     if (tvp) {
411         afs_initState = 300;    /* won */
412         afs_osi_Wakeup(&afs_initState);
413         afs_PutVolume(tvp, READ_LOCK);
414     }
415     if (afs_rootFid.Fid.Volume)
416         return 0;
417     else
418         return ENOENT;
419 }
420
421 /* ptr_parm 0 is the pathname, size_parm 0 to the fetch is the chunk number */
422 static void
423 BPath(register struct brequest *ab)
424 {
425     register struct dcache *tdc = NULL;
426     struct vcache *tvc = NULL;
427     struct vnode *tvn = NULL;
428 #ifdef AFS_LINUX22_ENV
429     struct dentry *dp = NULL;
430 #endif
431     afs_size_t offset, len;
432     struct vrequest treq;
433     afs_int32 code;
434
435     AFS_STATCNT(BPath);
436     if ((code = afs_InitReq(&treq, ab->cred)))
437         return;
438     AFS_GUNLOCK();
439 #ifdef AFS_LINUX22_ENV
440     code = gop_lookupname((char *)ab->ptr_parm[0], AFS_UIOSYS, 1, &dp);
441     if (dp)
442         tvn = (struct vnode *)dp->d_inode;
443 #else
444     code = gop_lookupname((char *)ab->ptr_parm[0], AFS_UIOSYS, 1, &tvn);
445 #endif
446     AFS_GLOCK();
447     osi_FreeLargeSpace((char *)ab->ptr_parm[0]);        /* free path name buffer here */
448     if (code)
449         return;
450     /* now path may not have been in afs, so check that before calling our cache manager */
451     if (!tvn || !IsAfsVnode(tvn)) {
452         /* release it and give up */
453         if (tvn) {
454 #ifdef AFS_LINUX22_ENV
455             dput(dp);
456 #else
457             AFS_RELE(tvn);
458 #endif
459         }
460         return;
461     }
462     tvc = VTOAFS(tvn);
463     /* here we know its an afs vnode, so we can get the data for the chunk */
464     tdc = afs_GetDCache(tvc, ab->size_parm[0], &treq, &offset, &len, 1);
465     if (tdc) {
466         afs_PutDCache(tdc);
467     }
468 #ifdef AFS_LINUX22_ENV
469     dput(dp);
470 #else
471     AFS_RELE(tvn);
472 #endif
473 }
474
475 /* size_parm 0 to the fetch is the chunk number,
476  * ptr_parm 0 is the dcache entry to wakeup,
477  * size_parm 1 is true iff we should release the dcache entry here.
478  */
479 static void
480 BPrefetch(register struct brequest *ab)
481 {
482     register struct dcache *tdc;
483     register struct vcache *tvc;
484     afs_size_t offset, len, abyte, totallen = 0;
485     struct vrequest treq;
486
487     AFS_STATCNT(BPrefetch);
488     if ((len = afs_InitReq(&treq, ab->cred)))
489         return;
490     abyte = ab->size_parm[0];
491     tvc = ab->vc;
492     do {
493         tdc = afs_GetDCache(tvc, abyte, &treq, &offset, &len, 1);
494         if (tdc) {
495             afs_PutDCache(tdc);
496         }
497         abyte+=len; 
498         totallen += len;
499     } while ((totallen < afs_preCache) && tdc && (len > 0));
500     /* now, dude may be waiting for us to clear DFFetchReq bit; do so.  Can't
501      * use tdc from GetDCache since afs_GetDCache may fail, but someone may
502      * be waiting for our wakeup anyway.
503      */
504     tdc = (struct dcache *)(ab->ptr_parm[0]);
505     ObtainSharedLock(&tdc->lock, 640);
506     if (tdc->mflags & DFFetchReq) {
507         UpgradeSToWLock(&tdc->lock, 641);
508         tdc->mflags &= ~DFFetchReq;
509         ReleaseWriteLock(&tdc->lock);
510     } else {
511         ReleaseSharedLock(&tdc->lock);
512     }
513     afs_osi_Wakeup(&tdc->validPos);
514     if (ab->size_parm[1]) {
515         afs_PutDCache(tdc);     /* put this one back, too */
516     }
517 }
518
519
520 static void
521 BStore(register struct brequest *ab)
522 {
523     register struct vcache *tvc;
524     register afs_int32 code;
525     struct vrequest treq;
526 #if defined(AFS_SGI_ENV)
527     struct cred *tmpcred;
528 #endif
529
530     AFS_STATCNT(BStore);
531     if ((code = afs_InitReq(&treq, ab->cred)))
532         return;
533     code = 0;
534     tvc = ab->vc;
535 #if defined(AFS_SGI_ENV)
536     /*
537      * Since StoreOnLastReference can end up calling osi_SyncVM which
538      * calls into VM code that assumes that u.u_cred has the
539      * correct credentials, we set our to theirs for this xaction
540      */
541     tmpcred = OSI_GET_CURRENT_CRED();
542     OSI_SET_CURRENT_CRED(ab->cred);
543
544     /*
545      * To avoid recursion since the WriteLock may be released during VM
546      * operations, we hold the VOP_RWLOCK across this transaction as
547      * do the other callers of StoreOnLastReference
548      */
549     AFS_RWLOCK((vnode_t *) tvc, 1);
550 #endif
551     ObtainWriteLock(&tvc->lock, 209);
552     code = afs_StoreOnLastReference(tvc, &treq);
553     ReleaseWriteLock(&tvc->lock);
554 #if defined(AFS_SGI_ENV)
555     OSI_SET_CURRENT_CRED(tmpcred);
556     AFS_RWUNLOCK((vnode_t *) tvc, 1);
557 #endif
558     /* now set final return code, and wakeup anyone waiting */
559     if ((ab->flags & BUVALID) == 0) {
560         ab->code = afs_CheckCode(code, &treq, 43);      /* set final code, since treq doesn't go across processes */
561         ab->flags |= BUVALID;
562         if (ab->flags & BUWAIT) {
563             ab->flags &= ~BUWAIT;
564             afs_osi_Wakeup(ab);
565         }
566     }
567 }
568
569 /* release a held request buffer */
570 void
571 afs_BRelease(register struct brequest *ab)
572 {
573
574     AFS_STATCNT(afs_BRelease);
575     MObtainWriteLock(&afs_xbrs, 294);
576     if (--ab->refCount <= 0) {
577         ab->flags = 0;
578     }
579     if (afs_brsWaiters)
580         afs_osi_Wakeup(&afs_brsWaiters);
581     MReleaseWriteLock(&afs_xbrs);
582 }
583
584 /* return true if bkg fetch daemons are all busy */
585 int
586 afs_BBusy(void)
587 {
588     AFS_STATCNT(afs_BBusy);
589     if (afs_brsDaemons > 0)
590         return 0;
591     return 1;
592 }
593
594 struct brequest *
595 afs_BQueue(register short aopcode, register struct vcache *avc,
596            afs_int32 dontwait, afs_int32 ause, struct AFS_UCRED *acred,
597            afs_size_t asparm0, afs_size_t asparm1, void *apparm0)
598 {
599     register int i;
600     register struct brequest *tb;
601
602     AFS_STATCNT(afs_BQueue);
603     MObtainWriteLock(&afs_xbrs, 296);
604     while (1) {
605         tb = afs_brs;
606         for (i = 0; i < NBRS; i++, tb++) {
607             if (tb->refCount == 0)
608                 break;
609         }
610         if (i < NBRS) {
611             /* found a buffer */
612             tb->opcode = aopcode;
613             tb->vc = avc;
614             tb->cred = acred;
615             crhold(tb->cred);
616             if (avc) {
617                 VN_HOLD(AFSTOV(avc));
618             }
619             tb->refCount = ause + 1;
620             tb->size_parm[0] = asparm0;
621             tb->size_parm[1] = asparm1;
622             tb->ptr_parm[0] = apparm0;
623             tb->flags = 0;
624             tb->code = 0;
625             tb->ts = afs_brs_count++;
626             /* if daemons are waiting for work, wake them up */
627             if (afs_brsDaemons > 0) {
628                 afs_osi_Wakeup(&afs_brsDaemons);
629             }
630             MReleaseWriteLock(&afs_xbrs);
631             return tb;
632         }
633         if (dontwait) {
634             MReleaseWriteLock(&afs_xbrs);
635             return NULL;
636         }
637         /* no free buffers, sleep a while */
638         afs_brsWaiters++;
639         MReleaseWriteLock(&afs_xbrs);
640         afs_osi_Sleep(&afs_brsWaiters);
641         MObtainWriteLock(&afs_xbrs, 301);
642         afs_brsWaiters--;
643     }
644 }
645
646 #ifdef AFS_AIX41_ENV
647 /* AIX 4.1 has a much different sleep/wakeup mechanism available for use. 
648  * The modifications here will work for either a UP or MP machine.
649  */
650 struct buf *afs_asyncbuf = (struct buf *)0;
651 tid_t afs_asyncbuf_cv = EVENT_NULL;
652 afs_int32 afs_biodcnt = 0;
653
654 /* in implementing this, I assumed that all external linked lists were
655  * null-terminated.  
656  *
657  * Several places in this code traverse a linked list.  The algorithm
658  * used here is probably unfamiliar to most people.  Careful examination
659  * will show that it eliminates an assignment inside the loop, as compared
660  * to the standard algorithm, at the cost of occasionally using an extra
661  * variable.
662  */
663
664 /* get_bioreq()
665  *
666  * This function obtains, and returns, a pointer to a buffer for
667  * processing by a daemon.  It sleeps until such a buffer is available.
668  * The source of buffers for it is the list afs_asyncbuf (see also 
669  * afs_gn_strategy).  This function may be invoked concurrently by
670  * several processes, that is, several instances of the same daemon.
671  * afs_gn_strategy, which adds buffers to the list, runs at interrupt
672  * level, while get_bioreq runs at process level.
673  *
674  * Since AIX 4.1 can wake just one process at a time, the separate sleep
675  * addresses have been removed.
676  * Note that the kernel_lock is held until the e_sleep_thread() occurs. 
677  * The afs_asyncbuf_lock is primarily used to serialize access between
678  * process and interrupts.
679  */
680 Simple_lock afs_asyncbuf_lock;
681 struct buf *
682 afs_get_bioreq()
683 {
684     struct buf *bp = NULL;
685     struct buf *bestbp;
686     struct buf **bestlbpP, **lbpP;
687     long bestage, stop;
688     struct buf *t1P, *t2P;      /* temp pointers for list manipulation */
689     int oldPriority;
690     afs_uint32 wait_ret;
691     struct afs_bioqueue *s;
692
693     /* ??? Does the forward pointer of the returned buffer need to be NULL?
694      */
695
696     /* Disable interrupts from the strategy function, and save the 
697      * prior priority level and lock access to the afs_asyncbuf.
698      */
699     AFS_GUNLOCK();
700     oldPriority = disable_lock(INTMAX, &afs_asyncbuf_lock);
701
702     while (1) {
703         if (afs_asyncbuf) {
704             /* look for oldest buffer */
705             bp = bestbp = afs_asyncbuf;
706             bestage = (long)bestbp->av_back;
707             bestlbpP = &afs_asyncbuf;
708             while (1) {
709                 lbpP = &bp->av_forw;
710                 bp = *lbpP;
711                 if (!bp)
712                     break;
713                 if ((long)bp->av_back - bestage < 0) {
714                     bestbp = bp;
715                     bestlbpP = lbpP;
716                     bestage = (long)bp->av_back;
717                 }
718             }
719             bp = bestbp;
720             *bestlbpP = bp->av_forw;
721             break;
722         } else {
723             /* If afs_asyncbuf is null, it is necessary to go to sleep.
724              * e_wakeup_one() ensures that only one thread wakes.
725              */
726             int interrupted;
727             /* The LOCK_HANDLER indicates to e_sleep_thread to only drop the
728              * lock on an MP machine.
729              */
730             interrupted =
731                 e_sleep_thread(&afs_asyncbuf_cv, &afs_asyncbuf_lock,
732                                LOCK_HANDLER | INTERRUPTIBLE);
733             if (interrupted == THREAD_INTERRUPTED) {
734                 /* re-enable interrupts from strategy */
735                 unlock_enable(oldPriority, &afs_asyncbuf_lock);
736                 AFS_GLOCK();
737                 return (NULL);
738             }
739         }                       /* end of "else asyncbuf is empty" */
740     }                           /* end of "inner loop" */
741
742     /*assert (bp); */
743
744     unlock_enable(oldPriority, &afs_asyncbuf_lock);
745     AFS_GLOCK();
746
747     /* For the convenience of other code, replace the gnodes in
748      * the b_vp field of bp and the other buffers on the b_work
749      * chain with the corresponding vnodes.   
750      *
751      * ??? what happens to the gnodes?  They're not just cut loose,
752      * are they?
753      */
754     for (t1P = bp;;) {
755         t2P = (struct buf *)t1P->b_work;
756         t1P->b_vp = ((struct gnode *)t1P->b_vp)->gn_vnode;
757         if (!t2P)
758             break;
759
760         t1P = (struct buf *)t2P->b_work;
761         t2P->b_vp = ((struct gnode *)t2P->b_vp)->gn_vnode;
762         if (!t1P)
763             break;
764     }
765
766     /* If the buffer does not specify I/O, it may immediately
767      * be returned to the caller.  This condition is detected
768      * by examining the buffer's flags (the b_flags field).  If
769      * the B_PFPROT bit is set, the buffer represents a protection
770      * violation, rather than a request for I/O.  The remainder
771      * of the outer loop handles the case where the B_PFPROT bit is clear.
772      */
773     if (bp->b_flags & B_PFPROT) {
774         return (bp);
775     }
776     return (bp);
777
778 }                               /* end of function get_bioreq() */
779
780
781 /* afs_BioDaemon
782  *
783  * This function is the daemon.  It is called from the syscall
784  * interface.  Ordinarily, a script or an administrator will run a
785  * daemon startup utility, specifying the number of I/O daemons to
786  * run.  The utility will fork off that number of processes,
787  * each making the appropriate syscall, which will cause this
788  * function to be invoked.
789  */
790 static int afs_initbiod = 0;    /* this is self-initializing code */
791 int DOvmlock = 0;
792 int
793 afs_BioDaemon(afs_int32 nbiods)
794 {
795     afs_int32 code, s, pflg = 0;
796     label_t jmpbuf;
797     struct buf *bp, *bp1, *tbp1, *tbp2; /* temp pointers only */
798     caddr_t tmpaddr;
799     struct vnode *vp;
800     struct vcache *vcp;
801     char tmperr;
802     if (!afs_initbiod) {
803         /* XXX ###1 XXX */
804         afs_initbiod = 1;
805         /* pin lock, since we'll be using it in an interrupt. */
806         lock_alloc(&afs_asyncbuf_lock, LOCK_ALLOC_PIN, 2, 1);
807         simple_lock_init(&afs_asyncbuf_lock);
808         pin(&afs_asyncbuf, sizeof(struct buf *));
809         pin(&afs_asyncbuf_cv, sizeof(afs_int32));
810     }
811
812     /* Ignore HUP signals... */
813     {
814         sigset_t sigbits, osigbits;
815         /*
816          * add SIGHUP to the set of already masked signals
817          */
818         SIGFILLSET(sigbits);    /* allow all signals    */
819         SIGDELSET(sigbits, SIGHUP);     /*   except SIGHUP      */
820         limit_sigs(&sigbits, &osigbits);        /*   and already masked */
821     }
822     /* Main body starts here -- this is an intentional infinite loop, and
823      * should NEVER exit 
824      *
825      * Now, the loop will exit if get_bioreq() returns NULL, indicating 
826      * that we've been interrupted.
827      */
828     while (1) {
829         bp = afs_get_bioreq();
830         if (!bp)
831             break;              /* we were interrupted */
832         if (code = setjmpx(&jmpbuf)) {
833             /* This should not have happend, maybe a lack of resources  */
834             AFS_GUNLOCK();
835             s = disable_lock(INTMAX, &afs_asyncbuf_lock);
836             for (bp1 = bp; bp; bp = bp1) {
837                 if (bp1)
838                     bp1 = (struct buf *)bp1->b_work;
839                 bp->b_actf = 0;
840                 bp->b_error = code;
841                 bp->b_flags |= B_ERROR;
842                 iodone(bp);
843             }
844             unlock_enable(s, &afs_asyncbuf_lock);
845             AFS_GLOCK();
846             continue;
847         }
848         vcp = VTOAFS(bp->b_vp);
849         if (bp->b_flags & B_PFSTORE) {  /* XXXX */
850             ObtainWriteLock(&vcp->lock, 404);
851             if (vcp->v.v_gnode->gn_mwrcnt) {
852                 afs_offs_t newlength =
853                     (afs_offs_t) dbtob(bp->b_blkno) + bp->b_bcount;
854                 if (vcp->m.Length < newlength) {
855                     afs_Trace4(afs_iclSetp, CM_TRACE_SETLENGTH,
856                                ICL_TYPE_STRING, __FILE__, ICL_TYPE_LONG,
857                                __LINE__, ICL_TYPE_OFFSET,
858                                ICL_HANDLE_OFFSET(vcp->m.Length),
859                                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(newlength));
860                     vcp->m.Length = newlength;
861                 }
862             }
863             ReleaseWriteLock(&vcp->lock);
864         }
865         /* If the buffer represents a protection violation, rather than
866          * an actual request for I/O, no special action need be taken.  
867          */
868         if (bp->b_flags & B_PFPROT) {
869             iodone(bp);         /* Notify all users of the buffer that we're done */
870             clrjmpx(&jmpbuf);
871             continue;
872         }
873         if (DOvmlock)
874             ObtainWriteLock(&vcp->pvmlock, 211);
875         /*
876          * First map its data area to a region in the current address space
877          * by calling vm_att with the subspace identifier, and a pointer to
878          * the data area.  vm_att returns  a new data area pointer, but we
879          * also want to hang onto the old one.
880          */
881         tmpaddr = bp->b_baddr;
882         bp->b_baddr = (caddr_t) vm_att(bp->b_xmemd.subspace_id, tmpaddr);
883         tmperr = afs_ustrategy(bp);     /* temp variable saves offset calculation */
884         if (tmperr) {           /* in non-error case */
885             bp->b_flags |= B_ERROR;     /* should other flags remain set ??? */
886             bp->b_error = tmperr;
887         }
888
889         /* Unmap the buffer's data area by calling vm_det.  Reset data area
890          * to the value that we saved above.
891          */
892         vm_det(bp->b_baddr);
893         bp->b_baddr = tmpaddr;
894
895         /*
896          * buffer may be linked with other buffers via the b_work field.
897          * See also afs_gn_strategy.  For each buffer in the chain (including
898          * bp) notify all users of the buffer that the daemon is finished
899          * using it by calling iodone.  
900          * assumes iodone can modify the b_work field.
901          */
902         for (tbp1 = bp;;) {
903             tbp2 = (struct buf *)tbp1->b_work;
904             iodone(tbp1);
905             if (!tbp2)
906                 break;
907
908             tbp1 = (struct buf *)tbp2->b_work;
909             iodone(tbp2);
910             if (!tbp1)
911                 break;
912         }
913         if (DOvmlock)
914             ReleaseWriteLock(&vcp->pvmlock);    /* Unlock the vnode.  */
915         clrjmpx(&jmpbuf);
916     }                           /* infinite loop (unless we're interrupted) */
917 }                               /* end of afs_BioDaemon() */
918
919 #endif /* AFS_AIX41_ENV */
920
921
922 int afs_nbrs = 0;
923 void
924 afs_BackgroundDaemon(void)
925 {
926     struct brequest *tb;
927     int i, foundAny;
928
929     AFS_STATCNT(afs_BackgroundDaemon);
930     /* initialize subsystem */
931     if (brsInit == 0) {
932         LOCK_INIT(&afs_xbrs, "afs_xbrs");
933         memset((char *)afs_brs, 0, sizeof(afs_brs));
934         brsInit = 1;
935 #if defined (AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
936         /*
937          * steal the first daemon for doing delayed DSlot flushing
938          * (see afs_GetDownDSlot)
939          */
940         AFS_GUNLOCK();
941         afs_sgidaemon();
942         return;
943 #endif
944     }
945     afs_nbrs++;
946
947     MObtainWriteLock(&afs_xbrs, 302);
948     while (1) {
949         int min_ts = 0;
950         struct brequest *min_tb = NULL;
951
952         if (afs_termState == AFSOP_STOP_BKG) {
953             if (--afs_nbrs <= 0)
954                 afs_termState = AFSOP_STOP_TRUNCDAEMON;
955             MReleaseWriteLock(&afs_xbrs);
956             afs_osi_Wakeup(&afs_termState);
957             return;
958         }
959
960         /* find a request */
961         tb = afs_brs;
962         foundAny = 0;
963         for (i = 0; i < NBRS; i++, tb++) {
964             /* look for request with smallest ts */
965             if ((tb->refCount > 0) && !(tb->flags & BSTARTED)) {
966                 /* new request, not yet picked up */
967                 if ((min_tb && (min_ts - tb->ts > 0)) || !min_tb) {
968                     min_tb = tb;
969                     min_ts = tb->ts;
970                 }
971             }
972         }
973         if ((tb = min_tb)) {
974             /* claim and process this request */
975             tb->flags |= BSTARTED;
976             MReleaseWriteLock(&afs_xbrs);
977             foundAny = 1;
978             afs_Trace1(afs_iclSetp, CM_TRACE_BKG1, ICL_TYPE_INT32,
979                        tb->opcode);
980             if (tb->opcode == BOP_FETCH)
981                 BPrefetch(tb);
982             else if (tb->opcode == BOP_STORE)
983                 BStore(tb);
984             else if (tb->opcode == BOP_PATH)
985                 BPath(tb);
986             else
987                 panic("background bop");
988             if (tb->vc) {
989                 AFS_RELE(AFSTOV(tb->vc));       /* MUST call vnode layer or could lose vnodes */
990                 tb->vc = NULL;
991             }
992             if (tb->cred) {
993                 crfree(tb->cred);
994                 tb->cred = (struct AFS_UCRED *)0;
995             }
996             afs_BRelease(tb);   /* this grabs and releases afs_xbrs lock */
997             MObtainWriteLock(&afs_xbrs, 305);
998         }
999         if (!foundAny) {
1000             /* wait for new request */
1001             afs_brsDaemons++;
1002             MReleaseWriteLock(&afs_xbrs);
1003             afs_osi_Sleep(&afs_brsDaemons);
1004             MObtainWriteLock(&afs_xbrs, 307);
1005             afs_brsDaemons--;
1006         }
1007     }
1008 }
1009
1010
1011 void
1012 shutdown_daemons(void)
1013 {
1014     AFS_STATCNT(shutdown_daemons);
1015     if (afs_cold_shutdown) {
1016         afs_brsDaemons = brsInit = 0;
1017         rxepoch_checked = afs_nbrs = 0;
1018         memset((char *)afs_brs, 0, sizeof(afs_brs));
1019         memset((char *)&afs_xbrs, 0, sizeof(afs_lock_t));
1020         afs_brsWaiters = 0;
1021 #ifdef AFS_AIX41_ENV
1022         lock_free(&afs_asyncbuf_lock);
1023         unpin(&afs_asyncbuf, sizeof(struct buf *));
1024         unpin(&afs_asyncbuf_cv, sizeof(afs_int32));
1025         afs_initbiod = 0;
1026 #endif
1027     }
1028 }
1029
1030 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1031 /*
1032  * sgi - daemon - handles certain operations that otherwise
1033  * would use up too much kernel stack space
1034  *
1035  * This all assumes that since the caller must have the xdcache lock
1036  * exclusively that the list will never be more than one long
1037  * and noone else can attempt to add anything until we're done.
1038  */
1039 SV_TYPE afs_sgibksync;
1040 SV_TYPE afs_sgibkwait;
1041 lock_t afs_sgibklock;
1042 struct dcache *afs_sgibklist;
1043
1044 int
1045 afs_sgidaemon(void)
1046 {
1047     int s;
1048     struct dcache *tdc;
1049
1050     if (afs_sgibklock == NULL) {
1051         SV_INIT(&afs_sgibksync, "bksync", 0, 0);
1052         SV_INIT(&afs_sgibkwait, "bkwait", 0, 0);
1053         SPINLOCK_INIT(&afs_sgibklock, "bklock");
1054     }
1055     s = SPLOCK(afs_sgibklock);
1056     for (;;) {
1057         /* wait for something to do */
1058         SP_WAIT(afs_sgibklock, s, &afs_sgibksync, PINOD);
1059         osi_Assert(afs_sgibklist);
1060
1061         /* XX will probably need to generalize to real list someday */
1062         s = SPLOCK(afs_sgibklock);
1063         while (afs_sgibklist) {
1064             tdc = afs_sgibklist;
1065             afs_sgibklist = NULL;
1066             SPUNLOCK(afs_sgibklock, s);
1067             AFS_GLOCK();
1068             tdc->dflags &= ~DFEntryMod;
1069             afs_WriteDCache(tdc, 1);
1070             AFS_GUNLOCK();
1071             s = SPLOCK(afs_sgibklock);
1072         }
1073
1074         /* done all the work - wake everyone up */
1075         while (SV_SIGNAL(&afs_sgibkwait));
1076     }
1077 }
1078 #endif