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