310c5685ee313cf1270bc5dd42a799244528ebfe
[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("$Header$");
14
15 #include "../afs/sysincludes.h" /* Standard vendor system headers */
16 #include "../afs/afsincludes.h" /* Afs-based standard headers */
17 #include "../afs/afs_stats.h"   /* statistics gathering code */
18 #include "../afs/afs_cbqueue.h" 
19 #ifdef AFS_AIX_ENV
20 #include <sys/adspace.h>        /* for vm_att(), vm_det() */
21 #endif
22
23
24 /* background request queue size */
25 afs_lock_t afs_xbrs;            /* lock for brs */
26 static int brsInit = 0;
27 short afs_brsWaiters = 0;       /* number of users waiting for brs buffers */
28 short afs_brsDaemons = 0;       /* number of daemons waiting for brs requests */
29 struct brequest afs_brs[NBRS];  /* request structures */
30 struct afs_osi_WaitHandle AFS_WaitHandler, AFS_CSWaitHandler;
31 static int afs_brs_count = 0;   /* request counter, to service reqs in order */
32
33 static int rxepoch_checked=0;
34 #define afs_CheckRXEpoch() {if (rxepoch_checked == 0 && rxkad_EpochWasSet) { \
35         rxepoch_checked = 1; afs_GCUserData(/* force flag */ 1);  } }
36
37 /* PAG garbage collection */
38 /* We induce a compile error if param.h does not define AFS_GCPAGS */
39 afs_int32 afs_gcpags=AFS_GCPAGS;
40 afs_int32 afs_gcpags_procsize;
41
42 afs_int32 afs_CheckServerDaemonStarted = 0;
43 #ifdef DEFAULT_PROBE_INTERVAL
44 afs_int32 PROBE_INTERVAL=DEFAULT_PROBE_INTERVAL;  /* overridding during compile */
45 #else
46 afs_int32 PROBE_INTERVAL=180;   /* default to 3 min */
47 #endif
48
49 #define PROBE_WAIT() (1000 * (PROBE_INTERVAL - ((afs_random() & 0x7fffffff) \
50                       % (PROBE_INTERVAL/2))))
51
52 int afs_CheckServerDaemon(void)
53 {
54     afs_int32 now, delay, lastCheck, last10MinCheck;
55
56     afs_CheckServerDaemonStarted = 1;
57
58     while (afs_initState < 101) afs_osi_Sleep(&afs_initState);
59     afs_osi_Wait(PROBE_WAIT(), &AFS_CSWaitHandler, 0);  
60     
61     last10MinCheck = lastCheck = osi_Time();
62     while ( 1 ) {
63         if (afs_termState == AFSOP_STOP_CS) {
64             afs_termState = AFSOP_STOP_BKG;
65             afs_osi_Wakeup(&afs_termState);
66             break;
67         }
68
69         now = osi_Time();
70         if (PROBE_INTERVAL + lastCheck <= now) {
71             afs_CheckServers(1, NULL); /* check down servers */
72             lastCheck = now = osi_Time();
73         }
74
75         if (600 + last10MinCheck <= now) {
76             afs_Trace1(afs_iclSetp, CM_TRACE_PROBEUP, ICL_TYPE_INT32, 600);
77             afs_CheckServers(0, NULL);
78             last10MinCheck = now = osi_Time();
79         }
80         /* shutdown check. */
81         if (afs_termState == AFSOP_STOP_CS) {
82             afs_termState = AFSOP_STOP_BKG;
83             afs_osi_Wakeup(&afs_termState);
84             break;
85         }
86
87         /* Compute time to next probe. */
88         delay = PROBE_INTERVAL + lastCheck;
89         if (delay > 600 + last10MinCheck)
90             delay = 600 + last10MinCheck;
91         delay -= now;
92         if (delay < 1)
93             delay = 1;
94         afs_osi_Wait(delay * 1000,  &AFS_CSWaitHandler, 0);  
95     }
96     afs_CheckServerDaemonStarted = 0;
97 }
98
99 void afs_Daemon(void)
100 {
101     afs_int32 code;
102     struct afs_exporter *exporter;
103     afs_int32 now;
104     afs_int32 last3MinCheck, last10MinCheck, last60MinCheck, lastNMinCheck;
105     afs_int32 last1MinCheck;
106     afs_uint32 lastCBSlotBump;
107     char cs_warned = 0;
108
109     AFS_STATCNT(afs_Daemon);
110     last1MinCheck = last3MinCheck = last60MinCheck = last10MinCheck = lastNMinCheck = 0;
111
112     afs_rootFid.Fid.Volume = 0;
113     while (afs_initState < 101) afs_osi_Sleep(&afs_initState);
114
115     now = osi_Time();
116     lastCBSlotBump = now;
117
118     /* when a lot of clients are booted simultaneously, they develop
119      * annoying synchronous VL server bashing behaviors.  So we stagger them.
120      */
121     last1MinCheck = now + ((afs_random() & 0x7fffffff) % 60); /* an extra 30 */
122     last3MinCheck = now - 90 + ((afs_random() & 0x7fffffff) % 180);
123     last60MinCheck = now - 1800 + ((afs_random() & 0x7fffffff) % 3600);
124     last10MinCheck = now - 300 + ((afs_random() & 0x7fffffff) % 600);
125     lastNMinCheck = now - 90 + ((afs_random() & 0x7fffffff) % 180);
126
127     /* start off with afs_initState >= 101 (basic init done) */
128     while(1) {
129         afs_CheckCallbacks(20);  /* unstat anything which will expire soon */
130         
131         /* things to do every 20 seconds or less - required by protocol spec */
132         if (afs_nfsexporter) 
133             afs_FlushActiveVcaches(0);  /* flush NFS writes */
134         afs_FlushVCBs(1);               /* flush queued callbacks */
135         afs_MaybeWakeupTruncateDaemon();        /* free cache space if have too */
136         rx_CheckPackets();              /* Does RX need more packets? */
137 #if     defined(AFS_AIX32_ENV) || defined(AFS_HPUX_ENV)
138         /* 
139          * Hack: We always want to make sure there are plenty free
140          * entries in the small free pool so that we don't have to
141          * worry about rx (with disabled interrupts) to have to call
142          * malloc). So we do the dummy call below...
143          */
144         if (((afs_stats_cmperf.SmallBlocksAlloced - afs_stats_cmperf.SmallBlocksActive) 
145              <= AFS_SALLOC_LOW_WATER))
146             osi_FreeSmallSpace(osi_AllocSmallSpace(AFS_SMALLOCSIZ));
147         if (((afs_stats_cmperf.MediumBlocksAlloced - afs_stats_cmperf.MediumBlocksActive) 
148              <= AFS_MALLOC_LOW_WATER+50)) 
149             osi_AllocMoreMSpace(AFS_MALLOC_LOW_WATER * 2); 
150 #endif
151         
152         now = osi_Time();
153         if (lastCBSlotBump + CBHTSLOTLEN < now) {  /* pretty time-dependant */
154             lastCBSlotBump = now;
155             if (afs_BumpBase()) {
156                 afs_CheckCallbacks(20);  /* unstat anything which will expire soon */
157             }
158         }
159         
160         if (last1MinCheck + 60 < now) {
161             /* things to do every minute */
162             DFlush();                   /* write out dir buffers */
163             afs_WriteThroughDSlots();   /* write through cacheinfo entries */
164             afs_FlushActiveVcaches(1);/* keep flocks held & flush nfs writes */
165             afs_CheckRXEpoch();
166             last1MinCheck = now;
167         }
168         
169         if (last3MinCheck + 180 < now) {
170             afs_CheckTokenCache();      /* check for access cache resets due to expired
171                                            tickets */
172             last3MinCheck = now;
173         }
174         if (!afs_CheckServerDaemonStarted) {
175             /* Do the check here if the correct afsd is not installed. */
176             if (!cs_warned) {
177                 cs_warned = 1;
178                 printf("Please install afsd with check server daemon.\n");
179             }
180             if (lastNMinCheck + PROBE_INTERVAL < now) {
181                 /* only check down servers */
182                 afs_CheckServers(1, NULL);
183                 lastNMinCheck = now;
184             }
185         }
186         if (last10MinCheck + 600 < now) {
187 #ifdef AFS_USERSPACE_IP_ADDR    
188             extern int rxi_GetcbiInfo(void);
189 #endif
190             afs_Trace1(afs_iclSetp, CM_TRACE_PROBEUP,
191                        ICL_TYPE_INT32, 600);
192 #ifdef AFS_USERSPACE_IP_ADDR    
193             if (rxi_GetcbiInfo()) { /* addresses changed from last time */
194                 afs_FlushCBs();
195             }
196 #else  /* AFS_USERSPACE_IP_ADDR */
197             if (rxi_GetIFInfo()) { /* addresses changed from last time */
198                 afs_FlushCBs();
199             }
200 #endif /* else AFS_USERSPACE_IP_ADDR */
201             if (!afs_CheckServerDaemonStarted)
202                 afs_CheckServers(0, NULL);
203             afs_GCUserData(0);      /* gc old conns */
204             /* This is probably the wrong way of doing GC for the various exporters but it will suffice for a while */
205             for (exporter = root_exported; exporter; exporter = exporter->exp_next) {
206                 (void) EXP_GC(exporter, 0);     /* Generalize params */
207             }
208             {
209                 static int cnt=0;
210                 if (++cnt < 12) {
211                     afs_CheckVolumeNames(AFS_VOLCHECK_EXPIRED |
212                                          AFS_VOLCHECK_BUSY);
213                 } else {
214                     cnt = 0;
215                     afs_CheckVolumeNames(AFS_VOLCHECK_EXPIRED |
216                                          AFS_VOLCHECK_BUSY |
217                                          AFS_VOLCHECK_MTPTS);
218                 }
219             }
220             last10MinCheck = now;
221         }
222         if (last60MinCheck + 3600 < now) {
223             afs_Trace1(afs_iclSetp, CM_TRACE_PROBEVOLUME,
224                        ICL_TYPE_INT32, 3600);
225             afs_CheckRootVolume();
226 #if AFS_GCPAGS
227             if (afs_gcpags == AFS_GCPAGS_OK) {
228                 afs_int32 didany;
229                 afs_GCPAGs(&didany);
230             }
231 #endif
232             last60MinCheck = now;
233         }
234         if (afs_initState < 300) {      /* while things ain't rosy */
235             code = afs_CheckRootVolume();
236             if (code == 0) afs_initState = 300;             /* succeeded */
237             if (afs_initState < 200) afs_initState = 200;   /* tried once */
238             afs_osi_Wakeup(&afs_initState);
239         }
240         
241         /* 18285 is because we're trying to divide evenly into 128, that is,
242          * CBSlotLen, while staying just under 20 seconds.  If CBSlotLen
243          * changes, should probably change this interval, too. 
244          * Some of the preceding actions may take quite some time, so we
245          * might not want to wait the entire interval */
246         now = 18285 - (osi_Time() - now);
247         if (now > 0) {
248             afs_osi_Wait(now, &AFS_WaitHandler, 0);  
249         }
250         
251         if (afs_termState == AFSOP_STOP_AFS) {
252             if (afs_CheckServerDaemonStarted)
253                 afs_termState = AFSOP_STOP_CS;
254             else
255                 afs_termState = AFSOP_STOP_BKG;
256             afs_osi_Wakeup(&afs_termState);
257             return;
258         }
259     }
260 }
261
262 int afs_CheckRootVolume (void)
263 {
264     char rootVolName[32];
265     register struct volume *tvp;
266     int usingDynroot = afs_GetDynrootEnable();
267
268     AFS_STATCNT(afs_CheckRootVolume);
269     if (*afs_rootVolumeName == 0) {
270         strcpy(rootVolName, "root.afs");
271     }
272     else {
273         strcpy(rootVolName, afs_rootVolumeName);
274     }
275     if (usingDynroot) {
276         afs_GetDynrootFid(&afs_rootFid);
277         tvp = afs_GetVolume(&afs_rootFid, NULL, READ_LOCK);
278     } else {
279         tvp = afs_GetVolumeByName(rootVolName, LOCALCELL, 1, NULL, READ_LOCK);
280     }
281     if (!tvp) {
282         char buf[128];
283         int len = strlen(rootVolName);
284
285         if ((len < 9) || strcmp(&rootVolName[len - 9], ".readonly")) {
286             strcpy(buf, rootVolName);
287             afs_strcat(buf, ".readonly");
288             tvp = afs_GetVolumeByName(buf, LOCALCELL, 1, NULL, READ_LOCK);
289         }
290     }
291     if (tvp) {
292         if (!usingDynroot) {
293             int volid = (tvp->roVol? tvp->roVol : tvp->volume);
294             afs_rootFid.Cell = LOCALCELL;
295             if (afs_rootFid.Fid.Volume && afs_rootFid.Fid.Volume != volid
296                 && afs_globalVp) {
297                 /* If we had a root fid before and it changed location we reset
298                  * the afs_globalVp so that it will be reevaluated.
299                  * Just decrement the reference count. This only occurs during
300                  * initial cell setup and can panic the machine if we set the
301                  * count to zero and fs checkv is executed when the current
302                  * directory is /afs.
303                  */
304                 AFS_FAST_RELE(afs_globalVp);
305                 afs_globalVp = 0;
306             }
307             afs_rootFid.Fid.Volume = volid;
308             afs_rootFid.Fid.Vnode = 1;
309             afs_rootFid.Fid.Unique = 1;
310         }
311         afs_initState = 300;    /* won */
312         afs_osi_Wakeup(&afs_initState);
313         afs_PutVolume(tvp, READ_LOCK);
314     }
315 #ifdef AFS_DEC_ENV
316 /* This is to make sure that we update the root gnode */
317 /* every time root volume gets released */
318     {
319         struct gnode *rootgp;
320         struct mount *mp;
321         int code;
322
323         /* Only do this if afs_globalVFS is properly set due to race conditions
324            this routine could be called before the gfs_mount is performed!
325            Furthermore, afs_root (called below) *waits* until
326            initState >= 200, so we don't try this until we've gotten
327            at least that far */
328         if (afs_globalVFS && afs_initState >= 200) {
329             if (code = afs_root(afs_globalVFS, &rootgp))
330                 return code;
331             mp = (struct mount *) afs_globalVFS->vfs_data ;
332             mp->m_rootgp = gget(mp, 0, 0, (char *)rootgp);
333             afs_unlock(mp->m_rootgp);   /* unlock basic gnode */
334             afs_vrele(VTOAFS(rootgp));  /* zap afs_root's vnode hold */
335         }
336     }
337 #endif
338     if (afs_rootFid.Fid.Volume) return 0;
339     else return ENOENT;
340 }
341
342 /* ptr_parm 0 is the pathname, size_parm 0 to the fetch is the chunk number */
343 static void BPath(register struct brequest *ab)
344 {
345     register struct dcache *tdc = NULL;
346     struct vcache *tvc = NULL;
347     struct vnode *tvn = NULL;
348 #ifdef AFS_LINUX22_ENV
349     struct dentry *dp = NULL;
350 #endif
351     afs_size_t offset, len;
352     struct vrequest treq;
353     afs_int32 code;
354
355     AFS_STATCNT(BPath);
356     if ((code = afs_InitReq(&treq, ab->cred))) return;
357     AFS_GUNLOCK();
358 #ifdef AFS_LINUX22_ENV
359     code = gop_lookupname((char *)ab->ptr_parm[0], AFS_UIOSYS, 1,  NULL, &dp);
360     if (dp)
361         tvn = (struct vnode*)dp->d_inode;
362 #else
363     code = gop_lookupname((char *)ab->ptr_parm[0], AFS_UIOSYS, 1,  NULL, (struct vnode **)&tvn);
364 #endif
365     AFS_GLOCK();
366     osi_FreeLargeSpace((char *)ab->ptr_parm[0]); /* free path name buffer here */
367     if (code) return;
368     /* now path may not have been in afs, so check that before calling our cache manager */
369     if (!tvn || !IsAfsVnode((struct vnode *) tvn)) {
370         /* release it and give up */
371         if (tvn) {
372 #ifdef AFS_DEC_ENV
373             grele(tvn);
374 #else
375 #ifdef AFS_LINUX22_ENV
376             dput(dp);
377 #else
378             AFS_RELE((struct vnode *) tvn);
379 #endif
380 #endif
381         }
382         return;
383     }
384 #ifdef AFS_DEC_ENV
385     tvc = VTOAFS(afs_gntovn(tvn));
386 #else
387     tvc = VTOAFS(tvn);
388 #endif
389     /* here we know its an afs vnode, so we can get the data for the chunk */
390     tdc = afs_GetDCache(tvc, ab->size_parm[0], &treq, &offset, &len, 1);
391     if (tdc) {
392         afs_PutDCache(tdc);
393     }
394 #ifdef AFS_DEC_ENV
395     grele(tvn);
396 #else
397 #ifdef AFS_LINUX22_ENV
398     dput(dp);
399 #else
400     AFS_RELE((struct vnode *) tvn);
401 #endif
402 #endif
403 }
404
405 /* size_parm 0 to the fetch is the chunk number,
406  * ptr_parm 0 is the dcache entry to wakeup,
407  * size_parm 1 is true iff we should release the dcache entry here.
408  */
409 static void BPrefetch(register struct brequest *ab)
410 {
411     register struct dcache *tdc;
412     register struct vcache *tvc;
413     afs_size_t offset, len;
414     struct vrequest treq;
415
416     AFS_STATCNT(BPrefetch);
417     if ((len = afs_InitReq(&treq, ab->cred))) return;
418     tvc = ab->vnode;
419     tdc = afs_GetDCache(tvc, ab->size_parm[0], &treq, &offset, &len, 1);
420     if (tdc) {
421         afs_PutDCache(tdc);
422     }
423     /* now, dude may be waiting for us to clear DFFetchReq bit; do so.  Can't
424      * use tdc from GetDCache since afs_GetDCache may fail, but someone may
425      * be waiting for our wakeup anyway.
426      */
427     tdc = (struct dcache *) (ab->ptr_parm[0]);
428     ObtainSharedLock(&tdc->lock, 640);
429     if (tdc->mflags & DFFetchReq) {
430         UpgradeSToWLock(&tdc->lock, 641);
431         tdc->mflags &= ~DFFetchReq;
432         ReleaseWriteLock(&tdc->lock);
433     } else {
434         ReleaseSharedLock(&tdc->lock);
435     }
436     afs_osi_Wakeup(&tdc->validPos);
437     if (ab->size_parm[1]) {
438         afs_PutDCache(tdc);     /* put this one back, too */
439     }
440 }
441
442
443 static void BStore(register struct brequest *ab)
444 {
445     register struct vcache *tvc;
446     register afs_int32 code;
447     struct vrequest treq;
448 #if defined(AFS_SGI_ENV)
449     struct cred *tmpcred;
450 #endif
451
452     AFS_STATCNT(BStore);
453     if ((code = afs_InitReq(&treq, ab->cred))) return;
454     code = 0;
455     tvc = ab->vnode;
456 #if defined(AFS_SGI_ENV)
457     /*
458      * Since StoreOnLastReference can end up calling osi_SyncVM which
459      * calls into VM code that assumes that u.u_cred has the
460      * correct credentials, we set our to theirs for this xaction
461      */
462     tmpcred = OSI_GET_CURRENT_CRED();
463     OSI_SET_CURRENT_CRED(ab->cred);
464
465     /*
466      * To avoid recursion since the WriteLock may be released during VM
467      * operations, we hold the VOP_RWLOCK across this transaction as
468      * do the other callers of StoreOnLastReference
469      */
470     AFS_RWLOCK((vnode_t *)tvc, 1);
471 #endif
472     ObtainWriteLock(&tvc->lock,209);
473     code = afs_StoreOnLastReference(tvc, &treq);
474     ReleaseWriteLock(&tvc->lock);
475 #if defined(AFS_SGI_ENV)
476     OSI_SET_CURRENT_CRED(tmpcred);
477     AFS_RWUNLOCK((vnode_t *)tvc, 1);
478 #endif
479     /* now set final return code, and wakeup anyone waiting */
480     if ((ab->flags & BUVALID) == 0) {
481         ab->code = afs_CheckCode(code, &treq, 43);    /* set final code, since treq doesn't go across processes */
482         ab->flags |= BUVALID;
483         if (ab->flags & BUWAIT) {
484             ab->flags &= ~BUWAIT;
485             afs_osi_Wakeup(ab);
486         }
487     }
488 }
489
490 /* release a held request buffer */
491 void afs_BRelease(register struct brequest *ab)
492 {
493
494     AFS_STATCNT(afs_BRelease);
495     MObtainWriteLock(&afs_xbrs,294);
496     if (--ab->refCount <= 0) {
497         ab->flags = 0;
498     }
499     if (afs_brsWaiters) afs_osi_Wakeup(&afs_brsWaiters);
500     MReleaseWriteLock(&afs_xbrs);
501 }
502
503 /* return true if bkg fetch daemons are all busy */
504 int afs_BBusy(void)
505 {
506     AFS_STATCNT(afs_BBusy);
507     if (afs_brsDaemons > 0) return 0;
508     return 1;
509 }
510
511 struct brequest *afs_BQueue(register short aopcode, register struct vcache *avc, 
512         afs_int32 dontwait, afs_int32 ause, struct AFS_UCRED *acred, 
513         afs_size_t asparm0, afs_size_t asparm1, void *apparm0)
514 {
515     register int i;
516     register struct brequest *tb;
517
518     AFS_STATCNT(afs_BQueue);
519     MObtainWriteLock(&afs_xbrs,296);
520     while (1) {
521         tb = afs_brs;
522         for(i=0;i<NBRS;i++,tb++) {
523             if (tb->refCount == 0) break;
524         }
525         if (i < NBRS) {
526             /* found a buffer */
527             tb->opcode = aopcode;
528             tb->vnode = avc;
529             tb->cred = acred;
530             crhold(tb->cred);
531             if (avc) {
532 #ifdef  AFS_DEC_ENV
533                 avc->vrefCount++;
534 #else
535                 VN_HOLD(AFSTOV(avc));
536 #endif
537             }
538             tb->refCount = ause+1;
539             tb->size_parm[0] = asparm0;
540             tb->size_parm[1] = asparm1;
541             tb->ptr_parm[0]  = apparm0;
542             tb->flags = 0;
543             tb->code = 0;
544             tb->ts = afs_brs_count++;
545             /* if daemons are waiting for work, wake them up */
546             if (afs_brsDaemons > 0) {
547                 afs_osi_Wakeup(&afs_brsDaemons);
548             }
549             MReleaseWriteLock(&afs_xbrs);
550             return tb;
551         }
552         if (dontwait) {
553             MReleaseWriteLock(&afs_xbrs);
554             return NULL;
555         }
556         /* no free buffers, sleep a while */
557         afs_brsWaiters++;
558         MReleaseWriteLock(&afs_xbrs);
559         afs_osi_Sleep(&afs_brsWaiters);
560         MObtainWriteLock(&afs_xbrs,301);
561         afs_brsWaiters--;
562     }
563 }
564
565 #ifdef  AFS_AIX32_ENV
566 #ifdef AFS_AIX41_ENV
567 /* AIX 4.1 has a much different sleep/wakeup mechanism available for use. 
568  * The modifications here will work for either a UP or MP machine.
569  */
570 struct buf *afs_asyncbuf = (struct buf*)0;
571 afs_int32 afs_asyncbuf_cv = EVENT_NULL;
572 afs_int32 afs_biodcnt = 0;
573
574 /* in implementing this, I assumed that all external linked lists were
575  * null-terminated.  
576  *
577  * Several places in this code traverse a linked list.  The algorithm
578  * used here is probably unfamiliar to most people.  Careful examination
579  * will show that it eliminates an assignment inside the loop, as compared
580  * to the standard algorithm, at the cost of occasionally using an extra
581  * variable.
582  */
583
584 /* get_bioreq()
585  *
586  * This function obtains, and returns, a pointer to a buffer for
587  * processing by a daemon.  It sleeps until such a buffer is available.
588  * The source of buffers for it is the list afs_asyncbuf (see also 
589  * naix_vm_strategy).  This function may be invoked concurrently by
590  * several processes, that is, several instances of the same daemon.
591  * naix_vm_strategy, which adds buffers to the list, runs at interrupt
592  * level, while get_bioreq runs at process level.
593  *
594  * Since AIX 4.1 can wake just one process at a time, the separate sleep
595  * addresses have been removed.
596  * Note that the kernel_lock is held until the e_sleep_thread() occurs. 
597  * The afs_asyncbuf_lock is primarily used to serialize access between
598  * process and interrupts.
599  */
600 Simple_lock afs_asyncbuf_lock;
601 /*static*/ struct buf *afs_get_bioreq()
602 {
603     struct buf *bp = NULL;
604     struct buf *bestbp;
605     struct buf **bestlbpP, **lbpP;
606     int bestage, stop;
607     struct buf *t1P, *t2P;      /* temp pointers for list manipulation */
608     int oldPriority;
609     afs_uint32 wait_ret;
610     struct afs_bioqueue *s;
611
612     /* ??? Does the forward pointer of the returned buffer need to be NULL?
613     */
614     
615     /* Disable interrupts from the strategy function, and save the 
616      * prior priority level and lock access to the afs_asyncbuf.
617      */
618     AFS_GUNLOCK();
619     oldPriority = disable_lock(INTMAX, &afs_asyncbuf_lock) ;
620
621     while(1) {
622         if (afs_asyncbuf) {
623             /* look for oldest buffer */
624             bp = bestbp = afs_asyncbuf;
625             bestage = (int) bestbp->av_back;
626             bestlbpP = &afs_asyncbuf;
627             while (1) {
628                 lbpP = &bp->av_forw;
629                 bp = *lbpP;
630                 if (!bp) break;
631                 if ((int) bp->av_back - bestage < 0) {
632                     bestbp = bp;
633                     bestlbpP = lbpP;
634                     bestage = (int) bp->av_back;
635                 }
636             }
637             bp = bestbp;
638             *bestlbpP = bp->av_forw;
639             break;
640         }
641         else {
642             /* If afs_asyncbuf is null, it is necessary to go to sleep.
643              * e_wakeup_one() ensures that only one thread wakes.
644              */
645             int interrupted;
646             /* The LOCK_HANDLER indicates to e_sleep_thread to only drop the
647              * lock on an MP machine.
648              */
649             interrupted = e_sleep_thread(&afs_asyncbuf_cv,
650                                          &afs_asyncbuf_lock,
651                                          LOCK_HANDLER|INTERRUPTIBLE);
652             if (interrupted==THREAD_INTERRUPTED) {
653                 /* re-enable interrupts from strategy */
654                 unlock_enable(oldPriority, &afs_asyncbuf_lock);
655                 AFS_GLOCK();
656                 return(NULL);
657             }
658         }  /* end of "else asyncbuf is empty" */
659     } /* end of "inner loop" */
660     
661     /*assert (bp);*/
662     
663     unlock_enable(oldPriority, &afs_asyncbuf_lock);
664     AFS_GLOCK();
665
666     /* For the convenience of other code, replace the gnodes in
667      * the b_vp field of bp and the other buffers on the b_work
668      * chain with the corresponding vnodes.   
669      *
670      * ??? what happens to the gnodes?  They're not just cut loose,
671      * are they?
672      */
673     for(t1P=bp;;) {
674         t2P = (struct buf *) t1P->b_work;
675         t1P->b_vp = ((struct gnode *) t1P->b_vp)->gn_vnode;
676         if (!t2P) 
677             break;
678
679         t1P = (struct buf *) t2P->b_work;
680         t2P->b_vp = ((struct gnode *) t2P->b_vp)->gn_vnode;
681         if (!t1P)
682             break;
683     }
684
685     /* If the buffer does not specify I/O, it may immediately
686      * be returned to the caller.  This condition is detected
687      * by examining the buffer's flags (the b_flags field).  If
688      * the B_PFPROT bit is set, the buffer represents a protection
689      * violation, rather than a request for I/O.  The remainder
690      * of the outer loop handles the case where the B_PFPROT bit is clear.
691      */
692     if (bp->b_flags & B_PFPROT)  {
693         return (bp);
694     }
695     return (bp);
696
697 } /* end of function get_bioreq() */
698
699
700 /* afs_BioDaemon
701  *
702  * This function is the daemon.  It is called from the syscall
703  * interface.  Ordinarily, a script or an administrator will run a
704  * daemon startup utility, specifying the number of I/O daemons to
705  * run.  The utility will fork off that number of processes,
706  * each making the appropriate syscall, which will cause this
707  * function to be invoked.
708  */
709 static int afs_initbiod = 0;            /* this is self-initializing code */
710 int DOvmlock = 0;
711 int afs_BioDaemon (afs_int32 nbiods)
712 {
713     afs_int32 code, s, pflg = 0;
714     label_t jmpbuf;
715     struct buf *bp, *bp1, *tbp1, *tbp2;         /* temp pointers only */
716     caddr_t tmpaddr;
717     struct vnode *vp;
718     struct vcache *vcp;
719     char tmperr;
720     if (!afs_initbiod) {
721         /* XXX ###1 XXX */
722         afs_initbiod = 1;
723         /* pin lock, since we'll be using it in an interrupt. */
724         lock_alloc(&afs_asyncbuf_lock, LOCK_ALLOC_PIN, 2, 1);
725         simple_lock_init(&afs_asyncbuf_lock);
726         pin (&afs_asyncbuf, sizeof(struct buf*));
727         pin (&afs_asyncbuf_cv, sizeof(afs_int32));
728     }
729
730     /* Ignore HUP signals... */
731     {
732         sigset_t sigbits, osigbits;
733         /*
734          * add SIGHUP to the set of already masked signals
735          */
736         SIGFILLSET(sigbits);                    /* allow all signals    */
737         SIGDELSET(sigbits, SIGHUP);             /*   except SIGHUP      */
738         limit_sigs(&sigbits, &osigbits);        /*   and already masked */
739     }
740     /* Main body starts here -- this is an intentional infinite loop, and
741      * should NEVER exit 
742      *
743      * Now, the loop will exit if get_bioreq() returns NULL, indicating 
744      * that we've been interrupted.
745      */
746     while (1) {
747         bp = afs_get_bioreq();
748         if (!bp)
749             break;      /* we were interrupted */
750         if (code = setjmpx(&jmpbuf)) {
751             /* This should not have happend, maybe a lack of resources  */
752             AFS_GUNLOCK();
753             s = disable_lock(INTMAX, &afs_asyncbuf_lock);
754             for (bp1 = bp; bp ; bp = bp1) {
755                 if (bp1)
756                     bp1 = (struct buf *) bp1->b_work;
757                 bp->b_actf = 0;
758                 bp->b_error = code;
759                 bp->b_flags |= B_ERROR;
760                 iodone(bp);
761             }
762             unlock_enable(s, &afs_asyncbuf_lock);
763             AFS_GLOCK();
764             continue;
765         }
766         vcp = VTOAFS(bp->b_vp);
767         if (bp->b_flags & B_PFSTORE) {  /* XXXX */
768             ObtainWriteLock(&vcp->lock,404);        
769             if (vcp->v.v_gnode->gn_mwrcnt) {
770                 afs_offs_t newlength = 
771                         (afs_offs_t) dbtob(bp->b_blkno) + bp->b_bcount;
772                 if (vcp->m.Length < newlength) {
773                     afs_Trace4(afs_iclSetp, CM_TRACE_SETLENGTH,
774                         ICL_TYPE_STRING, __FILE__,
775                         ICL_TYPE_LONG, __LINE__,
776                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(vcp->m.Length),
777                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(newlength));
778                     vcp->m.Length = newlength;
779                 }
780             }
781             ReleaseWriteLock(&vcp->lock);
782         }
783         /* If the buffer represents a protection violation, rather than
784          * an actual request for I/O, no special action need be taken.  
785          */
786         if ( bp->b_flags & B_PFPROT ) {   
787             iodone (bp);    /* Notify all users of the buffer that we're done */
788             clrjmpx(&jmpbuf);
789             continue;
790         }
791 if (DOvmlock)
792         ObtainWriteLock(&vcp->pvmlock,211);     
793         /*
794          * First map its data area to a region in the current address space
795          * by calling vm_att with the subspace identifier, and a pointer to
796          * the data area.  vm_att returns  a new data area pointer, but we
797          * also want to hang onto the old one.
798          */
799         tmpaddr = bp->b_baddr;
800         bp->b_baddr = vm_att (bp->b_xmemd.subspace_id, tmpaddr);
801         tmperr = afs_ustrategy(bp);     /* temp variable saves offset calculation */
802         if (tmperr) {                   /* in non-error case */
803             bp->b_flags |= B_ERROR;             /* should other flags remain set ??? */
804             bp->b_error = tmperr;
805         }
806
807         /* Unmap the buffer's data area by calling vm_det.  Reset data area
808          * to the value that we saved above.
809          */
810         vm_det(bp->b_un.b_addr);
811         bp->b_baddr = tmpaddr;
812
813         /*
814          * buffer may be linked with other buffers via the b_work field.
815          * See also naix_vm_strategy.  For each buffer in the chain (including
816          * bp) notify all users of the buffer that the daemon is finished
817          * using it by calling iodone.  
818          * assumes iodone can modify the b_work field.
819          */
820         for(tbp1=bp;;) {
821             tbp2 = (struct buf *) tbp1->b_work;
822             iodone(tbp1);
823             if (!tbp2) 
824                 break;
825
826             tbp1 = (struct buf *) tbp2->b_work;
827             iodone(tbp2);
828             if (!tbp1)
829                 break;
830         }
831 if (DOvmlock)
832         ReleaseWriteLock(&vcp->pvmlock);     /* Unlock the vnode.  */
833         clrjmpx(&jmpbuf);
834     } /* infinite loop (unless we're interrupted) */
835 } /* end of afs_BioDaemon() */
836
837 #else /* AFS_AIX41_ENV */
838
839
840 #define squeue afs_q
841 struct afs_bioqueue {
842     struct squeue lruq;
843     int sleeper;
844     int cnt;
845 };
846 struct afs_bioqueue afs_bioqueue;
847 struct buf *afs_busyq = NULL;
848 struct buf *afs_asyncbuf;
849 afs_int32 afs_biodcnt = 0;
850
851 /* in implementing this, I assumed that all external linked lists were
852  * null-terminated.  
853  *
854  * Several places in this code traverse a linked list.  The algorithm
855  * used here is probably unfamiliar to most people.  Careful examination
856  * will show that it eliminates an assignment inside the loop, as compared
857  * to the standard algorithm, at the cost of occasionally using an extra
858  * variable.
859  */
860
861 /* get_bioreq()
862  *
863  * This function obtains, and returns, a pointer to a buffer for
864  * processing by a daemon.  It sleeps until such a buffer is available.
865  * The source of buffers for it is the list afs_asyncbuf (see also 
866  * naix_vm_strategy).  This function may be invoked concurrently by
867  * several processes, that is, several instances of the same daemon.
868  * naix_vm_strategy, which adds buffers to the list, runs at interrupt
869  * level, while get_bioreq runs at process level.
870  *
871  * The common kernel paradigm of sleeping and waking up, in which all the
872  * competing processes sleep waiting for wakeups on one address, is not
873  * followed here.  Instead, the following paradigm is used:  when a daemon
874  * goes to sleep, it checks for other sleeping daemons.  If there aren't any,
875  * it sleeps on the address of variable afs_asyncbuf.  But if there is
876  * already a daemon sleeping on that address, it threads its own unique
877  * address onto a list, and sleeps on that address.  This way, every 
878  * sleeper is sleeping on a different address, and every wakeup wakes up
879  * exactly one daemon.  This prevents a whole bunch of daemons from waking
880  * up and then immediately having to go back to sleep.  This provides a
881  * performance gain and makes the I/O scheduling a bit more deterministic.
882  * The list of sleepers is variable afs_bioqueue.  The unique address
883  * on which to sleep is passed to get_bioreq as its parameter.
884  */
885 /*static*/ struct buf *afs_get_bioreq(self)
886     struct afs_bioqueue *self;      /* address on which to sleep */
887
888 {
889     struct buf *bp = NULL;
890     struct buf *bestbp;
891     struct buf **bestlbpP, **lbpP;
892     int bestage, stop;
893     struct buf *t1P, *t2P;      /* temp pointers for list manipulation */
894     int oldPriority;
895     afs_uint32 wait_ret;
896 struct afs_bioqueue *s;
897
898     /* ??? Does the forward pointer of the returned buffer need to be NULL?
899     */
900     
901         /* Disable interrupts from the strategy function, and save the 
902          * prior priority level
903          */
904         oldPriority = i_disable ( INTMAX ) ;
905
906         /* Each iteration of following loop either pulls
907          * a buffer off afs_asyncbuf, or sleeps.  
908          */
909         while (1) {   /* inner loop */
910                 if (afs_asyncbuf) {
911                         /* look for oldest buffer */
912                         bp = bestbp = afs_asyncbuf;
913                         bestage = (int) bestbp->av_back;
914                         bestlbpP = &afs_asyncbuf;
915                         while (1) {
916                                 lbpP = &bp->av_forw;
917                                 bp = *lbpP;
918                                 if (!bp) break;
919                                 if ((int) bp->av_back - bestage < 0) {
920                                         bestbp = bp;
921                                         bestlbpP = lbpP;
922                                         bestage = (int) bp->av_back;
923                                 }
924                         }
925                         bp = bestbp;
926                         *bestlbpP = bp->av_forw;
927                         break;  
928                         }
929                 else {
930                         int interrupted;
931
932                 /* If afs_asyncbuf is null, it is necessary to go to sleep.
933                  * There are two possibilities:  either there is already a
934                  * daemon that is sleeping on the address of afs_asyncbuf,
935                  * or there isn't. 
936                  */
937                         if (afs_bioqueue.sleeper) {
938                                 /* enqueue */
939                                 QAdd (&(afs_bioqueue.lruq), &(self->lruq));
940                                 interrupted = sleep ((caddr_t) self, PCATCH|(PZERO + 1));
941                                 if (self->lruq.next != &self->lruq) {   /* XXX ##3 XXX */
942                                     QRemove (&(self->lruq));            /* dequeue */
943                                 }
944 self->cnt++;
945                                 afs_bioqueue.sleeper = FALSE;
946                                 if (interrupted) {
947                                     /* re-enable interrupts from strategy */
948                                     i_enable (oldPriority);
949                                     return(NULL);
950                                 }
951                                 continue;
952                         } else {
953                                 afs_bioqueue.sleeper = TRUE;
954                                 interrupted = sleep ((caddr_t) &afs_asyncbuf, PCATCH|(PZERO + 1));
955                                 afs_bioqueue.sleeper = FALSE;
956                                 if (interrupted)
957                                 {
958                                     /*
959                                      * We need to wakeup another daemon if present
960                                      * since we were waiting on afs_asyncbuf.
961                                      */
962 #ifdef  notdef  /* The following doesn't work as advertised */                              
963                                      if (afs_bioqueue.lruq.next != &afs_bioqueue.lruq)
964                                      {
965                                          struct squeue *bq = afs_bioqueue.lruq.next;
966                                          QRemove (bq);
967                                          wakeup (bq);
968                                      }
969 #endif
970                                     /* re-enable interrupts from strategy */
971                                      i_enable (oldPriority);
972                                      return(NULL);
973                                  }
974                                 continue;
975                                 }
976
977                         }  /* end of "else asyncbuf is empty" */
978                 } /* end of "inner loop" */
979
980         /*assert (bp);*/
981
982         i_enable (oldPriority);     /* re-enable interrupts from strategy */
983
984         /* For the convenience of other code, replace the gnodes in
985          * the b_vp field of bp and the other buffers on the b_work
986          * chain with the corresponding vnodes.   
987          *
988          * ??? what happens to the gnodes?  They're not just cut loose,
989          * are they?
990          */
991         for(t1P=bp;;) {
992                 t2P = (struct buf *) t1P->b_work;
993                 t1P->b_vp = ((struct gnode *) t1P->b_vp)->gn_vnode;
994                 if (!t2P) 
995                         break;
996
997                 t1P = (struct buf *) t2P->b_work;
998                 t2P->b_vp = ((struct gnode *) t2P->b_vp)->gn_vnode;
999                 if (!t1P)
1000                         break;
1001                 }
1002
1003         /* If the buffer does not specify I/O, it may immediately
1004          * be returned to the caller.  This condition is detected
1005          * by examining the buffer's flags (the b_flags field).  If
1006          * the B_PFPROT bit is set, the buffer represents a protection
1007          * violation, rather than a request for I/O.  The remainder
1008          * of the outer loop handles the case where the B_PFPROT bit is clear.
1009          */
1010          if (bp->b_flags & B_PFPROT)  {
1011                 return (bp);
1012             }
1013
1014         /* wake up another process to handle the next buffer, and return
1015          * bp to the caller.
1016          */
1017         oldPriority = i_disable ( INTMAX ) ;
1018
1019         /* determine where to find the sleeping process. 
1020          * There are two cases: either it is sleeping on
1021          * afs_asyncbuf, or it is sleeping on its own unique
1022          * address.  These cases are distinguished by examining
1023          * the sleeper field of afs_bioqueue.
1024          */
1025         if (afs_bioqueue.sleeper) {
1026                 wakeup (&afs_asyncbuf);
1027                 }
1028         else {
1029                 if (afs_bioqueue.lruq.next == &afs_bioqueue.lruq) {
1030                         /* queue is empty, what now? ???*/
1031                         /* Should this be impossible, or does    */
1032                         /* it just mean that nobody is sleeping? */;
1033                         }
1034                 else {
1035                         struct squeue *bq = afs_bioqueue.lruq.next;
1036                         QRemove (bq);
1037                         QInit (bq);
1038                         wakeup (bq);
1039                         afs_bioqueue.sleeper = TRUE; 
1040                         }
1041                 }
1042         i_enable (oldPriority);     /* re-enable interrupts from strategy */
1043         return (bp);
1044
1045 } /* end of function get_bioreq() */
1046
1047
1048 /* afs_BioDaemon
1049  *
1050  * This function is the daemon.  It is called from the syscall
1051  * interface.  Ordinarily, a script or an administrator will run a
1052  * daemon startup utility, specifying the number of I/O daemons to
1053  * run.  The utility will fork off that number of processes,
1054  * each making the appropriate syscall, which will cause this
1055  * function to be invoked.
1056  */
1057 static int afs_initbiod = 0;            /* this is self-initializing code */
1058 int DOvmlock = 0;
1059 afs_BioDaemon (nbiods)
1060     afs_int32 nbiods;
1061 {
1062     struct afs_bioqueue *self;
1063     afs_int32 code, s, pflg = 0;
1064     label_t jmpbuf;
1065     struct buf *bp, *bp1, *tbp1, *tbp2;         /* temp pointers only */
1066     caddr_t tmpaddr;
1067     struct vnode *vp;
1068     struct vcache *vcp;
1069     char tmperr;
1070     if (!afs_initbiod) {
1071         /* XXX ###1 XXX */
1072         afs_initbiod = 1;
1073         /* Initialize the queue of waiting processes, afs_bioqueue.  */
1074         QInit (&(afs_bioqueue.lruq));           
1075     }
1076
1077     /* establish ourself as a kernel process so shutdown won't kill us */
1078 /*    u.u_procp->p_flag |= SKPROC;*/
1079
1080     /* Initialize a token (self) to use in the queue of sleeping processes.   */
1081     self = (struct afs_bioqueue *) afs_osi_Alloc (sizeof (struct afs_bioqueue));
1082     pin (self, sizeof (struct afs_bioqueue)); /* fix in memory */
1083     memset(self, 0, sizeof(*self));
1084     QInit (&(self->lruq));              /* initialize queue entry pointers */
1085
1086
1087     /* Ignore HUP signals... */
1088     SIGDELSET(u.u_procp->p_sig, SIGHUP);
1089     SIGADDSET(u.u_procp->p_sigignore, SIGHUP);
1090     SIGDELSET(u.u_procp->p_sigcatch, SIGHUP);
1091     /* Main body starts here -- this is an intentional infinite loop, and
1092      * should NEVER exit 
1093      *
1094      * Now, the loop will exit if get_bioreq() returns NULL, indicating 
1095      * that we've been interrupted.
1096      */
1097     while (1) {
1098         bp = afs_get_bioreq(self);
1099         if (!bp)
1100             break;      /* we were interrupted */
1101         if (code = setjmpx(&jmpbuf)) {
1102             /* This should not have happend, maybe a lack of resources  */
1103             s = splimp();
1104             for (bp1 = bp; bp ; bp = bp1) {
1105                 if (bp1)
1106                     bp1 = bp1->b_work;
1107                 bp->b_actf = 0;
1108                 bp->b_error = code;
1109                 bp->b_flags |= B_ERROR;
1110                 iodone(bp);
1111             }
1112             splx(s);
1113             continue;
1114         }
1115         vcp = VTOAFS(bp->b_vp);
1116         if (bp->b_flags & B_PFSTORE) {
1117             ObtainWriteLock(&vcp->lock,210);        
1118             if (vcp->v.v_gnode->gn_mwrcnt) {
1119                 if (vcp->m.Length < bp->b_bcount + (u_int)dbtob(bp->b_blkno))
1120                     vcp->m.Length = bp->b_bcount + (u_int)dbtob(bp->b_blkno);
1121             }
1122             ReleaseWriteLock(&vcp->lock);
1123         }
1124         /* If the buffer represents a protection violation, rather than
1125          * an actual request for I/O, no special action need be taken.  
1126          */
1127         if ( bp->b_flags & B_PFPROT ) {   
1128             iodone (bp);    /* Notify all users of the buffer that we're done */
1129             continue;
1130         }
1131 if (DOvmlock)
1132         ObtainWriteLock(&vcp->pvmlock,558);     
1133         /*
1134          * First map its data area to a region in the current address space
1135          * by calling vm_att with the subspace identifier, and a pointer to
1136          * the data area.  vm_att returns  a new data area pointer, but we
1137          * also want to hang onto the old one.
1138          */
1139         tmpaddr = bp->b_baddr;
1140         bp->b_baddr = vm_att (bp->b_xmemd.subspace_id, tmpaddr);
1141         tmperr = afs_ustrategy(bp);     /* temp variable saves offset calculation */
1142         if (tmperr) {                   /* in non-error case */
1143             bp->b_flags |= B_ERROR;             /* should other flags remain set ??? */
1144             bp->b_error = tmperr;
1145         }
1146
1147         /* Unmap the buffer's data area by calling vm_det.  Reset data area
1148          * to the value that we saved above.
1149          */
1150         vm_det(bp->b_un.b_addr);
1151         bp->b_baddr = tmpaddr;
1152
1153         /*
1154          * buffer may be linked with other buffers via the b_work field.
1155          * See also naix_vm_strategy.  For each buffer in the chain (including
1156          * bp) notify all users of the buffer that the daemon is finished
1157          * using it by calling iodone.  
1158          * assumes iodone can modify the b_work field.
1159          */
1160         for(tbp1=bp;;) {
1161             tbp2 = (struct buf *) tbp1->b_work;
1162             iodone(tbp1);
1163             if (!tbp2) 
1164                 break;
1165
1166             tbp1 = (struct buf *) tbp2->b_work;
1167             iodone(tbp2);
1168             if (!tbp1)
1169                 break;
1170         }
1171 if (DOvmlock)
1172         ReleaseWriteLock(&vcp->pvmlock);     /* Unlock the vnode.  */
1173         clrjmpx(&jmpbuf);
1174     } /* infinite loop (unless we're interrupted) */
1175     unpin (self, sizeof (struct afs_bioqueue));
1176     afs_osi_Free (self, sizeof (struct afs_bioqueue));
1177 } /* end of afs_BioDaemon() */
1178 #endif /* AFS_AIX41_ENV */ 
1179 #endif /* AFS_AIX32_ENV */
1180
1181
1182 int afs_nbrs = 0;
1183 void afs_BackgroundDaemon(void)
1184 {
1185     struct brequest *tb;
1186     int i, foundAny;
1187
1188     AFS_STATCNT(afs_BackgroundDaemon);
1189     /* initialize subsystem */
1190     if (brsInit == 0) {
1191         LOCK_INIT(&afs_xbrs, "afs_xbrs");
1192         memset((char *)afs_brs, 0, sizeof(afs_brs));
1193         brsInit = 1;
1194 #if defined (AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1195         /*
1196          * steal the first daemon for doing delayed DSlot flushing
1197          * (see afs_GetDownDSlot)
1198          */
1199         AFS_GUNLOCK();
1200         afs_sgidaemon();
1201         return;
1202 #endif
1203     }
1204     afs_nbrs++;
1205
1206     MObtainWriteLock(&afs_xbrs,302);
1207     while (1) {
1208         int min_ts;
1209         struct brequest *min_tb;
1210
1211         if (afs_termState == AFSOP_STOP_BKG) {
1212             if (--afs_nbrs <= 0)
1213                 afs_termState = AFSOP_STOP_TRUNCDAEMON;
1214             MReleaseWriteLock(&afs_xbrs);
1215             afs_osi_Wakeup(&afs_termState);
1216             return;
1217         }
1218
1219         /* find a request */
1220         tb = afs_brs;
1221         foundAny = 0;
1222         min_tb = NULL;
1223         for(i=0; i<NBRS; i++, tb++) {
1224             /* look for request with smallest ts */
1225             if ((tb->refCount > 0) && !(tb->flags & BSTARTED)) {
1226                 /* new request, not yet picked up */
1227                 if ((min_tb && (min_ts - tb->ts > 0)) || !min_tb) {
1228                     min_tb = tb;
1229                     min_ts = tb->ts;
1230                 }
1231             }
1232         }
1233         if ((tb = min_tb)) {
1234             /* claim and process this request */
1235             tb->flags |= BSTARTED;
1236             MReleaseWriteLock(&afs_xbrs);
1237             foundAny = 1;
1238             afs_Trace1(afs_iclSetp, CM_TRACE_BKG1,
1239                        ICL_TYPE_INT32, tb->opcode);
1240             if (tb->opcode == BOP_FETCH)
1241                 BPrefetch(tb);
1242             else if (tb->opcode == BOP_STORE)
1243                 BStore(tb);
1244             else if (tb->opcode == BOP_PATH)
1245                 BPath(tb);
1246             else panic("background bop");
1247             if (tb->vnode) {
1248 #ifdef  AFS_DEC_ENV
1249                 tb->vnode->vrefCount--;     /* fix up reference count */
1250 #else
1251                 AFS_RELE((struct vnode *)(tb->vnode));  /* MUST call vnode layer or could lose vnodes */
1252 #endif
1253                 tb->vnode = NULL;
1254             }
1255             if (tb->cred) {
1256                 crfree(tb->cred);
1257                 tb->cred = (struct AFS_UCRED *) 0;
1258             }
1259             afs_BRelease(tb);   /* this grabs and releases afs_xbrs lock */
1260             MObtainWriteLock(&afs_xbrs,305);
1261         }
1262         if (!foundAny) {
1263             /* wait for new request */
1264             afs_brsDaemons++;
1265             MReleaseWriteLock(&afs_xbrs);
1266             afs_osi_Sleep(&afs_brsDaemons);
1267             MObtainWriteLock(&afs_xbrs,307);
1268             afs_brsDaemons--;
1269         }
1270     }
1271 }
1272
1273
1274 void shutdown_daemons(void)
1275 {
1276   AFS_STATCNT(shutdown_daemons);
1277   if (afs_cold_shutdown) {
1278       afs_brsDaemons = brsInit = 0;
1279       rxepoch_checked = afs_nbrs = 0;
1280       memset((char *)afs_brs, 0, sizeof(afs_brs));
1281       memset((char *)&afs_xbrs, 0, sizeof(afs_lock_t));
1282       afs_brsWaiters = 0;
1283 #ifdef AFS_AIX32_ENV
1284 #ifdef AFS_AIX41_ENV
1285       lock_free(&afs_asyncbuf_lock);
1286       unpin(&afs_asyncbuf, sizeof(struct buf*));
1287       pin (&afs_asyncbuf_cv, sizeof(afs_int32));
1288 #else /* AFS_AIX41_ENV */
1289       afs_busyq = NULL;
1290       afs_biodcnt = 0;
1291       memset((char *)&afs_bioqueue, 0, sizeof(struct afs_bioqueue));
1292 #endif
1293       afs_initbiod = 0;
1294 #endif
1295   }
1296 }
1297
1298 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1299 /*
1300  * sgi - daemon - handles certain operations that otherwise
1301  * would use up too much kernel stack space
1302  *
1303  * This all assumes that since the caller must have the xdcache lock
1304  * exclusively that the list will never be more than one long
1305  * and noone else can attempt to add anything until we're done.
1306  */
1307 SV_TYPE afs_sgibksync;
1308 SV_TYPE afs_sgibkwait;
1309 lock_t afs_sgibklock;
1310 struct dcache *afs_sgibklist;
1311
1312 int afs_sgidaemon(void)
1313 {
1314         int s;
1315         struct dcache *tdc;
1316
1317         if (afs_sgibklock == NULL) {
1318                 SV_INIT(&afs_sgibksync, "bksync", 0, 0);
1319                 SV_INIT(&afs_sgibkwait, "bkwait", 0, 0);
1320                 SPINLOCK_INIT(&afs_sgibklock, "bklock");
1321         }
1322         s = SPLOCK(afs_sgibklock);
1323         for (;;) {
1324                 /* wait for something to do */
1325                 SP_WAIT(afs_sgibklock, s, &afs_sgibksync, PINOD);
1326                 osi_Assert(afs_sgibklist);
1327
1328                 /* XX will probably need to generalize to real list someday */
1329                 s = SPLOCK(afs_sgibklock);
1330                 while (afs_sgibklist) {
1331                         tdc = afs_sgibklist;
1332                         afs_sgibklist = NULL;
1333                         SPUNLOCK(afs_sgibklock, s);
1334                         AFS_GLOCK();
1335                         tdc->dflags &= ~DFEntryMod;
1336                         afs_WriteDCache(tdc, 1);
1337                         AFS_GUNLOCK();
1338                         s = SPLOCK(afs_sgibklock);
1339                 }
1340
1341                 /* done all the work - wake everyone up */
1342                 while (SV_SIGNAL(&afs_sgibkwait))
1343                         ;
1344         }
1345 }
1346 #endif