28c9dcef73baa56a4b8252a0bb447de50fad14ca
[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 = 0;
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 void 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     struct volume *tvp = NULL;
266     int usingDynroot = afs_GetDynrootEnable();
267     int localcell;
268
269     AFS_STATCNT(afs_CheckRootVolume);
270     if (*afs_rootVolumeName == 0) {
271         strcpy(rootVolName, "root.afs");
272     } else {
273         strcpy(rootVolName, afs_rootVolumeName);
274     }
275
276     if (!usingDynroot) {
277         struct cell *lc = afs_GetPrimaryCell(READ_LOCK);
278
279         if (!lc)
280             return ENOENT;
281         localcell = lc->cellNum;
282         afs_PutCell(lc, READ_LOCK);
283     }
284
285     if (usingDynroot) {
286         afs_GetDynrootFid(&afs_rootFid);
287         tvp = afs_GetVolume(&afs_rootFid, NULL, READ_LOCK);
288     } else {
289         tvp = afs_GetVolumeByName(rootVolName, localcell, 1, NULL, READ_LOCK);
290     }
291     if (!tvp && !usingDynroot) {
292         char buf[128];
293         int len = strlen(rootVolName);
294
295         if ((len < 9) || strcmp(&rootVolName[len - 9], ".readonly")) {
296             strcpy(buf, rootVolName);
297             afs_strcat(buf, ".readonly");
298             tvp = afs_GetVolumeByName(buf, localcell, 1, NULL, READ_LOCK);
299         }
300     }
301     if (tvp) {
302         if (!usingDynroot) {
303             int volid = (tvp->roVol? tvp->roVol : tvp->volume);
304             afs_rootFid.Cell = localcell;
305             if (afs_rootFid.Fid.Volume && afs_rootFid.Fid.Volume != volid
306                 && afs_globalVp) {
307                 /* If we had a root fid before and it changed location we reset
308                  * the afs_globalVp so that it will be reevaluated.
309                  * Just decrement the reference count. This only occurs during
310                  * initial cell setup and can panic the machine if we set the
311                  * count to zero and fs checkv is executed when the current
312                  * directory is /afs.
313                  */
314                 AFS_FAST_RELE(afs_globalVp);
315                 afs_globalVp = 0;
316             }
317             afs_rootFid.Fid.Volume = volid;
318             afs_rootFid.Fid.Vnode = 1;
319             afs_rootFid.Fid.Unique = 1;
320         }
321         afs_initState = 300;    /* won */
322         afs_osi_Wakeup(&afs_initState);
323         afs_PutVolume(tvp, READ_LOCK);
324     }
325 #ifdef AFS_DEC_ENV
326 /* This is to make sure that we update the root gnode */
327 /* every time root volume gets released */
328     {
329         struct gnode *rootgp;
330         struct mount *mp;
331         int code;
332
333         /* Only do this if afs_globalVFS is properly set due to race conditions
334            this routine could be called before the gfs_mount is performed!
335            Furthermore, afs_root (called below) *waits* until
336            initState >= 200, so we don't try this until we've gotten
337            at least that far */
338         if (afs_globalVFS && afs_initState >= 200) {
339             if (code = afs_root(afs_globalVFS, &rootgp))
340                 return code;
341             mp = (struct mount *) afs_globalVFS->vfs_data ;
342             mp->m_rootgp = gget(mp, 0, 0, (char *)rootgp);
343             afs_unlock(mp->m_rootgp);   /* unlock basic gnode */
344             afs_vrele(VTOAFS(rootgp));  /* zap afs_root's vnode hold */
345         }
346     }
347 #endif
348     if (afs_rootFid.Fid.Volume) return 0;
349     else return ENOENT;
350 }
351
352 /* ptr_parm 0 is the pathname, size_parm 0 to the fetch is the chunk number */
353 static void BPath(register struct brequest *ab)
354 {
355     register struct dcache *tdc = NULL;
356     struct vcache *tvc = NULL;
357     struct vnode *tvn = NULL;
358 #ifdef AFS_LINUX22_ENV
359     struct dentry *dp = NULL;
360 #endif
361     afs_size_t offset, len;
362     struct vrequest treq;
363     afs_int32 code;
364
365     AFS_STATCNT(BPath);
366     if ((code = afs_InitReq(&treq, ab->cred))) return;
367     AFS_GUNLOCK();
368 #ifdef AFS_LINUX22_ENV
369     code = gop_lookupname((char *)ab->ptr_parm[0], AFS_UIOSYS, 1,  NULL, &dp);
370     if (dp)
371         tvn = (struct vnode*)dp->d_inode;
372 #else
373     code = gop_lookupname((char *)ab->ptr_parm[0], AFS_UIOSYS, 1,  NULL, (struct vnode **)&tvn);
374 #endif
375     AFS_GLOCK();
376     osi_FreeLargeSpace((char *)ab->ptr_parm[0]); /* free path name buffer here */
377     if (code) return;
378     /* now path may not have been in afs, so check that before calling our cache manager */
379     if (!tvn || !IsAfsVnode((struct vnode *) tvn)) {
380         /* release it and give up */
381         if (tvn) {
382 #ifdef AFS_DEC_ENV
383             grele(tvn);
384 #else
385 #ifdef AFS_LINUX22_ENV
386             dput(dp);
387 #else
388             AFS_RELE((struct vnode *) tvn);
389 #endif
390 #endif
391         }
392         return;
393     }
394 #ifdef AFS_DEC_ENV
395     tvc = VTOAFS(afs_gntovn(tvn));
396 #else
397     tvc = VTOAFS(tvn);
398 #endif
399     /* here we know its an afs vnode, so we can get the data for the chunk */
400     tdc = afs_GetDCache(tvc, ab->size_parm[0], &treq, &offset, &len, 1);
401     if (tdc) {
402         afs_PutDCache(tdc);
403     }
404 #ifdef AFS_DEC_ENV
405     grele(tvn);
406 #else
407 #ifdef AFS_LINUX22_ENV
408     dput(dp);
409 #else
410     AFS_RELE((struct vnode *) tvn);
411 #endif
412 #endif
413 }
414
415 /* size_parm 0 to the fetch is the chunk number,
416  * ptr_parm 0 is the dcache entry to wakeup,
417  * size_parm 1 is true iff we should release the dcache entry here.
418  */
419 static void BPrefetch(register struct brequest *ab)
420 {
421     register struct dcache *tdc;
422     register struct vcache *tvc;
423     afs_size_t offset, len;
424     struct vrequest treq;
425
426     AFS_STATCNT(BPrefetch);
427     if ((len = afs_InitReq(&treq, ab->cred))) return;
428     tvc = ab->vnode;
429     tdc = afs_GetDCache(tvc, ab->size_parm[0], &treq, &offset, &len, 1);
430     if (tdc) {
431         afs_PutDCache(tdc);
432     }
433     /* now, dude may be waiting for us to clear DFFetchReq bit; do so.  Can't
434      * use tdc from GetDCache since afs_GetDCache may fail, but someone may
435      * be waiting for our wakeup anyway.
436      */
437     tdc = (struct dcache *) (ab->ptr_parm[0]);
438     ObtainSharedLock(&tdc->lock, 640);
439     if (tdc->mflags & DFFetchReq) {
440         UpgradeSToWLock(&tdc->lock, 641);
441         tdc->mflags &= ~DFFetchReq;
442         ReleaseWriteLock(&tdc->lock);
443     } else {
444         ReleaseSharedLock(&tdc->lock);
445     }
446     afs_osi_Wakeup(&tdc->validPos);
447     if (ab->size_parm[1]) {
448         afs_PutDCache(tdc);     /* put this one back, too */
449     }
450 }
451
452
453 static void BStore(register struct brequest *ab)
454 {
455     register struct vcache *tvc;
456     register afs_int32 code;
457     struct vrequest treq;
458 #if defined(AFS_SGI_ENV)
459     struct cred *tmpcred;
460 #endif
461
462     AFS_STATCNT(BStore);
463     if ((code = afs_InitReq(&treq, ab->cred))) return;
464     code = 0;
465     tvc = ab->vnode;
466 #if defined(AFS_SGI_ENV)
467     /*
468      * Since StoreOnLastReference can end up calling osi_SyncVM which
469      * calls into VM code that assumes that u.u_cred has the
470      * correct credentials, we set our to theirs for this xaction
471      */
472     tmpcred = OSI_GET_CURRENT_CRED();
473     OSI_SET_CURRENT_CRED(ab->cred);
474
475     /*
476      * To avoid recursion since the WriteLock may be released during VM
477      * operations, we hold the VOP_RWLOCK across this transaction as
478      * do the other callers of StoreOnLastReference
479      */
480     AFS_RWLOCK((vnode_t *)tvc, 1);
481 #endif
482     ObtainWriteLock(&tvc->lock,209);
483     code = afs_StoreOnLastReference(tvc, &treq);
484     ReleaseWriteLock(&tvc->lock);
485 #if defined(AFS_SGI_ENV)
486     OSI_SET_CURRENT_CRED(tmpcred);
487     AFS_RWUNLOCK((vnode_t *)tvc, 1);
488 #endif
489     /* now set final return code, and wakeup anyone waiting */
490     if ((ab->flags & BUVALID) == 0) {
491         ab->code = afs_CheckCode(code, &treq, 43);    /* set final code, since treq doesn't go across processes */
492         ab->flags |= BUVALID;
493         if (ab->flags & BUWAIT) {
494             ab->flags &= ~BUWAIT;
495             afs_osi_Wakeup(ab);
496         }
497     }
498 }
499
500 /* release a held request buffer */
501 void afs_BRelease(register struct brequest *ab)
502 {
503
504     AFS_STATCNT(afs_BRelease);
505     MObtainWriteLock(&afs_xbrs,294);
506     if (--ab->refCount <= 0) {
507         ab->flags = 0;
508     }
509     if (afs_brsWaiters) afs_osi_Wakeup(&afs_brsWaiters);
510     MReleaseWriteLock(&afs_xbrs);
511 }
512
513 /* return true if bkg fetch daemons are all busy */
514 int afs_BBusy(void)
515 {
516     AFS_STATCNT(afs_BBusy);
517     if (afs_brsDaemons > 0) return 0;
518     return 1;
519 }
520
521 struct brequest *afs_BQueue(register short aopcode, register struct vcache *avc, 
522         afs_int32 dontwait, afs_int32 ause, struct AFS_UCRED *acred, 
523         afs_size_t asparm0, afs_size_t asparm1, void *apparm0)
524 {
525     register int i;
526     register struct brequest *tb;
527
528     AFS_STATCNT(afs_BQueue);
529     MObtainWriteLock(&afs_xbrs,296);
530     while (1) {
531         tb = afs_brs;
532         for(i=0;i<NBRS;i++,tb++) {
533             if (tb->refCount == 0) break;
534         }
535         if (i < NBRS) {
536             /* found a buffer */
537             tb->opcode = aopcode;
538             tb->vnode = avc;
539             tb->cred = acred;
540             crhold(tb->cred);
541             if (avc) {
542 #ifdef  AFS_DEC_ENV
543                 avc->vrefCount++;
544 #else
545                 VN_HOLD(AFSTOV(avc));
546 #endif
547             }
548             tb->refCount = ause+1;
549             tb->size_parm[0] = asparm0;
550             tb->size_parm[1] = asparm1;
551             tb->ptr_parm[0]  = apparm0;
552             tb->flags = 0;
553             tb->code = 0;
554             tb->ts = afs_brs_count++;
555             /* if daemons are waiting for work, wake them up */
556             if (afs_brsDaemons > 0) {
557                 afs_osi_Wakeup(&afs_brsDaemons);
558             }
559             MReleaseWriteLock(&afs_xbrs);
560             return tb;
561         }
562         if (dontwait) {
563             MReleaseWriteLock(&afs_xbrs);
564             return NULL;
565         }
566         /* no free buffers, sleep a while */
567         afs_brsWaiters++;
568         MReleaseWriteLock(&afs_xbrs);
569         afs_osi_Sleep(&afs_brsWaiters);
570         MObtainWriteLock(&afs_xbrs,301);
571         afs_brsWaiters--;
572     }
573 }
574
575 #ifdef  AFS_AIX32_ENV
576 #ifdef AFS_AIX41_ENV
577 /* AIX 4.1 has a much different sleep/wakeup mechanism available for use. 
578  * The modifications here will work for either a UP or MP machine.
579  */
580 struct buf *afs_asyncbuf = (struct buf*)0;
581 afs_int32 afs_asyncbuf_cv = EVENT_NULL;
582 afs_int32 afs_biodcnt = 0;
583
584 /* in implementing this, I assumed that all external linked lists were
585  * null-terminated.  
586  *
587  * Several places in this code traverse a linked list.  The algorithm
588  * used here is probably unfamiliar to most people.  Careful examination
589  * will show that it eliminates an assignment inside the loop, as compared
590  * to the standard algorithm, at the cost of occasionally using an extra
591  * variable.
592  */
593
594 /* get_bioreq()
595  *
596  * This function obtains, and returns, a pointer to a buffer for
597  * processing by a daemon.  It sleeps until such a buffer is available.
598  * The source of buffers for it is the list afs_asyncbuf (see also 
599  * naix_vm_strategy).  This function may be invoked concurrently by
600  * several processes, that is, several instances of the same daemon.
601  * naix_vm_strategy, which adds buffers to the list, runs at interrupt
602  * level, while get_bioreq runs at process level.
603  *
604  * Since AIX 4.1 can wake just one process at a time, the separate sleep
605  * addresses have been removed.
606  * Note that the kernel_lock is held until the e_sleep_thread() occurs. 
607  * The afs_asyncbuf_lock is primarily used to serialize access between
608  * process and interrupts.
609  */
610 Simple_lock afs_asyncbuf_lock;
611 /*static*/ struct buf *afs_get_bioreq()
612 {
613     struct buf *bp = NULL;
614     struct buf *bestbp;
615     struct buf **bestlbpP, **lbpP;
616     int bestage, stop;
617     struct buf *t1P, *t2P;      /* temp pointers for list manipulation */
618     int oldPriority;
619     afs_uint32 wait_ret;
620     struct afs_bioqueue *s;
621
622     /* ??? Does the forward pointer of the returned buffer need to be NULL?
623     */
624     
625     /* Disable interrupts from the strategy function, and save the 
626      * prior priority level and lock access to the afs_asyncbuf.
627      */
628     AFS_GUNLOCK();
629     oldPriority = disable_lock(INTMAX, &afs_asyncbuf_lock) ;
630
631     while(1) {
632         if (afs_asyncbuf) {
633             /* look for oldest buffer */
634             bp = bestbp = afs_asyncbuf;
635             bestage = (int) bestbp->av_back;
636             bestlbpP = &afs_asyncbuf;
637             while (1) {
638                 lbpP = &bp->av_forw;
639                 bp = *lbpP;
640                 if (!bp) break;
641                 if ((int) bp->av_back - bestage < 0) {
642                     bestbp = bp;
643                     bestlbpP = lbpP;
644                     bestage = (int) bp->av_back;
645                 }
646             }
647             bp = bestbp;
648             *bestlbpP = bp->av_forw;
649             break;
650         }
651         else {
652             /* If afs_asyncbuf is null, it is necessary to go to sleep.
653              * e_wakeup_one() ensures that only one thread wakes.
654              */
655             int interrupted;
656             /* The LOCK_HANDLER indicates to e_sleep_thread to only drop the
657              * lock on an MP machine.
658              */
659             interrupted = e_sleep_thread(&afs_asyncbuf_cv,
660                                          &afs_asyncbuf_lock,
661                                          LOCK_HANDLER|INTERRUPTIBLE);
662             if (interrupted==THREAD_INTERRUPTED) {
663                 /* re-enable interrupts from strategy */
664                 unlock_enable(oldPriority, &afs_asyncbuf_lock);
665                 AFS_GLOCK();
666                 return(NULL);
667             }
668         }  /* end of "else asyncbuf is empty" */
669     } /* end of "inner loop" */
670     
671     /*assert (bp);*/
672     
673     unlock_enable(oldPriority, &afs_asyncbuf_lock);
674     AFS_GLOCK();
675
676     /* For the convenience of other code, replace the gnodes in
677      * the b_vp field of bp and the other buffers on the b_work
678      * chain with the corresponding vnodes.   
679      *
680      * ??? what happens to the gnodes?  They're not just cut loose,
681      * are they?
682      */
683     for(t1P=bp;;) {
684         t2P = (struct buf *) t1P->b_work;
685         t1P->b_vp = ((struct gnode *) t1P->b_vp)->gn_vnode;
686         if (!t2P) 
687             break;
688
689         t1P = (struct buf *) t2P->b_work;
690         t2P->b_vp = ((struct gnode *) t2P->b_vp)->gn_vnode;
691         if (!t1P)
692             break;
693     }
694
695     /* If the buffer does not specify I/O, it may immediately
696      * be returned to the caller.  This condition is detected
697      * by examining the buffer's flags (the b_flags field).  If
698      * the B_PFPROT bit is set, the buffer represents a protection
699      * violation, rather than a request for I/O.  The remainder
700      * of the outer loop handles the case where the B_PFPROT bit is clear.
701      */
702     if (bp->b_flags & B_PFPROT)  {
703         return (bp);
704     }
705     return (bp);
706
707 } /* end of function get_bioreq() */
708
709
710 /* afs_BioDaemon
711  *
712  * This function is the daemon.  It is called from the syscall
713  * interface.  Ordinarily, a script or an administrator will run a
714  * daemon startup utility, specifying the number of I/O daemons to
715  * run.  The utility will fork off that number of processes,
716  * each making the appropriate syscall, which will cause this
717  * function to be invoked.
718  */
719 static int afs_initbiod = 0;            /* this is self-initializing code */
720 int DOvmlock = 0;
721 int afs_BioDaemon (afs_int32 nbiods)
722 {
723     afs_int32 code, s, pflg = 0;
724     label_t jmpbuf;
725     struct buf *bp, *bp1, *tbp1, *tbp2;         /* temp pointers only */
726     caddr_t tmpaddr;
727     struct vnode *vp;
728     struct vcache *vcp;
729     char tmperr;
730     if (!afs_initbiod) {
731         /* XXX ###1 XXX */
732         afs_initbiod = 1;
733         /* pin lock, since we'll be using it in an interrupt. */
734         lock_alloc(&afs_asyncbuf_lock, LOCK_ALLOC_PIN, 2, 1);
735         simple_lock_init(&afs_asyncbuf_lock);
736         pin (&afs_asyncbuf, sizeof(struct buf*));
737         pin (&afs_asyncbuf_cv, sizeof(afs_int32));
738     }
739
740     /* Ignore HUP signals... */
741     {
742         sigset_t sigbits, osigbits;
743         /*
744          * add SIGHUP to the set of already masked signals
745          */
746         SIGFILLSET(sigbits);                    /* allow all signals    */
747         SIGDELSET(sigbits, SIGHUP);             /*   except SIGHUP      */
748         limit_sigs(&sigbits, &osigbits);        /*   and already masked */
749     }
750     /* Main body starts here -- this is an intentional infinite loop, and
751      * should NEVER exit 
752      *
753      * Now, the loop will exit if get_bioreq() returns NULL, indicating 
754      * that we've been interrupted.
755      */
756     while (1) {
757         bp = afs_get_bioreq();
758         if (!bp)
759             break;      /* we were interrupted */
760         if (code = setjmpx(&jmpbuf)) {
761             /* This should not have happend, maybe a lack of resources  */
762             AFS_GUNLOCK();
763             s = disable_lock(INTMAX, &afs_asyncbuf_lock);
764             for (bp1 = bp; bp ; bp = bp1) {
765                 if (bp1)
766                     bp1 = (struct buf *) bp1->b_work;
767                 bp->b_actf = 0;
768                 bp->b_error = code;
769                 bp->b_flags |= B_ERROR;
770                 iodone(bp);
771             }
772             unlock_enable(s, &afs_asyncbuf_lock);
773             AFS_GLOCK();
774             continue;
775         }
776         vcp = VTOAFS(bp->b_vp);
777         if (bp->b_flags & B_PFSTORE) {  /* XXXX */
778             ObtainWriteLock(&vcp->lock,404);        
779             if (vcp->v.v_gnode->gn_mwrcnt) {
780                 afs_offs_t newlength = 
781                         (afs_offs_t) dbtob(bp->b_blkno) + bp->b_bcount;
782                 if (vcp->m.Length < newlength) {
783                     afs_Trace4(afs_iclSetp, CM_TRACE_SETLENGTH,
784                         ICL_TYPE_STRING, __FILE__,
785                         ICL_TYPE_LONG, __LINE__,
786                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(vcp->m.Length),
787                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(newlength));
788                     vcp->m.Length = newlength;
789                 }
790             }
791             ReleaseWriteLock(&vcp->lock);
792         }
793         /* If the buffer represents a protection violation, rather than
794          * an actual request for I/O, no special action need be taken.  
795          */
796         if ( bp->b_flags & B_PFPROT ) {   
797             iodone (bp);    /* Notify all users of the buffer that we're done */
798             clrjmpx(&jmpbuf);
799             continue;
800         }
801 if (DOvmlock)
802         ObtainWriteLock(&vcp->pvmlock,211);     
803         /*
804          * First map its data area to a region in the current address space
805          * by calling vm_att with the subspace identifier, and a pointer to
806          * the data area.  vm_att returns  a new data area pointer, but we
807          * also want to hang onto the old one.
808          */
809         tmpaddr = bp->b_baddr;
810         bp->b_baddr = vm_att (bp->b_xmemd.subspace_id, tmpaddr);
811         tmperr = afs_ustrategy(bp);     /* temp variable saves offset calculation */
812         if (tmperr) {                   /* in non-error case */
813             bp->b_flags |= B_ERROR;             /* should other flags remain set ??? */
814             bp->b_error = tmperr;
815         }
816
817         /* Unmap the buffer's data area by calling vm_det.  Reset data area
818          * to the value that we saved above.
819          */
820         vm_det(bp->b_un.b_addr);
821         bp->b_baddr = tmpaddr;
822
823         /*
824          * buffer may be linked with other buffers via the b_work field.
825          * See also naix_vm_strategy.  For each buffer in the chain (including
826          * bp) notify all users of the buffer that the daemon is finished
827          * using it by calling iodone.  
828          * assumes iodone can modify the b_work field.
829          */
830         for(tbp1=bp;;) {
831             tbp2 = (struct buf *) tbp1->b_work;
832             iodone(tbp1);
833             if (!tbp2) 
834                 break;
835
836             tbp1 = (struct buf *) tbp2->b_work;
837             iodone(tbp2);
838             if (!tbp1)
839                 break;
840         }
841 if (DOvmlock)
842         ReleaseWriteLock(&vcp->pvmlock);     /* Unlock the vnode.  */
843         clrjmpx(&jmpbuf);
844     } /* infinite loop (unless we're interrupted) */
845 } /* end of afs_BioDaemon() */
846
847 #else /* AFS_AIX41_ENV */
848
849
850 #define squeue afs_q
851 struct afs_bioqueue {
852     struct squeue lruq;
853     int sleeper;
854     int cnt;
855 };
856 struct afs_bioqueue afs_bioqueue;
857 struct buf *afs_busyq = NULL;
858 struct buf *afs_asyncbuf;
859 afs_int32 afs_biodcnt = 0;
860
861 /* in implementing this, I assumed that all external linked lists were
862  * null-terminated.  
863  *
864  * Several places in this code traverse a linked list.  The algorithm
865  * used here is probably unfamiliar to most people.  Careful examination
866  * will show that it eliminates an assignment inside the loop, as compared
867  * to the standard algorithm, at the cost of occasionally using an extra
868  * variable.
869  */
870
871 /* get_bioreq()
872  *
873  * This function obtains, and returns, a pointer to a buffer for
874  * processing by a daemon.  It sleeps until such a buffer is available.
875  * The source of buffers for it is the list afs_asyncbuf (see also 
876  * naix_vm_strategy).  This function may be invoked concurrently by
877  * several processes, that is, several instances of the same daemon.
878  * naix_vm_strategy, which adds buffers to the list, runs at interrupt
879  * level, while get_bioreq runs at process level.
880  *
881  * The common kernel paradigm of sleeping and waking up, in which all the
882  * competing processes sleep waiting for wakeups on one address, is not
883  * followed here.  Instead, the following paradigm is used:  when a daemon
884  * goes to sleep, it checks for other sleeping daemons.  If there aren't any,
885  * it sleeps on the address of variable afs_asyncbuf.  But if there is
886  * already a daemon sleeping on that address, it threads its own unique
887  * address onto a list, and sleeps on that address.  This way, every 
888  * sleeper is sleeping on a different address, and every wakeup wakes up
889  * exactly one daemon.  This prevents a whole bunch of daemons from waking
890  * up and then immediately having to go back to sleep.  This provides a
891  * performance gain and makes the I/O scheduling a bit more deterministic.
892  * The list of sleepers is variable afs_bioqueue.  The unique address
893  * on which to sleep is passed to get_bioreq as its parameter.
894  */
895 /*static*/ struct buf *afs_get_bioreq(self)
896     struct afs_bioqueue *self;      /* address on which to sleep */
897
898 {
899     struct buf *bp = NULL;
900     struct buf *bestbp;
901     struct buf **bestlbpP, **lbpP;
902     int bestage, stop;
903     struct buf *t1P, *t2P;      /* temp pointers for list manipulation */
904     int oldPriority;
905     afs_uint32 wait_ret;
906 struct afs_bioqueue *s;
907
908     /* ??? Does the forward pointer of the returned buffer need to be NULL?
909     */
910     
911         /* Disable interrupts from the strategy function, and save the 
912          * prior priority level
913          */
914         oldPriority = i_disable ( INTMAX ) ;
915
916         /* Each iteration of following loop either pulls
917          * a buffer off afs_asyncbuf, or sleeps.  
918          */
919         while (1) {   /* inner loop */
920                 if (afs_asyncbuf) {
921                         /* look for oldest buffer */
922                         bp = bestbp = afs_asyncbuf;
923                         bestage = (int) bestbp->av_back;
924                         bestlbpP = &afs_asyncbuf;
925                         while (1) {
926                                 lbpP = &bp->av_forw;
927                                 bp = *lbpP;
928                                 if (!bp) break;
929                                 if ((int) bp->av_back - bestage < 0) {
930                                         bestbp = bp;
931                                         bestlbpP = lbpP;
932                                         bestage = (int) bp->av_back;
933                                 }
934                         }
935                         bp = bestbp;
936                         *bestlbpP = bp->av_forw;
937                         break;  
938                         }
939                 else {
940                         int interrupted;
941
942                 /* If afs_asyncbuf is null, it is necessary to go to sleep.
943                  * There are two possibilities:  either there is already a
944                  * daemon that is sleeping on the address of afs_asyncbuf,
945                  * or there isn't. 
946                  */
947                         if (afs_bioqueue.sleeper) {
948                                 /* enqueue */
949                                 QAdd (&(afs_bioqueue.lruq), &(self->lruq));
950                                 interrupted = sleep ((caddr_t) self, PCATCH|(PZERO + 1));
951                                 if (self->lruq.next != &self->lruq) {   /* XXX ##3 XXX */
952                                     QRemove (&(self->lruq));            /* dequeue */
953                                 }
954 self->cnt++;
955                                 afs_bioqueue.sleeper = FALSE;
956                                 if (interrupted) {
957                                     /* re-enable interrupts from strategy */
958                                     i_enable (oldPriority);
959                                     return(NULL);
960                                 }
961                                 continue;
962                         } else {
963                                 afs_bioqueue.sleeper = TRUE;
964                                 interrupted = sleep ((caddr_t) &afs_asyncbuf, PCATCH|(PZERO + 1));
965                                 afs_bioqueue.sleeper = FALSE;
966                                 if (interrupted)
967                                 {
968                                     /*
969                                      * We need to wakeup another daemon if present
970                                      * since we were waiting on afs_asyncbuf.
971                                      */
972 #ifdef  notdef  /* The following doesn't work as advertised */                              
973                                      if (afs_bioqueue.lruq.next != &afs_bioqueue.lruq)
974                                      {
975                                          struct squeue *bq = afs_bioqueue.lruq.next;
976                                          QRemove (bq);
977                                          wakeup (bq);
978                                      }
979 #endif
980                                     /* re-enable interrupts from strategy */
981                                      i_enable (oldPriority);
982                                      return(NULL);
983                                  }
984                                 continue;
985                                 }
986
987                         }  /* end of "else asyncbuf is empty" */
988                 } /* end of "inner loop" */
989
990         /*assert (bp);*/
991
992         i_enable (oldPriority);     /* re-enable interrupts from strategy */
993
994         /* For the convenience of other code, replace the gnodes in
995          * the b_vp field of bp and the other buffers on the b_work
996          * chain with the corresponding vnodes.   
997          *
998          * ??? what happens to the gnodes?  They're not just cut loose,
999          * are they?
1000          */
1001         for(t1P=bp;;) {
1002                 t2P = (struct buf *) t1P->b_work;
1003                 t1P->b_vp = ((struct gnode *) t1P->b_vp)->gn_vnode;
1004                 if (!t2P) 
1005                         break;
1006
1007                 t1P = (struct buf *) t2P->b_work;
1008                 t2P->b_vp = ((struct gnode *) t2P->b_vp)->gn_vnode;
1009                 if (!t1P)
1010                         break;
1011                 }
1012
1013         /* If the buffer does not specify I/O, it may immediately
1014          * be returned to the caller.  This condition is detected
1015          * by examining the buffer's flags (the b_flags field).  If
1016          * the B_PFPROT bit is set, the buffer represents a protection
1017          * violation, rather than a request for I/O.  The remainder
1018          * of the outer loop handles the case where the B_PFPROT bit is clear.
1019          */
1020          if (bp->b_flags & B_PFPROT)  {
1021                 return (bp);
1022             }
1023
1024         /* wake up another process to handle the next buffer, and return
1025          * bp to the caller.
1026          */
1027         oldPriority = i_disable ( INTMAX ) ;
1028
1029         /* determine where to find the sleeping process. 
1030          * There are two cases: either it is sleeping on
1031          * afs_asyncbuf, or it is sleeping on its own unique
1032          * address.  These cases are distinguished by examining
1033          * the sleeper field of afs_bioqueue.
1034          */
1035         if (afs_bioqueue.sleeper) {
1036                 wakeup (&afs_asyncbuf);
1037                 }
1038         else {
1039                 if (afs_bioqueue.lruq.next == &afs_bioqueue.lruq) {
1040                         /* queue is empty, what now? ???*/
1041                         /* Should this be impossible, or does    */
1042                         /* it just mean that nobody is sleeping? */;
1043                         }
1044                 else {
1045                         struct squeue *bq = afs_bioqueue.lruq.next;
1046                         QRemove (bq);
1047                         QInit (bq);
1048                         wakeup (bq);
1049                         afs_bioqueue.sleeper = TRUE; 
1050                         }
1051                 }
1052         i_enable (oldPriority);     /* re-enable interrupts from strategy */
1053         return (bp);
1054
1055 } /* end of function get_bioreq() */
1056
1057
1058 /* afs_BioDaemon
1059  *
1060  * This function is the daemon.  It is called from the syscall
1061  * interface.  Ordinarily, a script or an administrator will run a
1062  * daemon startup utility, specifying the number of I/O daemons to
1063  * run.  The utility will fork off that number of processes,
1064  * each making the appropriate syscall, which will cause this
1065  * function to be invoked.
1066  */
1067 static int afs_initbiod = 0;            /* this is self-initializing code */
1068 int DOvmlock = 0;
1069 afs_BioDaemon (nbiods)
1070     afs_int32 nbiods;
1071 {
1072     struct afs_bioqueue *self;
1073     afs_int32 code, s, pflg = 0;
1074     label_t jmpbuf;
1075     struct buf *bp, *bp1, *tbp1, *tbp2;         /* temp pointers only */
1076     caddr_t tmpaddr;
1077     struct vnode *vp;
1078     struct vcache *vcp;
1079     char tmperr;
1080     if (!afs_initbiod) {
1081         /* XXX ###1 XXX */
1082         afs_initbiod = 1;
1083         /* Initialize the queue of waiting processes, afs_bioqueue.  */
1084         QInit (&(afs_bioqueue.lruq));           
1085     }
1086
1087     /* establish ourself as a kernel process so shutdown won't kill us */
1088 /*    u.u_procp->p_flag |= SKPROC;*/
1089
1090     /* Initialize a token (self) to use in the queue of sleeping processes.   */
1091     self = (struct afs_bioqueue *) afs_osi_Alloc (sizeof (struct afs_bioqueue));
1092     pin (self, sizeof (struct afs_bioqueue)); /* fix in memory */
1093     memset(self, 0, sizeof(*self));
1094     QInit (&(self->lruq));              /* initialize queue entry pointers */
1095
1096
1097     /* Ignore HUP signals... */
1098     SIGDELSET(u.u_procp->p_sig, SIGHUP);
1099     SIGADDSET(u.u_procp->p_sigignore, SIGHUP);
1100     SIGDELSET(u.u_procp->p_sigcatch, SIGHUP);
1101     /* Main body starts here -- this is an intentional infinite loop, and
1102      * should NEVER exit 
1103      *
1104      * Now, the loop will exit if get_bioreq() returns NULL, indicating 
1105      * that we've been interrupted.
1106      */
1107     while (1) {
1108         bp = afs_get_bioreq(self);
1109         if (!bp)
1110             break;      /* we were interrupted */
1111         if (code = setjmpx(&jmpbuf)) {
1112             /* This should not have happend, maybe a lack of resources  */
1113             s = splimp();
1114             for (bp1 = bp; bp ; bp = bp1) {
1115                 if (bp1)
1116                     bp1 = bp1->b_work;
1117                 bp->b_actf = 0;
1118                 bp->b_error = code;
1119                 bp->b_flags |= B_ERROR;
1120                 iodone(bp);
1121             }
1122             splx(s);
1123             continue;
1124         }
1125         vcp = VTOAFS(bp->b_vp);
1126         if (bp->b_flags & B_PFSTORE) {
1127             ObtainWriteLock(&vcp->lock,210);        
1128             if (vcp->v.v_gnode->gn_mwrcnt) {
1129                 afs_offs_t newlength = 
1130                         (afs_offs_t) dbtob(bp->b_blkno) + bp->b_bcount;
1131                 if (vcp->m.Length < newlength) {
1132                     afs_Trace4(afs_iclSetp, CM_TRACE_SETLENGTH,
1133                         ICL_TYPE_STRING, __FILE__,
1134                         ICL_TYPE_LONG, __LINE__,
1135                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(vcp->m.Length),
1136                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(newlength));
1137                     vcp->m.Length = newlength;
1138                 }
1139             }
1140             ReleaseWriteLock(&vcp->lock);
1141         }
1142         /* If the buffer represents a protection violation, rather than
1143          * an actual request for I/O, no special action need be taken.  
1144          */
1145         if ( bp->b_flags & B_PFPROT ) {   
1146             iodone (bp);    /* Notify all users of the buffer that we're done */
1147             continue;
1148         }
1149 if (DOvmlock)
1150         ObtainWriteLock(&vcp->pvmlock,558);     
1151         /*
1152          * First map its data area to a region in the current address space
1153          * by calling vm_att with the subspace identifier, and a pointer to
1154          * the data area.  vm_att returns  a new data area pointer, but we
1155          * also want to hang onto the old one.
1156          */
1157         tmpaddr = bp->b_baddr;
1158         bp->b_baddr = vm_att (bp->b_xmemd.subspace_id, tmpaddr);
1159         tmperr = afs_ustrategy(bp);     /* temp variable saves offset calculation */
1160         if (tmperr) {                   /* in non-error case */
1161             bp->b_flags |= B_ERROR;             /* should other flags remain set ??? */
1162             bp->b_error = tmperr;
1163         }
1164
1165         /* Unmap the buffer's data area by calling vm_det.  Reset data area
1166          * to the value that we saved above.
1167          */
1168         vm_det(bp->b_un.b_addr);
1169         bp->b_baddr = tmpaddr;
1170
1171         /*
1172          * buffer may be linked with other buffers via the b_work field.
1173          * See also naix_vm_strategy.  For each buffer in the chain (including
1174          * bp) notify all users of the buffer that the daemon is finished
1175          * using it by calling iodone.  
1176          * assumes iodone can modify the b_work field.
1177          */
1178         for(tbp1=bp;;) {
1179             tbp2 = (struct buf *) tbp1->b_work;
1180             iodone(tbp1);
1181             if (!tbp2) 
1182                 break;
1183
1184             tbp1 = (struct buf *) tbp2->b_work;
1185             iodone(tbp2);
1186             if (!tbp1)
1187                 break;
1188         }
1189 if (DOvmlock)
1190         ReleaseWriteLock(&vcp->pvmlock);     /* Unlock the vnode.  */
1191         clrjmpx(&jmpbuf);
1192     } /* infinite loop (unless we're interrupted) */
1193     unpin (self, sizeof (struct afs_bioqueue));
1194     afs_osi_Free (self, sizeof (struct afs_bioqueue));
1195 } /* end of afs_BioDaemon() */
1196 #endif /* AFS_AIX41_ENV */ 
1197 #endif /* AFS_AIX32_ENV */
1198
1199
1200 int afs_nbrs = 0;
1201 void afs_BackgroundDaemon(void)
1202 {
1203     struct brequest *tb;
1204     int i, foundAny;
1205
1206     AFS_STATCNT(afs_BackgroundDaemon);
1207     /* initialize subsystem */
1208     if (brsInit == 0) {
1209         LOCK_INIT(&afs_xbrs, "afs_xbrs");
1210         memset((char *)afs_brs, 0, sizeof(afs_brs));
1211         brsInit = 1;
1212 #if defined (AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1213         /*
1214          * steal the first daemon for doing delayed DSlot flushing
1215          * (see afs_GetDownDSlot)
1216          */
1217         AFS_GUNLOCK();
1218         afs_sgidaemon();
1219         return;
1220 #endif
1221     }
1222     afs_nbrs++;
1223
1224     MObtainWriteLock(&afs_xbrs,302);
1225     while (1) {
1226         int min_ts;
1227         struct brequest *min_tb;
1228
1229         if (afs_termState == AFSOP_STOP_BKG) {
1230             if (--afs_nbrs <= 0)
1231                 afs_termState = AFSOP_STOP_TRUNCDAEMON;
1232             MReleaseWriteLock(&afs_xbrs);
1233             afs_osi_Wakeup(&afs_termState);
1234             return;
1235         }
1236
1237         /* find a request */
1238         tb = afs_brs;
1239         foundAny = 0;
1240         min_tb = NULL;
1241         for(i=0; i<NBRS; i++, tb++) {
1242             /* look for request with smallest ts */
1243             if ((tb->refCount > 0) && !(tb->flags & BSTARTED)) {
1244                 /* new request, not yet picked up */
1245                 if ((min_tb && (min_ts - tb->ts > 0)) || !min_tb) {
1246                     min_tb = tb;
1247                     min_ts = tb->ts;
1248                 }
1249             }
1250         }
1251         if ((tb = min_tb)) {
1252             /* claim and process this request */
1253             tb->flags |= BSTARTED;
1254             MReleaseWriteLock(&afs_xbrs);
1255             foundAny = 1;
1256             afs_Trace1(afs_iclSetp, CM_TRACE_BKG1,
1257                        ICL_TYPE_INT32, tb->opcode);
1258             if (tb->opcode == BOP_FETCH)
1259                 BPrefetch(tb);
1260             else if (tb->opcode == BOP_STORE)
1261                 BStore(tb);
1262             else if (tb->opcode == BOP_PATH)
1263                 BPath(tb);
1264             else panic("background bop");
1265             if (tb->vnode) {
1266 #ifdef  AFS_DEC_ENV
1267                 tb->vnode->vrefCount--;     /* fix up reference count */
1268 #else
1269                 AFS_RELE((struct vnode *)(tb->vnode));  /* MUST call vnode layer or could lose vnodes */
1270 #endif
1271                 tb->vnode = NULL;
1272             }
1273             if (tb->cred) {
1274                 crfree(tb->cred);
1275                 tb->cred = (struct AFS_UCRED *) 0;
1276             }
1277             afs_BRelease(tb);   /* this grabs and releases afs_xbrs lock */
1278             MObtainWriteLock(&afs_xbrs,305);
1279         }
1280         if (!foundAny) {
1281             /* wait for new request */
1282             afs_brsDaemons++;
1283             MReleaseWriteLock(&afs_xbrs);
1284             afs_osi_Sleep(&afs_brsDaemons);
1285             MObtainWriteLock(&afs_xbrs,307);
1286             afs_brsDaemons--;
1287         }
1288     }
1289 }
1290
1291
1292 void shutdown_daemons(void)
1293 {
1294   AFS_STATCNT(shutdown_daemons);
1295   if (afs_cold_shutdown) {
1296       afs_brsDaemons = brsInit = 0;
1297       rxepoch_checked = afs_nbrs = 0;
1298       memset((char *)afs_brs, 0, sizeof(afs_brs));
1299       memset((char *)&afs_xbrs, 0, sizeof(afs_lock_t));
1300       afs_brsWaiters = 0;
1301 #ifdef AFS_AIX32_ENV
1302 #ifdef AFS_AIX41_ENV
1303       lock_free(&afs_asyncbuf_lock);
1304       unpin(&afs_asyncbuf, sizeof(struct buf*));
1305       pin (&afs_asyncbuf_cv, sizeof(afs_int32));
1306 #else /* AFS_AIX41_ENV */
1307       afs_busyq = NULL;
1308       afs_biodcnt = 0;
1309       memset((char *)&afs_bioqueue, 0, sizeof(struct afs_bioqueue));
1310 #endif
1311       afs_initbiod = 0;
1312 #endif
1313   }
1314 }
1315
1316 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1317 /*
1318  * sgi - daemon - handles certain operations that otherwise
1319  * would use up too much kernel stack space
1320  *
1321  * This all assumes that since the caller must have the xdcache lock
1322  * exclusively that the list will never be more than one long
1323  * and noone else can attempt to add anything until we're done.
1324  */
1325 SV_TYPE afs_sgibksync;
1326 SV_TYPE afs_sgibkwait;
1327 lock_t afs_sgibklock;
1328 struct dcache *afs_sgibklist;
1329
1330 int afs_sgidaemon(void)
1331 {
1332         int s;
1333         struct dcache *tdc;
1334
1335         if (afs_sgibklock == NULL) {
1336                 SV_INIT(&afs_sgibksync, "bksync", 0, 0);
1337                 SV_INIT(&afs_sgibkwait, "bkwait", 0, 0);
1338                 SPINLOCK_INIT(&afs_sgibklock, "bklock");
1339         }
1340         s = SPLOCK(afs_sgibklock);
1341         for (;;) {
1342                 /* wait for something to do */
1343                 SP_WAIT(afs_sgibklock, s, &afs_sgibksync, PINOD);
1344                 osi_Assert(afs_sgibklist);
1345
1346                 /* XX will probably need to generalize to real list someday */
1347                 s = SPLOCK(afs_sgibklock);
1348                 while (afs_sgibklist) {
1349                         tdc = afs_sgibklist;
1350                         afs_sgibklist = NULL;
1351                         SPUNLOCK(afs_sgibklock, s);
1352                         AFS_GLOCK();
1353                         tdc->dflags &= ~DFEntryMod;
1354                         afs_WriteDCache(tdc, 1);
1355                         AFS_GUNLOCK();
1356                         s = SPLOCK(afs_sgibklock);
1357                 }
1358
1359                 /* done all the work - wake everyone up */
1360                 while (SV_SIGNAL(&afs_sgibkwait))
1361                         ;
1362         }
1363 }
1364 #endif