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