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