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