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