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