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