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