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