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