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