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