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