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