viced-cblater-unmark-20090605
[openafs.git] / src / viced / callback.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  * Portions Copyright (c) 2006 Sine Nomine Associates
10  */
11
12 /*
13  * NEW callback package callback.c (replaces vicecb.c)
14  * Updated call back routines, NOW with:
15  * 
16  *     Faster DeleteVenus (Now called DeleteAllCallBacks)
17  *     Call back breaking for volumes
18  *     Adaptive timeouts on call backs
19  *     Architected for Multi RPC
20  *     No locks (currently implicit vnode locks--these will go, to)
21  *     Delayed call back when rpc connection down.
22  *     Bulk break of delayed call backs when rpc connection
23  *         reestablished
24  *     Strict limit on number of call backs.
25  *
26  * InitCallBack(nblocks)
27  *     Initialize: nblocks is max number # of file entries + # of callback entries
28  *     nblocks must be < 65536
29  *     Space used is nblocks*16 bytes
30  *     Note that space will be reclaimed by breaking callbacks of old hosts
31  * 
32  * time = AddCallBack(host, fid)
33  *     Add a call back.
34  *     Returns the expiration time at the workstation.
35  * 
36  * BreakCallBack(host, fid)
37  *     Break all call backs for fid, except for the specified host.
38  *     Delete all of them.
39  * 
40  * BreakVolumeCallBacks(volume)
41  *     Break all call backs on volume, using single call to each host
42  *     Delete all the call backs.
43  * 
44  * DeleteCallBack(host,fid)
45  *     Delete (do not break) single call back for fid.
46  * 
47  * DeleteFileCallBacks(fid)
48  *     Delete (do not break) all call backs for fid.
49  *
50  * DeleteAllCallBacks(host)
51  *     Delete (do not break) all call backs for host.
52  * 
53  * CleanupTimedOutCallBacks()
54  *     Delete all timed out call back entries
55  *     Must be called periodically by file server.
56  * 
57  * BreakDelayedCallBacks(host)
58  *     Break all delayed call backs for host.
59  *     Returns 1: one or more failed, 0: success.
60  * 
61  * PrintCallBackStats()
62  *     Print statistics about call backs to stdout.
63  * 
64  * DumpCallBacks() ---wishful thinking---
65  *     Dump call back state to /tmp/callback.state.
66  *     This is separately interpretable by the program pcb.
67  *
68  * Notes:  In general, if a call back to a host doesn't get through,
69  * then HostDown, supplied elsewhere, is called.  BreakDelayedCallBacks,
70  * however, does not call HostDown, but instead returns an indication of
71  * success if all delayed call backs were finally broken.
72  *
73  * BreakDelayedCallBacks MUST be called at the first sign of activity
74  * from the host after HostDown has been called (or a previous
75  * BreakDelayedCallBacks failed). The BreakDelayedCallBacks must be
76  * allowed to complete before any requests from that host are handled.
77  * If BreakDelayedCallBacks fails, then the host should remain
78  * down (and the request should be failed).
79
80  * CleanupCallBacks MUST be called periodically by the file server for
81  * this package to work correctly.  Every 5 minutes is suggested.
82  */
83
84 #include <afsconfig.h>
85 #include <afs/param.h>
86
87 RCSID
88     ("$Header$");
89
90 #include <stdio.h>
91 #include <stdlib.h>             /* for malloc() */
92 #include <time.h>               /* ANSI standard location for time stuff */
93 #include <string.h>
94 #ifdef AFS_NT40_ENV
95 #include <fcntl.h>
96 #include <io.h>
97 #else
98 #include <sys/time.h>
99 #include <sys/file.h>
100 #endif
101 #include <afs/assert.h>
102
103 #include <afs/stds.h>
104
105 #include <afs/nfs.h>            /* yuck.  This is an abomination. */
106 #include <lwp.h>
107 #include <rx/rx.h>
108 #include <afscbint.h>
109 #include <afs/afsutil.h>
110 #include <lock.h>
111 #include <afs/ihandle.h>
112 #include <afs/vnode.h>
113 #include <afs/volume.h>
114 #include "viced_prototypes.h"
115 #include "viced.h"
116
117 #include <afs/ptclient.h>       /* need definition of prlist for host.h */
118 #include "host.h"
119 #include "callback.h"
120 #ifdef AFS_DEMAND_ATTACH_FS
121 #include "../tviced/serialize_state.h"
122 #endif /* AFS_DEMAND_ATTACH_FS */
123
124
125 extern afsUUID FS_HostUUID;
126 extern int hostCount;
127
128 #ifndef INTERPRET_DUMP
129 static int ShowProblems = 1;
130 #endif
131
132 struct cbcounters cbstuff;
133
134 static struct FileEntry * FE = NULL;    /* don't use FE[0] */
135 static struct CallBack * CB = NULL;     /* don't use CB[0] */
136
137 static struct CallBack * CBfree = NULL;
138 static struct FileEntry * FEfree = NULL;
139
140
141 /* Time to live for call backs depends upon number of users of the file.
142  * TimeOuts is indexed by this number/8 (using TimeOut macro).  Times
143  * in this table are for the workstation; server timeouts, add
144  * ServerBias */
145
146 static int TimeOuts[] = {
147 /* Note: don't make the first entry larger than 4 hours (see above) */
148     4 * 60 * 60,                /* 0-7 users */
149     1 * 60 * 60,                /* 8-15 users */
150     30 * 60,                    /* 16-23 users */
151     15 * 60,                    /* 24-31 users */
152     15 * 60,                    /* 32-39 users */
153     10 * 60,                    /* 40-47 users */
154     10 * 60,                    /* 48-55 users */
155     10 * 60,                    /* 56-63 users */
156 };                              /* Anything more: MinTimeOut */
157
158 /* minimum time given for a call back */
159 #ifndef INTERPRET_DUMP
160 static int MinTimeOut = (7 * 60);
161 #endif
162
163 /* Heads of CB queues; a timeout index is 1+index into this array */
164 static afs_uint32 timeout[CB_NUM_TIMEOUT_QUEUES];
165
166 static afs_int32 tfirst;        /* cbtime of oldest unexpired call back time queue */
167
168
169 /* 16 byte object get/free routines */
170 struct object {
171     struct object *next;
172 };
173
174 /* Prototypes for static routines */
175 static struct FileEntry *FindFE(register AFSFid * fid);
176
177 #ifndef INTERPRET_DUMP
178 static struct CallBack *iGetCB(register int *nused);
179 static int iFreeCB(register struct CallBack *cb, register int *nused);
180 static struct FileEntry *iGetFE(register int *nused);
181 static int iFreeFE(register struct FileEntry *fe, register int *nused);
182 static int TAdd(register struct CallBack *cb, register afs_uint32 * thead);
183 static int TDel(register struct CallBack *cb);
184 static int HAdd(register struct CallBack *cb, register struct host *host);
185 static int HDel(register struct CallBack *cb);
186 static int CDel(struct CallBack *cb, int deletefe);
187 static int CDelPtr(register struct FileEntry *fe, register afs_uint32 * cbp,
188                    int deletefe);
189 static afs_uint32 *FindCBPtr(struct FileEntry *fe, struct host *host);
190 static int FDel(register struct FileEntry *fe);
191 static int AddCallBack1_r(struct host *host, AFSFid * fid, afs_uint32 * thead,
192                           int type, int locked);
193 static void MultiBreakCallBack_r(struct cbstruct cba[], int ncbas,
194                                  struct AFSCBFids *afidp, struct host *xhost);
195 static int MultiBreakVolumeCallBack_r(struct host *host, int isheld,
196                                       struct VCBParams *parms, int deletefe);
197 static int MultiBreakVolumeCallBack(struct host *host, int isheld,
198                                     void *rock);
199 static int MultiBreakVolumeLaterCallBack(struct host *host, int isheld,
200                                          void *rock);
201 static int GetSomeSpace_r(struct host *hostp, int locked);
202 static int ClearHostCallbacks_r(struct host *hp, int locked);
203 #endif
204
205 #define GetCB() ((struct CallBack *)iGetCB(&cbstuff.nCBs))
206 #define GetFE() ((struct FileEntry *)iGetFE(&cbstuff.nFEs))
207 #define FreeCB(cb) iFreeCB((struct CallBack *)cb, &cbstuff.nCBs)
208 #define FreeFE(fe) iFreeFE((struct FileEntry *)fe, &cbstuff.nFEs)
209
210
211 /* Other protos - move out sometime */
212 void PrintCB(register struct CallBack *cb, afs_uint32 now);
213
214 static afs_uint32 HashTable[FEHASH_SIZE];       /* File entry hash table */
215
216 static struct FileEntry *
217 FindFE(register AFSFid * fid)
218 {
219     int hash;
220     register int fei;
221     register struct FileEntry *fe;
222
223     hash = FEHash(fid->Volume, fid->Unique);
224     for (fei = HashTable[hash]; fei; fei = fe->fnext) {
225         fe = itofe(fei);
226         if (fe->volid == fid->Volume && fe->unique == fid->Unique
227             && fe->vnode == fid->Vnode && (fe->status & FE_LATER) != FE_LATER)
228             return fe;
229     }
230     return 0;
231 }
232
233 #ifndef INTERPRET_DUMP
234
235 static struct CallBack *
236 iGetCB(register int *nused)
237 {
238     register struct CallBack *ret;
239
240     if ((ret = CBfree)) {
241         CBfree = (struct CallBack *)(((struct object *)ret)->next);
242         (*nused)++;
243     }
244     return ret;
245 }
246
247 static int
248 iFreeCB(register struct CallBack *cb, register int *nused)
249 {
250     ((struct object *)cb)->next = (struct object *)CBfree;
251     CBfree = cb;
252     (*nused)--;
253     return 0;
254 }
255
256 static struct FileEntry *
257 iGetFE(register int *nused)
258 {
259     register struct FileEntry *ret;
260
261     if ((ret = FEfree)) {
262         FEfree = (struct FileEntry *)(((struct object *)ret)->next);
263         (*nused)++;
264     }
265     return ret;
266 }
267
268 static int
269 iFreeFE(register struct FileEntry *fe, register int *nused)
270 {
271     ((struct object *)fe)->next = (struct object *)FEfree;
272     FEfree = fe;
273     (*nused)--;
274     return 0;
275 }
276
277 /* Add cb to end of specified timeout list */
278 static int
279 TAdd(register struct CallBack *cb, register afs_uint32 * thead)
280 {
281     if (!*thead) {
282         (*thead) = cb->tnext = cb->tprev = cbtoi(cb);
283     } else {
284         register struct CallBack *thp = itocb(*thead);
285
286         cb->tprev = thp->tprev;
287         cb->tnext = *thead;
288         if (thp) {
289             if (thp->tprev)
290                 thp->tprev = (itocb(thp->tprev)->tnext = cbtoi(cb));
291             else
292                 thp->tprev = cbtoi(cb);
293         }
294     }
295     cb->thead = ttoi(thead);
296     return 0;
297 }
298
299 /* Delete call back entry from timeout list */
300 static int
301 TDel(register struct CallBack *cb)
302 {
303     register afs_uint32 *thead = itot(cb->thead);
304
305     if (*thead == cbtoi(cb))
306         *thead = (*thead == cb->tnext ? 0 : cb->tnext);
307     if (itocb(cb->tprev))
308         itocb(cb->tprev)->tnext = cb->tnext;
309     if (itocb(cb->tnext))
310         itocb(cb->tnext)->tprev = cb->tprev;
311     return 0;
312 }
313
314 /* Add cb to end of specified host list */
315 static int
316 HAdd(register struct CallBack *cb, register struct host *host)
317 {
318     cb->hhead = h_htoi(host);
319     if (!host->cblist) {
320         host->cblist = cb->hnext = cb->hprev = cbtoi(cb);
321     } else {
322         register struct CallBack *fcb = itocb(host->cblist);
323
324         cb->hprev = fcb->hprev;
325         cb->hnext = cbtoi(fcb);
326         fcb->hprev = (itocb(fcb->hprev)->hnext = cbtoi(cb));
327     }
328     return 0;
329 }
330
331 /* Delete call back entry from host list */
332 static int
333 HDel(register struct CallBack *cb)
334 {
335     register afs_uint32 *hhead = &h_itoh(cb->hhead)->cblist;
336
337     if (*hhead == cbtoi(cb))
338         *hhead = (*hhead == cb->hnext ? 0 : cb->hnext);
339     itocb(cb->hprev)->hnext = cb->hnext;
340     itocb(cb->hnext)->hprev = cb->hprev;
341     return 0;
342 }
343
344 /* Delete call back entry from fid's chain of cb's */
345 /* N.B.  This one also deletes the CB, and also possibly parent FE, so
346  * make sure that it is not on any other list before calling this
347  * routine */
348 static int
349 CDel(struct CallBack *cb, int deletefe)
350 {
351     int cbi = cbtoi(cb);
352     struct FileEntry *fe = itofe(cb->fhead);
353     register afs_uint32 *cbp;
354     register int safety;
355
356     for (safety = 0, cbp = &fe->firstcb; *cbp && *cbp != cbi;
357          cbp = &itocb(*cbp)->cnext, safety++) {
358         if (safety > cbstuff.nblks + 10) {
359             assert(0);
360             ViceLog(0,
361                     ("CDel: Internal Error -- shutting down: wanted %d from %d, now at %d\n",
362                      cbi, fe->firstcb, *cbp));
363             DumpCallBackState();
364             ShutDownAndCore(PANIC);
365         }
366     }
367     CDelPtr(fe, cbp, deletefe);
368     return 0;
369 }
370
371 /* Same as CDel, but pointer to parent pointer to CB entry is passed,
372  * as well as file entry */
373 /* N.B.  This one also deletes the CB, and also possibly parent FE, so
374  * make sure that it is not on any other list before calling this
375  * routine */
376 static int Ccdelpt = 0, CcdelB = 0;
377
378 static int
379 CDelPtr(register struct FileEntry *fe, register afs_uint32 * cbp,
380         int deletefe)
381 {
382     register struct CallBack *cb;
383
384     if (!*cbp)
385         return 0;
386     Ccdelpt++;
387     cb = itocb(*cbp);
388     if (cb != &CB[*cbp])
389         CcdelB++;
390     *cbp = cb->cnext;
391     FreeCB(cb);
392     if ((--fe->ncbs == 0) && deletefe)
393         FDel(fe);
394     return 0;
395 }
396
397 static afs_uint32 *
398 FindCBPtr(struct FileEntry *fe, struct host *host)
399 {
400     register afs_uint32 hostindex = h_htoi(host);
401     register struct CallBack *cb;
402     register afs_uint32 *cbp;
403     register int safety;
404
405     for (safety = 0, cbp = &fe->firstcb; *cbp; cbp = &cb->cnext, safety++) {
406         if (safety > cbstuff.nblks) {
407             ViceLog(0, ("FindCBPtr: Internal Error -- shutting down.\n"));
408             DumpCallBackState();
409             ShutDownAndCore(PANIC);
410         }
411         cb = itocb(*cbp);
412         if (cb->hhead == hostindex)
413             break;
414     }
415     return cbp;
416 }
417
418 /* Delete file entry from hash table */
419 static int
420 FDel(register struct FileEntry *fe)
421 {
422     register int fei = fetoi(fe);
423     register afs_uint32 *p = &HashTable[FEHash(fe->volid, fe->unique)];
424
425     while (*p && *p != fei)
426         p = &itofe(*p)->fnext;
427     assert(*p);
428     *p = fe->fnext;
429     FreeFE(fe);
430     return 0;
431 }
432
433 /* initialize the callback package */
434 int
435 InitCallBack(int nblks)
436 {
437     H_LOCK;
438     tfirst = CBtime(FT_ApproxTime());
439     /* N.B. The "-1", below, is because
440      * FE[0] and CB[0] are not used--and not allocated */
441     FE = ((struct FileEntry *)(calloc(nblks, sizeof(struct FileEntry))));
442     if (!FE) {
443         ViceLog(0, ("Failed malloc in InitCallBack\n"));
444         assert(0);
445     }
446     FE--;  /* FE[0] is supposed to point to junk */
447     cbstuff.nFEs = nblks;
448     while (cbstuff.nFEs)
449         FreeFE(&FE[cbstuff.nFEs]);      /* This is correct */
450     CB = ((struct CallBack *)(calloc(nblks, sizeof(struct CallBack))));
451     if (!CB) {
452         ViceLog(0, ("Failed malloc in InitCallBack\n"));
453         assert(0);
454     }
455     CB--;  /* CB[0] is supposed to point to junk */
456     cbstuff.nCBs = nblks;
457     while (cbstuff.nCBs)
458         FreeCB(&CB[cbstuff.nCBs]);      /* This is correct */
459     cbstuff.nblks = nblks;
460     cbstuff.nbreakers = 0;
461     H_UNLOCK;
462     return 0;
463 }
464
465 afs_int32
466 XCallBackBulk_r(struct host * ahost, struct AFSFid * fids, afs_int32 nfids)
467 {
468     struct AFSCallBack tcbs[AFSCBMAX];
469     register int i;
470     struct AFSCBFids tf;
471     struct AFSCBs tc;
472     int code;
473     int j;
474     struct rx_connection *cb_conn = NULL;
475
476 #ifdef  ADAPT_MTU
477     rx_SetConnDeadTime(ahost->callback_rxcon, 4);
478     rx_SetConnHardDeadTime(ahost->callback_rxcon, AFS_HARDDEADTIME);
479 #endif
480
481     code = 0;
482     j = 0;
483     while (nfids > 0) {
484
485         for (i = 0; i < nfids && i < AFSCBMAX; i++) {
486             tcbs[i].CallBackVersion = CALLBACK_VERSION;
487             tcbs[i].ExpirationTime = 0;
488             tcbs[i].CallBackType = CB_DROPPED;
489         }
490         tf.AFSCBFids_len = i;
491         tf.AFSCBFids_val = &(fids[j]);
492         nfids -= i;
493         j += i;
494         tc.AFSCBs_len = i;
495         tc.AFSCBs_val = tcbs;
496
497         cb_conn = ahost->callback_rxcon;
498         rx_GetConnection(cb_conn);
499         H_UNLOCK;
500         code |= RXAFSCB_CallBack(cb_conn, &tf, &tc);
501         rx_PutConnection(cb_conn);
502         cb_conn = NULL;
503         H_LOCK;
504     }
505
506     return code;
507 }
508
509 /* the locked flag tells us if the host entry has already been locked 
510  * by our parent.  I don't think anybody actually calls us with the
511  * host locked, but here's how to make that work:  GetSomeSpace has to
512  * change so that it doesn't attempt to lock any hosts < "host".  That
513  * means that it might be unable to free any objects, so it has to
514  * return an exit status.  If it fails, then AddCallBack1 might fail,
515  * as well. If so, the host->ResetDone should probably be set to 0,
516  * and we probably don't want to return a callback promise to the
517  * cache manager, either. */
518 int
519 AddCallBack1(struct host *host, AFSFid * fid, afs_uint32 * thead, int type,
520              int locked)
521 {
522     int retVal;
523     H_LOCK;
524     if (!locked) {
525         h_Lock_r(host);
526     }
527     retVal = AddCallBack1_r(host, fid, thead, type, 1);
528
529     if (!locked) {
530         h_Unlock_r(host);
531     }
532     H_UNLOCK;
533     return retVal;
534 }
535
536 static int
537 AddCallBack1_r(struct host *host, AFSFid * fid, afs_uint32 * thead, int type,
538                int locked)
539 {
540     struct FileEntry *fe;
541     struct CallBack *cb = 0, *lastcb = 0;
542     struct FileEntry *newfe = 0;
543     afs_uint32 time_out = 0;
544     afs_uint32 *Thead = thead;
545     struct CallBack *newcb = 0;
546     int safety;
547
548     cbstuff.AddCallBacks++;
549
550     host->Console |= 2;
551
552     /* allocate these guys first, since we can't call the allocator with
553      * the host structure locked -- or we might deadlock. However, we have 
554      * to avoid races with FindFE... */
555     while (!(newcb = GetCB())) {
556         GetSomeSpace_r(host, locked);
557     }
558     while (!(newfe = GetFE())) {        /* Get it now, so we don't have to call */
559         /* GetSomeSpace with the host locked, later.  This might turn out to */
560         /* have been unneccessary, but that's actually kind of unlikely, since */
561         /* most files are not shared. */
562         GetSomeSpace_r(host, locked);
563     }
564
565     if (!locked) {
566         h_Lock_r(host);         /* this can yield, so do it before we get any */
567         /* fragile info */
568     }
569
570     fe = FindFE(fid);
571     if (type == CB_NORMAL) {
572         time_out =
573             TimeCeiling(FT_ApproxTime() + TimeOut(fe ? fe->ncbs : 0) +
574                         ServerBias);
575         Thead = THead(CBtime(time_out));
576     } else if (type == CB_VOLUME) {
577         time_out = TimeCeiling((60 * 120 + FT_ApproxTime()) + ServerBias);
578         Thead = THead(CBtime(time_out));
579     } else if (type == CB_BULK) {
580         /* bulk status can get so many callbacks all at once, and most of them
581          * are probably not for things that will be used for long.
582          */
583         time_out =
584             TimeCeiling(FT_ApproxTime() + ServerBias +
585                         TimeOut(22 + (fe ? fe->ncbs : 0)));
586         Thead = THead(CBtime(time_out));
587     }
588
589     host->Console &= ~2;
590
591     if (!fe) {
592         register afs_uint32 hash;
593
594         fe = newfe;
595         newfe = NULL;
596         fe->firstcb = 0;
597         fe->volid = fid->Volume;
598         fe->vnode = fid->Vnode;
599         fe->unique = fid->Unique;
600         fe->ncbs = 0;
601         fe->status = 0;
602         hash = FEHash(fid->Volume, fid->Unique);
603         fe->fnext = HashTable[hash];
604         HashTable[hash] = fetoi(fe);
605     }
606     for (safety = 0, lastcb = cb = itocb(fe->firstcb); cb;
607          lastcb = cb, cb = itocb(cb->cnext), safety++) {
608         if (safety > cbstuff.nblks) {
609             ViceLog(0, ("AddCallBack1: Internal Error -- shutting down.\n"));
610             DumpCallBackState();
611             ShutDownAndCore(PANIC);
612         }
613         if (cb->hhead == h_htoi(host))
614             break;
615     }
616     if (cb) {                   /* Already have call back:  move to new timeout list */
617         /* don't change delayed callbacks back to normal ones */
618         if (cb->status != CB_DELAYED)
619             cb->status = type;
620         /* Only move if new timeout is longer */
621         if (TNorm(ttoi(Thead)) > TNorm(cb->thead)) {
622             TDel(cb);
623             TAdd(cb, Thead);
624         }
625         if (newfe == NULL) {    /* we are using the new FE */
626             fe->firstcb = cbtoi(cb);
627             fe->ncbs++;
628             cb->fhead = fetoi(fe);
629         }
630     } else {
631         cb = newcb;
632         newcb = NULL;
633         *(lastcb ? &lastcb->cnext : &fe->firstcb) = cbtoi(cb);
634         fe->ncbs++;
635         cb->cnext = 0;
636         cb->fhead = fetoi(fe);
637         cb->status = type;
638         HAdd(cb, host);
639         TAdd(cb, Thead);
640     }
641
642     /* now free any still-unused callback or host entries */
643     if (newcb)
644         FreeCB(newcb);
645     if (newfe)
646         FreeFE(newfe);
647
648     if (!locked)                /* freecb and freefe might(?) yield */
649         h_Unlock_r(host);
650
651     if (type == CB_NORMAL || type == CB_VOLUME || type == CB_BULK)
652         return time_out - ServerBias;   /* Expires sooner at workstation */
653
654     return 0;
655 }
656
657 static int
658 CompareCBA(const void *e1, const void *e2)
659 {
660     const struct cbstruct *cba1 = (const struct cbstruct *)e1;
661     const struct cbstruct *cba2 = (const struct cbstruct *)e2;
662     return ((cba1->hp)->index - (cba2->hp)->index);
663 }
664
665 /* Take an array full of hosts, all held.  Break callbacks to them, and 
666  * release the holds once you're done, except don't release xhost.  xhost 
667  * may be NULL.  Currently only works for a single Fid in afidp array.
668  * If you want to make this work with multiple fids, you need to fix
669  * the error handling.  One approach would be to force a reset if a
670  * multi-fid call fails, or you could add delayed callbacks for each
671  * fid.   You probably also need to sort and remove duplicate hosts.
672  * When this is called from the BreakVolumeCallBacks path, it does NOT 
673  * force a reset if the RPC fails, it just marks the host down and tries 
674  * to create a delayed callback. */
675 /* N.B.  be sure that code works when ncbas == 0 */
676 /* N.B.  requires all the cba[*].hp pointers to be valid... */
677 /* This routine does not hold a lock on the host for the duration of 
678  * the BreakCallBack RPC, which is a significant deviation from tradition.
679  * It _does_ get a lock on the host before setting VenusDown = 1,
680  * which is sufficient only if VenusDown = 0 only happens when the
681  * lock is held over the RPC and the subsequent VenusDown == 0
682  * wherever that is done. */
683 static void
684 MultiBreakCallBack_r(struct cbstruct cba[], int ncbas,
685                      struct AFSCBFids *afidp, struct host *xhost)
686 {
687     int i, j;
688     struct rx_connection *conns[MAX_CB_HOSTS];
689     static struct AFSCBs tc = { 0, 0 };
690     int multi_to_cba_map[MAX_CB_HOSTS];
691
692     assert(ncbas <= MAX_CB_HOSTS);
693
694     /* sort cba list to avoid makecall issues */
695     qsort(cba, ncbas, sizeof(struct cbstruct), CompareCBA);
696
697     /* set up conns for multi-call */
698     for (i = 0, j = 0; i < ncbas; i++) {
699         struct host *thishost = cba[i].hp;
700         if (!thishost || (thishost->hostFlags & HOSTDELETED)) {
701             continue;
702         }
703         rx_GetConnection(thishost->callback_rxcon);
704         multi_to_cba_map[j] = i;
705         conns[j++] = thishost->callback_rxcon;
706
707 #ifdef  ADAPT_MTU
708         rx_SetConnDeadTime(thishost->callback_rxcon, 4);
709         rx_SetConnHardDeadTime(thishost->callback_rxcon, AFS_HARDDEADTIME);
710 #endif
711     }
712
713     if (j) {                    /* who knows what multi would do with 0 conns? */
714         cbstuff.nbreakers++;
715         H_UNLOCK;
716         multi_Rx(conns, j) {
717             multi_RXAFSCB_CallBack(afidp, &tc);
718             if (multi_error) {
719                 afs_uint32 idx;
720                 struct host *hp;
721                 char hoststr[16];
722
723                 i = multi_to_cba_map[multi_i];
724                 hp = cba[i].hp;
725                 idx = cba[i].thead;
726
727                 if (!hp || !idx) {
728                     ViceLog(0,
729                             ("BCB: INTERNAL ERROR: hp=%x, cba=%x, thead=%u\n", 
730                              hp, cba, idx));
731                 } else {
732                     /* 
733                      ** try breaking callbacks on alternate interface addresses
734                      */
735                     if (MultiBreakCallBackAlternateAddress(hp, afidp)) {
736                         if (ShowProblems) {
737                             ViceLog(7,
738                                     ("BCB: Failed on file %u.%u.%u, Host %x (%s:%d) is down\n",
739                                      afidp->AFSCBFids_val->Volume,
740                                      afidp->AFSCBFids_val->Vnode,
741                                      afidp->AFSCBFids_val->Unique,
742                                      hp,
743                                      afs_inet_ntoa_r(hp->host, hoststr),
744                                      ntohs(hp->port)));
745                         }
746
747                         H_LOCK;
748                         h_Lock_r(hp); 
749                         hp->hostFlags |= VENUSDOWN;
750                 /**
751                   * We always go into AddCallBack1_r with the host locked
752                   */
753                         AddCallBack1_r(hp, afidp->AFSCBFids_val, itot(idx),
754                                        CB_DELAYED, 1);
755                         h_Unlock_r(hp); 
756                         H_UNLOCK;
757                     }
758                 }
759             }
760         }
761         multi_End;
762         H_LOCK;
763         cbstuff.nbreakers--;
764     }
765
766     for (i = 0; i < ncbas; i++) {
767         struct host *hp;
768         hp = cba[i].hp;
769         if (hp && xhost != hp) {
770             h_Release_r(hp);
771         }
772     }
773
774     /* H_UNLOCK around this so h_FreeConnection does not deadlock.
775        h_FreeConnection should *never* be called on a callback connection,
776        but on 10/27/04 a deadlock occurred where it was, when we know why,
777        this should be reverted. -- shadow */
778     H_UNLOCK;
779     for (i = 0; i < j; i++) {
780         rx_PutConnection(conns[i]);
781     }
782     H_LOCK;
783
784     return;
785 }
786
787 /*
788  * Break all call backs for fid, except for the specified host (unless flag
789  * is true, in which case all get a callback message. Assumption: the specified
790  * host is h_Held, by the caller; the others aren't.
791  * Specified host may be bogus, that's ok.  This used to check to see if the 
792  * host was down in two places, once right after the host was h_held, and 
793  * again after it was locked.  That race condition is incredibly rare and
794  * relatively harmless even when it does occur, so we don't check for it now. 
795  */
796 /* if flag is true, send a break callback msg to "host", too */
797 int
798 BreakCallBack(struct host *xhost, AFSFid * fid, int flag)
799 {
800     struct FileEntry *fe;
801     struct CallBack *cb, *nextcb;
802     struct cbstruct cba[MAX_CB_HOSTS];
803     int ncbas;
804     struct AFSCBFids tf;
805     int hostindex;
806     char hoststr[16];
807
808     ViceLog(7,
809             ("BCB: BreakCallBack(Host %x all but %s:%d, (%u,%u,%u))\n",
810              xhost, afs_inet_ntoa_r(xhost->host, hoststr), ntohs(xhost->port),
811              fid->Volume, fid->Vnode, fid->Unique));
812
813     H_LOCK;
814     cbstuff.BreakCallBacks++;
815     fe = FindFE(fid);
816     if (!fe) {
817         goto done;
818     }
819     hostindex = h_htoi(xhost);
820     cb = itocb(fe->firstcb);
821     if (!cb || ((fe->ncbs == 1) && (cb->hhead == hostindex) && !flag)) {
822         /* the most common case is what follows the || */
823         goto done;
824     }
825     tf.AFSCBFids_len = 1;
826     tf.AFSCBFids_val = fid;
827
828     for (; cb;) {
829         for (ncbas = 0; cb && ncbas < MAX_CB_HOSTS; cb = nextcb) {
830             nextcb = itocb(cb->cnext);
831             if ((cb->hhead != hostindex || flag)
832                 && (cb->status == CB_BULK || cb->status == CB_NORMAL
833                     || cb->status == CB_VOLUME)) {
834                 struct host *thishost = h_itoh(cb->hhead);
835                 if (!thishost) {
836                     ViceLog(0, ("BCB: BOGUS! cb->hhead is NULL!\n"));
837                 } else if (thishost->hostFlags & VENUSDOWN) {
838                     ViceLog(7,
839                             ("BCB: %x (%s:%d) is down; delaying break call back\n",
840                              thishost, afs_inet_ntoa_r(thishost->host, hoststr),
841                              ntohs(thishost->port)));
842                     cb->status = CB_DELAYED;
843                 } else {
844                     h_Hold_r(thishost);
845                     cba[ncbas].hp = thishost;
846                     cba[ncbas].thead = cb->thead;
847                     ncbas++;
848                     TDel(cb);
849                     HDel(cb);
850                     CDel(cb, 1);        /* Usually first; so this delete 
851                                          * is reasonably inexpensive */
852                 }
853             }
854         }
855
856         if (ncbas) {
857             MultiBreakCallBack_r(cba, ncbas, &tf, xhost);
858
859             /* we need to to all these initializations again because MultiBreakCallBack may block */
860             fe = FindFE(fid);
861             if (!fe) {
862                 goto done;
863             }
864             cb = itocb(fe->firstcb);
865             if (!cb || ((fe->ncbs == 1) && (cb->hhead == hostindex) && !flag)) {
866                 /* the most common case is what follows the || */
867                 goto done;
868             }
869         }
870     }
871
872   done:
873     H_UNLOCK;
874     return 0;
875 }
876
877 /* Delete (do not break) single call back for fid */
878 int
879 DeleteCallBack(struct host *host, AFSFid * fid)
880 {
881     register struct FileEntry *fe;
882     register afs_uint32 *pcb;
883     char hoststr[16];
884
885     H_LOCK;
886     cbstuff.DeleteCallBacks++;
887
888     h_Lock_r(host);
889     fe = FindFE(fid);
890     if (!fe) {
891         h_Unlock_r(host);
892         H_UNLOCK;
893         ViceLog(8,
894                 ("DCB: No call backs for fid (%u, %u, %u)\n", fid->Volume,
895                  fid->Vnode, fid->Unique));
896         return 0;
897     }
898     pcb = FindCBPtr(fe, host);
899     if (!*pcb) {
900         ViceLog(8,
901                 ("DCB: No call back for host %x (%s:%d), (%u, %u, %u)\n",
902                  host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
903                  fid->Volume, fid->Vnode, fid->Unique));
904         h_Unlock_r(host);
905         H_UNLOCK;
906         return 0;
907     }
908     HDel(itocb(*pcb));
909     TDel(itocb(*pcb));
910     CDelPtr(fe, pcb, 1);
911     h_Unlock_r(host);
912     H_UNLOCK;
913     return 0;
914 }
915
916 /*
917  * Delete (do not break) all call backs for fid.  This call doesn't
918  * set all of the various host locks, but it shouldn't really matter
919  * since we're not adding callbacks, but deleting them.  I'm not sure
920  * why it doesn't set the lock, however; perhaps it should.
921  */
922 int
923 DeleteFileCallBacks(AFSFid * fid)
924 {
925     register struct FileEntry *fe;
926     register struct CallBack *cb;
927     register afs_uint32 cbi;
928     register int n;
929
930     H_LOCK;
931     cbstuff.DeleteFiles++;
932     fe = FindFE(fid);
933     if (!fe) {
934         H_UNLOCK;
935         ViceLog(8,
936                 ("DF: No fid (%u,%u,%u) to delete\n", fid->Volume, fid->Vnode,
937                  fid->Unique));
938         return 0;
939     }
940     for (n = 0, cbi = fe->firstcb; cbi; n++) {
941         cb = itocb(cbi);
942         cbi = cb->cnext;
943         TDel(cb);
944         HDel(cb);
945         FreeCB(cb);
946         fe->ncbs--;
947     }
948     FDel(fe);
949     H_UNLOCK;
950     return 0;
951 }
952
953 /* Delete (do not break) all call backs for host.  The host should be
954  * locked. */
955 int
956 DeleteAllCallBacks_r(struct host *host, int deletefe)
957 {
958     register struct CallBack *cb;
959     register int cbi, first;
960
961     cbstuff.DeleteAllCallBacks++;
962     cbi = first = host->cblist;
963     if (!cbi) {
964         ViceLog(8, ("DV: no call backs\n"));
965         return 0;
966     }
967     do {
968         cb = itocb(cbi);
969         cbi = cb->hnext;
970         TDel(cb);
971         CDel(cb, deletefe);
972     } while (cbi != first);
973     host->cblist = 0;
974     return 0;
975 }
976
977 /*
978  * Break all delayed call backs for host.  Returns 1 if all call backs
979  * successfully broken; 0 otherwise.  Assumes host is h_Held and h_Locked.
980  * Must be called with VenusDown set for this host
981  */
982 int
983 BreakDelayedCallBacks(struct host *host)
984 {
985     int retVal;
986     H_LOCK;
987     retVal = BreakDelayedCallBacks_r(host);
988     H_UNLOCK;
989     return retVal;
990 }
991
992 int
993 BreakDelayedCallBacks_r(struct host *host)
994 {
995     struct AFSFid fids[AFSCBMAX];
996     u_byte thead[AFSCBMAX];     /* This should match thead in struct Callback */
997     int cbi, first, nfids;
998     struct CallBack *cb;
999     int code;
1000     char hoststr[16];
1001     struct rx_connection *cb_conn;
1002
1003     cbstuff.nbreakers++;
1004     if (!(host->hostFlags & RESETDONE) && !(host->hostFlags & HOSTDELETED)) {
1005         host->hostFlags &= ~ALTADDR;    /* alternate addresses are invalid */
1006         cb_conn = host->callback_rxcon;
1007         rx_GetConnection(cb_conn);
1008         if (host->interface) {
1009             H_UNLOCK;
1010             code =
1011                 RXAFSCB_InitCallBackState3(cb_conn, &FS_HostUUID);
1012         } else {
1013             H_UNLOCK;
1014             code = RXAFSCB_InitCallBackState(cb_conn);
1015         }
1016         rx_PutConnection(cb_conn);
1017         cb_conn = NULL;
1018         H_LOCK;
1019         host->hostFlags |= ALTADDR;     /* alternate addresses are valid */
1020         if (code) {
1021             if (ShowProblems) {
1022                 ViceLog(0,
1023                         ("CB: Call back connect back failed (in break delayed) for Host %x (%s:%d)\n",
1024                          host, afs_inet_ntoa_r(host->host, hoststr),
1025                          ntohs(host->port)));
1026             }
1027             host->hostFlags |= VENUSDOWN;
1028         } else {
1029             ViceLog(25,
1030                     ("InitCallBackState success on %x (%s:%d)\n",
1031                      host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1032             /* reset was done successfully */
1033             host->hostFlags |= RESETDONE;
1034             host->hostFlags &= ~VENUSDOWN;
1035         }
1036     } else
1037         while (!(host->hostFlags & HOSTDELETED)) {
1038             nfids = 0;
1039             host->hostFlags &= ~VENUSDOWN;      /* presume up */
1040             cbi = first = host->cblist;
1041             if (!cbi)
1042                 break;
1043             do {
1044                 first = host->cblist;
1045                 cb = itocb(cbi);
1046                 cbi = cb->hnext;
1047                 if (cb->status == CB_DELAYED) {
1048                     register struct FileEntry *fe = itofe(cb->fhead);
1049                     thead[nfids] = cb->thead;
1050                     fids[nfids].Volume = fe->volid;
1051                     fids[nfids].Vnode = fe->vnode;
1052                     fids[nfids].Unique = fe->unique;
1053                     nfids++;
1054                     HDel(cb);
1055                     TDel(cb);
1056                     CDel(cb, 1);
1057                 }
1058             } while (cbi && cbi != first && nfids < AFSCBMAX);
1059
1060             if (nfids == 0) {
1061                 break;
1062             }
1063
1064             if (XCallBackBulk_r(host, fids, nfids)) {
1065                 /* Failed, again:  put them back, probably with old
1066                  * timeout values */
1067                 int i;
1068                 if (ShowProblems) {
1069                     ViceLog(0,
1070                             ("CB: XCallBackBulk failed, Host %x (%s:%d); callback list follows:\n",
1071                              host, afs_inet_ntoa_r(host->host, hoststr),
1072                              ntohs(host->port)));
1073                 }
1074                 for (i = 0; i < nfids; i++) {
1075                     if (ShowProblems) {
1076                         ViceLog(0,
1077                                 ("CB: Host %x (%s:%d), file %u.%u.%u (part of bulk callback)\n",
1078                                  host, afs_inet_ntoa_r(host->host, hoststr),
1079                                  ntohs(host->port), fids[i].Volume,
1080                                  fids[i].Vnode, fids[i].Unique));
1081                     }
1082                     /* used to do this:
1083                      * AddCallBack1_r(host, &fids[i], itot(thead[i]), CB_DELAYED, 1);
1084                      * * but it turns out to cause too many tricky locking problems.
1085                      * * now, if break delayed fails, screw it. */
1086                 }
1087                 host->hostFlags |= VENUSDOWN;   /* Failed */
1088                 ClearHostCallbacks_r(host, 1 /* locked */ );
1089                 nfids = 0;
1090                 break;
1091             }
1092             if (nfids < AFSCBMAX)
1093                 break;
1094         }
1095
1096     cbstuff.nbreakers--;
1097     /* If we succeeded it's always ok to unset HFE_LATER */
1098     if (!(host->hostFlags & VENUSDOWN))
1099         host->hostFlags &= ~HFE_LATER;
1100     return (host->hostFlags & VENUSDOWN);
1101 }
1102
1103 /*
1104 ** isheld is 0 if the host is held in h_Enumerate
1105 ** isheld is 1 if the host is held in BreakVolumeCallBacks
1106 */
1107 static int
1108 MultiBreakVolumeCallBack_r(struct host *host, int isheld,
1109                            struct VCBParams *parms, int deletefe)
1110 {
1111     char hoststr[16];
1112
1113     if (!isheld)
1114         return isheld;          /* host is held only by h_Enumerate, do nothing */
1115     if (host->hostFlags & HOSTDELETED)
1116         return 0;               /* host is deleted, release hold */
1117
1118     if (host->hostFlags & VENUSDOWN) {
1119         h_Lock_r(host);
1120         if (host->hostFlags & HOSTDELETED) {
1121             h_Unlock_r(host);
1122             return 0;           /* Release hold */
1123         }
1124         ViceLog(8,
1125                 ("BVCB: volume call back for Host %x (%s:%d) failed\n",
1126                  host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
1127         if (ShowProblems) {
1128             ViceLog(0,
1129                     ("CB: volume callback for Host %x (%s:%d) failed\n",
1130                      host, afs_inet_ntoa_r(host->host, hoststr),
1131                      ntohs(host->port)));
1132         }
1133         DeleteAllCallBacks_r(host, deletefe);   /* Delete all callback state 
1134                                                  * rather than attempting to 
1135                                                  * selectively remember to
1136                                                  * delete the volume callbacks
1137                                                  * later */
1138         host->hostFlags &= ~RESETDONE;  /* Do InitCallBackState when host returns */
1139         h_Unlock_r(host);
1140         return 0;               /* release hold */
1141     }
1142     assert(parms->ncbas <= MAX_CB_HOSTS);
1143
1144     /* Do not call MultiBreakCallBack on the current host structure
1145      ** because it would prematurely release the hold on the host
1146      */
1147     if (parms->ncbas == MAX_CB_HOSTS) {
1148         struct AFSCBFids tf;
1149
1150         tf.AFSCBFids_len = 1;
1151         tf.AFSCBFids_val = parms->fid;
1152
1153         /* this releases all the hosts */
1154         MultiBreakCallBack_r(parms->cba, parms->ncbas, &tf, 0 /* xhost */ );
1155
1156         parms->ncbas = 0;
1157     }
1158     parms->cba[parms->ncbas].hp = host;
1159     parms->cba[(parms->ncbas)++].thead = parms->thead;
1160     return 1;                   /* DON'T release hold, because we still need it. */
1161 }
1162
1163 /*
1164 ** isheld is 0 if the host is held in h_Enumerate
1165 ** isheld is 1 if the host is held in BreakVolumeCallBacks
1166 */
1167 static int
1168 MultiBreakVolumeCallBack(struct host *host, int isheld, void *rock)
1169 {
1170     struct VCBParams *parms = (struct VCBParams *) rock;
1171     
1172     int retval;
1173     H_LOCK;
1174     retval = MultiBreakVolumeCallBack_r(host, isheld, parms, 1);
1175     H_UNLOCK;
1176     return retval;
1177 }
1178
1179 /*
1180 ** isheld is 0 if the host is held in h_Enumerate
1181 ** isheld is 1 if the host is held in BreakVolumeCallBacks
1182 */
1183 static int
1184 MultiBreakVolumeLaterCallBack(struct host *host, int isheld, void *rock)
1185 {
1186     struct VCBParams *parms = (struct VCBParams *)rock;
1187     int retval;
1188     H_LOCK;
1189     retval = MultiBreakVolumeCallBack_r(host, isheld, parms, 0);
1190     H_UNLOCK;
1191     return retval;
1192 }
1193
1194 /*
1195  * Break all call backs on a single volume.  Don't call this with any
1196  * hosts h_held.  Note that this routine clears the callbacks before
1197  * actually breaking them, and that the vnode isn't locked during this
1198  * operation, so that people might see temporary callback loss while
1199  * this function is executing.  It is just a temporary state, however,
1200  * since the callback will be broken later by this same function.
1201  *
1202  * Now uses multi-RX for CallBack RPC.  Note that the
1203  * multiBreakCallBacks routine does not force a reset if the RPC
1204  * fails, unlike the previous version of this routine, but does create
1205  * a delayed callback.  Resets will be forced if the host is
1206  * determined to be down before the RPC is executed.
1207  */
1208 int
1209 BreakVolumeCallBacks(afs_uint32 volume)
1210 {
1211     struct AFSFid fid;
1212     int hash;
1213     afs_uint32 *feip;
1214     struct CallBack *cb;
1215     struct FileEntry *fe;
1216     struct host *host;
1217     struct VCBParams henumParms;
1218     afs_uint32 tthead = 0;      /* zero is illegal value */
1219
1220     H_LOCK;
1221     fid.Volume = volume, fid.Vnode = fid.Unique = 0;
1222     for (hash = 0; hash < FEHASH_SIZE; hash++) {
1223         for (feip = &HashTable[hash]; (fe = itofe(*feip));) {
1224             if (fe->volid == volume) {
1225                 register struct CallBack *cbnext;
1226                 for (cb = itocb(fe->firstcb); cb; cb = cbnext) {
1227                     host = h_itoh(cb->hhead);
1228                     h_Hold_r(host);
1229                     cbnext = itocb(cb->cnext);
1230                     if (!tthead || (TNorm(tthead) < TNorm(cb->thead))) {
1231                         tthead = cb->thead;
1232                     }
1233                     TDel(cb);
1234                     HDel(cb);
1235                     FreeCB(cb);
1236                     /* leave hold for MultiBreakVolumeCallBack to clear */
1237                 }
1238                 *feip = fe->fnext;
1239                 FreeFE(fe);
1240             } else {
1241                 feip = &fe->fnext;
1242             }
1243         }
1244     }
1245
1246     if (!tthead) {
1247         /* didn't find any callbacks, so return right away. */
1248         H_UNLOCK;
1249         return 0;
1250     }
1251     henumParms.ncbas = 0;
1252     henumParms.fid = &fid;
1253     henumParms.thead = tthead;
1254     H_UNLOCK;
1255     h_Enumerate(MultiBreakVolumeCallBack, &henumParms);
1256     H_LOCK;
1257     if (henumParms.ncbas) {     /* do left-overs */
1258         struct AFSCBFids tf;
1259         tf.AFSCBFids_len = 1;
1260         tf.AFSCBFids_val = &fid;
1261
1262         MultiBreakCallBack_r(henumParms.cba, henumParms.ncbas, &tf, 0);
1263
1264         henumParms.ncbas = 0;
1265     }
1266     H_UNLOCK;
1267     return 0;
1268 }
1269
1270 #ifdef AFS_PTHREAD_ENV
1271 extern pthread_cond_t fsync_cond;
1272 #else
1273 extern char fsync_wait[];
1274 #endif
1275
1276 int
1277 BreakVolumeCallBacksLater(afs_uint32 volume)
1278 {
1279     int hash;
1280     afs_uint32 *feip;
1281     struct FileEntry *fe;
1282     struct CallBack *cb;
1283     struct host *host;
1284     int found = 0;
1285
1286     ViceLog(25, ("Setting later on volume %u\n", volume));
1287     H_LOCK;
1288     for (hash = 0; hash < FEHASH_SIZE; hash++) {
1289         for (feip = &HashTable[hash]; (fe = itofe(*feip)) != NULL; ) {
1290             if (fe->volid == volume) {
1291                 register struct CallBack *cbnext;
1292                 for (cb = itocb(fe->firstcb); cb; cb = cbnext) {
1293                     host = h_itoh(cb->hhead);
1294                     host->hostFlags |= HFE_LATER;
1295                     cb->status = CB_DELAYED;
1296                     cbnext = itocb(cb->cnext);
1297                 }
1298                 FSYNC_LOCK;
1299                 fe->status |= FE_LATER;
1300                 FSYNC_UNLOCK;
1301                 found = 1;
1302             }
1303             feip = &fe->fnext;
1304         }
1305     }
1306     H_UNLOCK;
1307     if (!found) {
1308         /* didn't find any callbacks, so return right away. */
1309         return 0;
1310     }
1311
1312     ViceLog(25, ("Fsync thread wakeup\n"));
1313 #ifdef AFS_PTHREAD_ENV
1314     FSYNC_LOCK;
1315     assert(pthread_cond_broadcast(&fsync_cond) == 0);
1316     FSYNC_UNLOCK;
1317 #else
1318     LWP_NoYieldSignal(fsync_wait);
1319 #endif
1320     return 0;
1321 }
1322
1323 int
1324 BreakLaterCallBacks(void)
1325 {
1326     struct AFSFid fid;
1327     int hash;
1328     afs_uint32 *feip;
1329     struct CallBack *cb;
1330     struct FileEntry *fe = NULL;
1331     struct FileEntry *myfe = NULL;
1332     struct host *host;
1333     struct VCBParams henumParms;
1334     unsigned short tthead = 0;  /* zero is illegal value */
1335     char hoststr[16];
1336
1337     /* Unchain first */
1338     ViceLog(25, ("Looking for FileEntries to unchain\n"));
1339     H_LOCK;
1340     FSYNC_LOCK;
1341     /* Pick the first volume we see to clean up */
1342     fid.Volume = fid.Vnode = fid.Unique = 0;
1343
1344     for (hash = 0; hash < FEHASH_SIZE; hash++) {
1345         for (feip = &HashTable[hash]; (fe = itofe(*feip)) != NULL; ) {
1346             if (fe && (fe->status & FE_LATER)
1347                 && (fid.Volume == 0 || fid.Volume == fe->volid)) {
1348                 /* Ugly, but used to avoid left side casting */
1349                 struct object *tmpfe;
1350                 ViceLog(125,
1351                         ("Unchaining for %u:%u:%u\n", fe->vnode, fe->unique,
1352                          fe->volid));
1353                 fid.Volume = fe->volid;
1354                 *feip = fe->fnext;
1355                 fe->status &= ~FE_LATER; /* not strictly needed */
1356                 /* Works since volid is deeper than the largest pointer */
1357                 tmpfe = (struct object *)fe;
1358                 tmpfe->next = (struct object *)myfe;
1359                 myfe = fe;
1360             } else
1361                 feip = &fe->fnext;
1362         }
1363     }
1364     FSYNC_UNLOCK;
1365
1366     if (!myfe) {
1367         H_UNLOCK;
1368         return 0;
1369     }
1370
1371     /* loop over FEs from myfe and free/break */
1372     tthead = 0;
1373     for (fe = myfe; fe;) {
1374         register struct CallBack *cbnext;
1375         for (cb = itocb(fe->firstcb); cb; cb = cbnext) {
1376             cbnext = itocb(cb->cnext);
1377             host = h_itoh(cb->hhead);
1378             if (cb->status == CB_DELAYED) {
1379                 h_Hold_r(host);
1380                 if (!tthead || (TNorm(tthead) < TNorm(cb->thead))) {
1381                     tthead = cb->thead;
1382                 }
1383                 TDel(cb);
1384                 HDel(cb);
1385                 CDel(cb, 0);    /* Don't let CDel clean up the fe */
1386                 /* leave hold for MultiBreakVolumeCallBack to clear */
1387             } else {
1388                 ViceLog(125,
1389                         ("Found host %x (%s:%d) non-DELAYED cb for %u:%u:%u\n", 
1390                          host, afs_inet_ntoa_r(host->host, hoststr),
1391                          ntohs(host->port), fe->vnode, fe->unique, fe->volid));
1392             }
1393         }
1394         myfe = fe;
1395         fe = (struct FileEntry *)((struct object *)fe)->next;
1396         FreeFE(myfe);
1397     }
1398
1399     if (tthead) {
1400         ViceLog(125, ("Breaking volume %u\n", fid.Volume));
1401         henumParms.ncbas = 0;
1402         henumParms.fid = &fid;
1403         henumParms.thead = tthead;
1404         H_UNLOCK;
1405         h_Enumerate(MultiBreakVolumeLaterCallBack, (char *)&henumParms);
1406         H_LOCK;
1407         if (henumParms.ncbas) { /* do left-overs */
1408             struct AFSCBFids tf;
1409             tf.AFSCBFids_len = 1;
1410             tf.AFSCBFids_val = &fid;
1411
1412             MultiBreakCallBack_r(henumParms.cba, henumParms.ncbas, &tf, 0);
1413             henumParms.ncbas = 0;
1414         }
1415     }
1416     H_UNLOCK;
1417
1418     /* Arrange to be called again */
1419     return 1;
1420 }
1421
1422 /*
1423  * Delete all timed-out call back entries (to be called periodically by file
1424  * server)
1425  */
1426 int
1427 CleanupTimedOutCallBacks(void)
1428 {
1429     H_LOCK;
1430     CleanupTimedOutCallBacks_r();
1431     H_UNLOCK;
1432     return 0;
1433 }
1434
1435 int
1436 CleanupTimedOutCallBacks_r(void)
1437 {
1438     afs_uint32 now = CBtime(FT_ApproxTime());
1439     register afs_uint32 *thead;
1440     register struct CallBack *cb;
1441     register int ntimedout = 0;
1442     char hoststr[16];
1443
1444     while (tfirst <= now) {
1445         register int cbi;
1446         cbi = *(thead = THead(tfirst));
1447         if (cbi) {
1448             do {
1449                 cb = itocb(cbi);
1450                 cbi = cb->tnext;
1451                 ViceLog(8,
1452                         ("CCB: deleting timed out call back %x (%s:%d), (%u,%u,%u)\n",
1453                          h_itoh(cb->hhead)->host,
1454                          afs_inet_ntoa_r(h_itoh(cb->hhead)->host, hoststr),
1455                          h_itoh(cb->hhead)->port, itofe(cb->fhead)->volid,
1456                          itofe(cb->fhead)->vnode, itofe(cb->fhead)->unique));
1457                 HDel(cb);
1458                 CDel(cb, 1);
1459                 ntimedout++;
1460                 if (ntimedout > cbstuff.nblks) {
1461                     ViceLog(0, ("CCB: Internal Error -- shutting down...\n"));
1462                     DumpCallBackState();
1463                     ShutDownAndCore(PANIC);
1464                 }
1465             } while (cbi != *thead);
1466             *thead = 0;
1467         }
1468         tfirst++;
1469     }
1470     cbstuff.CBsTimedOut += ntimedout;
1471     ViceLog(7, ("CCB: deleted %d timed out callbacks\n", ntimedout));
1472     return (ntimedout > 0);
1473 }
1474
1475 static struct host *lih_host;
1476 static int lih_host_held;
1477
1478 /* This version does not allow 'host' to be selected unless its ActiveCall 
1479  * is newer than 'hostp' which is the host with the oldest ActiveCall from
1480  * the last pass (if it is provided).  We filter out any hosts that are
1481  * are held by other threads.
1482  */
1483 static int
1484 lih0_r(register struct host *host, register int held, void *rock)
1485 {
1486     struct host *hostp = (struct host *) rock;
1487     if (host->cblist
1488         && (hostp && host != hostp) 
1489         && (!held && !h_OtherHolds_r(host))
1490         && (!lih_host || host->ActiveCall < lih_host->ActiveCall) 
1491         && (!hostp || host->ActiveCall > hostp->ActiveCall)) {
1492         if (lih_host != NULL && lih_host_held) {
1493             h_Release_r(lih_host);
1494         }
1495         lih_host = host;
1496         lih_host_held = !held;
1497         held = 1;
1498     }
1499     return held;
1500 }
1501
1502 /* This version does not allow 'host' to be selected unless its ActiveCall 
1503  * is newer than 'hostp' which is the host with the oldest ActiveCall from
1504  * the last pass (if it is provided).  In this second varient, we do not 
1505  * prevent held hosts from being selected.
1506  */
1507 static int
1508 lih1_r(register struct host *host, register int held, void *rock)
1509 {
1510     struct host *hostp = (struct host *) rock;
1511
1512     if (host->cblist
1513         && (hostp && host != hostp) 
1514         && (!lih_host || host->ActiveCall < lih_host->ActiveCall) 
1515         && (!hostp || host->ActiveCall > hostp->ActiveCall)) {
1516         if (lih_host != NULL && lih_host_held) {
1517             h_Release_r(lih_host);
1518         }
1519         lih_host = host;
1520         lih_host_held = !held;
1521         held = 1;
1522     }
1523     return held;
1524 }
1525
1526 /* This could be upgraded to get more space each time */
1527 /* first pass: sequentially find the oldest host which isn't held by
1528                anyone for which we can clear callbacks;
1529                skipping 'hostp' */
1530 /* second pass: sequentially find the oldest host regardless of 
1531                whether or not the host is held; skipping 'hostp' */
1532 /* third pass: attempt to clear callbacks from 'hostp' */
1533 /* always called with hostp unlocked */
1534
1535 /* Note: hostlist is ordered most recently created host first and 
1536  * its order has no relationship to the most recently used. */
1537 extern struct host *hostList;
1538 static int
1539 GetSomeSpace_r(struct host *hostp, int locked)
1540 {
1541     register struct host *hp, *hp1, *hp2;
1542     int i = 0;
1543
1544     cbstuff.GotSomeSpaces++;
1545     ViceLog(5,
1546             ("GSS: First looking for timed out call backs via CleanupCallBacks\n"));
1547     if (CleanupTimedOutCallBacks_r()) {
1548         cbstuff.GSS3++;
1549         return 0;
1550     }
1551
1552     i = 0;
1553     hp1 = NULL;
1554     hp2 = hostList;
1555     do {
1556         lih_host = 0;
1557         h_Enumerate_r(i == 0 ? lih0_r : lih1_r, hp2, (char *)hp1);
1558         hp = lih_host;
1559         if (hp) {
1560             /* set in lih_r! private copy before giving up H_LOCK */
1561             int lih_host_held2=lih_host_held;   
1562             cbstuff.GSS4++;
1563             if ((hp != hostp) && !ClearHostCallbacks_r(hp, 0 /* not locked or held */ )) {
1564                 if (lih_host_held2)
1565                     h_Release_r(hp);
1566                 return 0;
1567             }
1568             if (lih_host_held2)
1569                 h_Release_r(hp);
1570             hp1 = hp;
1571             hp2 = hostList;
1572         } else {
1573             /*
1574              * Next time try getting callbacks from any host even if
1575              * it's deleted (that's actually great since we can freely
1576              * remove its callbacks) or it's held since the only other
1577              * option is starvation for the file server (i.e. until the
1578              * callback timeout arrives).
1579              */
1580             i++;
1581             hp1 = NULL;
1582             hp2 = hostList;
1583             cbstuff.GSS1++;
1584             ViceLog(5,
1585                     ("GSS: Try harder for longest inactive host cnt= %d\n",
1586                      i));
1587         }
1588     } while (i < 2);
1589
1590     /* Could not obtain space from other hosts, clear hostp's callback state */
1591     cbstuff.GSS2++;
1592     if (!locked) {
1593         h_Lock_r(hostp);
1594     }
1595     ClearHostCallbacks_r(hostp, 1 /*already locked */ );
1596     if (!locked) {
1597         h_Unlock_r(hostp);
1598     }
1599     return 0;
1600 }
1601
1602 /* locked - set if caller has already locked the host */
1603 static int
1604 ClearHostCallbacks_r(struct host *hp, int locked)
1605 {
1606     int code;
1607     int held = 0;
1608     char hoststr[16];
1609     struct rx_connection *cb_conn = NULL;
1610
1611     ViceLog(5,
1612             ("GSS: Delete longest inactive host %x (%s:%d)\n",
1613              hp, afs_inet_ntoa_r(hp->host, hoststr), ntohs(hp->port)));
1614     if (!(held = h_Held_r(hp)))
1615         h_Hold_r(hp);
1616
1617     /** Try a non-blocking lock. If the lock is already held return
1618       * after releasing hold on hp
1619       */
1620     if (!locked) {
1621         if (h_NBLock_r(hp)) {
1622             if (!held)
1623                 h_Release_r(hp);
1624             return 1;
1625         }
1626     }
1627     if (hp->Console & 2) {
1628         /*
1629          * If the special console field is set it means that a thread
1630          * is waiting in AddCallBack1 after it set pointers to the
1631          * file entry and/or callback entry. Because of the bogus
1632          * usage of h_hold it won't prevent from another thread, this
1633          * one, to remove all the callbacks so just to be safe we keep
1634          * a reference. NOTE, on the last phase we'll free the calling
1635          * host's callbacks but that's ok...
1636          */
1637         cbstuff.GSS5++;
1638     }
1639     DeleteAllCallBacks_r(hp, 1);
1640     if (hp->hostFlags & VENUSDOWN) {
1641         hp->hostFlags &= ~RESETDONE;    /* remember that we must do a reset */
1642     } else {
1643         /* host is up, try a call */
1644         hp->hostFlags &= ~ALTADDR;      /* alternate addresses are invalid */
1645         cb_conn = hp->callback_rxcon;
1646         rx_GetConnection(hp->callback_rxcon);
1647         if (hp->interface) {
1648             H_UNLOCK;
1649             code =
1650                 RXAFSCB_InitCallBackState3(cb_conn, &FS_HostUUID);
1651         } else {
1652             H_UNLOCK;
1653             code = RXAFSCB_InitCallBackState(cb_conn);
1654         }
1655         rx_PutConnection(cb_conn);
1656         cb_conn = NULL;
1657         H_LOCK;
1658         hp->hostFlags |= ALTADDR;       /* alternate addresses are valid */
1659         if (code) {
1660             /* failed, mark host down and need reset */
1661             hp->hostFlags |= VENUSDOWN;
1662             hp->hostFlags &= ~RESETDONE;
1663         } else {
1664             /* reset succeeded, we're done */
1665             hp->hostFlags |= RESETDONE;
1666         }
1667     }
1668     if (!locked) {
1669         h_Unlock_r(hp);
1670     }
1671     if (!held)
1672         h_Release_r(hp);
1673
1674     return 0;
1675 }
1676 #endif /* INTERPRET_DUMP */
1677
1678
1679 int
1680 PrintCallBackStats(void)
1681 {
1682     fprintf(stderr,
1683             "%d add CB, %d break CB, %d del CB, %d del FE, %d CB's timed out, %d space reclaim, %d del host\n",
1684             cbstuff.AddCallBacks, cbstuff.BreakCallBacks,
1685             cbstuff.DeleteCallBacks, cbstuff.DeleteFiles, cbstuff.CBsTimedOut,
1686             cbstuff.GotSomeSpaces, cbstuff.DeleteAllCallBacks);
1687     fprintf(stderr, "%d CBs, %d FEs, (%d of total of %d 16-byte blocks)\n",
1688             cbstuff.nCBs, cbstuff.nFEs, cbstuff.nCBs + cbstuff.nFEs,
1689             cbstuff.nblks);
1690
1691     return 0;
1692 }
1693
1694 #define MAGIC 0x12345678        /* To check byte ordering of dump when it is read in */
1695 #define MAGICV2 0x12345679      /* To check byte ordering & version of dump when it is read in */
1696
1697
1698 #ifndef INTERPRET_DUMP
1699
1700 #ifdef AFS_DEMAND_ATTACH_FS
1701 /*
1702  * demand attach fs
1703  * callback state serialization
1704  */
1705 static int cb_stateSaveTimeouts(struct fs_dump_state * state);
1706 static int cb_stateSaveFEHash(struct fs_dump_state * state);
1707 static int cb_stateSaveFEs(struct fs_dump_state * state);
1708 static int cb_stateSaveFE(struct fs_dump_state * state, struct FileEntry * fe);
1709 static int cb_stateRestoreTimeouts(struct fs_dump_state * state);
1710 static int cb_stateRestoreFEHash(struct fs_dump_state * state);
1711 static int cb_stateRestoreFEs(struct fs_dump_state * state);
1712 static int cb_stateRestoreFE(struct fs_dump_state * state);
1713 static int cb_stateRestoreCBs(struct fs_dump_state * state, struct FileEntry * fe, 
1714                               struct iovec * iov, int niovecs);
1715
1716 static int cb_stateVerifyFEHash(struct fs_dump_state * state);
1717 static int cb_stateVerifyFE(struct fs_dump_state * state, struct FileEntry * fe);
1718 static int cb_stateVerifyFCBList(struct fs_dump_state * state, struct FileEntry * fe);
1719 static int cb_stateVerifyTimeoutQueues(struct fs_dump_state * state);
1720
1721 static int cb_stateFEToDiskEntry(struct FileEntry *, struct FEDiskEntry *);
1722 static int cb_stateDiskEntryToFE(struct fs_dump_state * state,
1723                                  struct FEDiskEntry *, struct FileEntry *);
1724
1725 static int cb_stateCBToDiskEntry(struct CallBack *, struct CBDiskEntry *);
1726 static int cb_stateDiskEntryToCB(struct fs_dump_state * state,
1727                                  struct CBDiskEntry *, struct CallBack *);
1728
1729 static int cb_stateFillHeader(struct callback_state_header * hdr);
1730 static int cb_stateCheckHeader(struct callback_state_header * hdr);
1731
1732 static int cb_stateAllocMap(struct fs_dump_state * state);
1733
1734 int
1735 cb_stateSave(struct fs_dump_state * state)
1736 {
1737     int ret = 0;
1738
1739     AssignInt64(state->eof_offset, &state->hdr->cb_offset);
1740
1741     /* invalidate callback state header */
1742     memset(state->cb_hdr, 0, sizeof(struct callback_state_header));
1743     if (fs_stateWriteHeader(state, &state->hdr->cb_offset, state->cb_hdr,
1744                             sizeof(struct callback_state_header))) {
1745         ret = 1;
1746         goto done;
1747     }
1748
1749     fs_stateIncEOF(state, sizeof(struct callback_state_header));
1750
1751     /* dump timeout state */
1752     if (cb_stateSaveTimeouts(state)) {
1753         ret = 1;
1754         goto done;
1755     }
1756
1757     /* dump fe hashtable state */
1758     if (cb_stateSaveFEHash(state)) {
1759         ret = 1;
1760         goto done;
1761     }
1762
1763     /* dump callback state */
1764     if (cb_stateSaveFEs(state)) {
1765         ret = 1;
1766         goto done;
1767     }
1768
1769     /* write the callback state header to disk */
1770     cb_stateFillHeader(state->cb_hdr);
1771     if (fs_stateWriteHeader(state, &state->hdr->cb_offset, state->cb_hdr,
1772                             sizeof(struct callback_state_header))) {
1773         ret = 1;
1774         goto done;
1775     }
1776     
1777  done:
1778     return ret;
1779 }
1780
1781 int
1782 cb_stateRestore(struct fs_dump_state * state)
1783 {
1784     int ret = 0;
1785
1786     if (fs_stateReadHeader(state, &state->hdr->cb_offset, state->cb_hdr,
1787                            sizeof(struct callback_state_header))) {
1788         ret = 1;
1789         goto done;
1790     }
1791
1792     if (cb_stateCheckHeader(state->cb_hdr)) {
1793         ret = 1;
1794         goto done;
1795     }
1796
1797     if (cb_stateAllocMap(state)) {
1798         ret = 1;
1799         goto done;
1800     }
1801
1802     if (cb_stateRestoreTimeouts(state)) {
1803         ret = 1;
1804         goto done;
1805     }
1806
1807     if (cb_stateRestoreFEHash(state)) {
1808         ret = 1;
1809         goto done;
1810     }
1811
1812     /* restore FEs and CBs from disk */
1813     if (cb_stateRestoreFEs(state)) {
1814         ret = 1;
1815         goto done;
1816     }
1817
1818     /* restore the timeout queue heads */
1819     tfirst = state->cb_hdr->tfirst;
1820
1821  done:
1822     return ret;
1823 }
1824
1825 int
1826 cb_stateRestoreIndices(struct fs_dump_state * state)
1827 {
1828     int i, ret = 0;
1829     struct FileEntry * fe;
1830     struct CallBack * cb;
1831
1832     /* restore indices in the FileEntry structures */
1833     for (i = 1; i < state->fe_map.len; i++) {
1834         if (state->fe_map.entries[i].new_idx) {
1835             fe = itofe(state->fe_map.entries[i].new_idx);
1836
1837             /* restore the fe->fnext entry */
1838             if (fe_OldToNew(state, fe->fnext, &fe->fnext)) {
1839                 ret = 1;
1840                 goto done;
1841             }
1842
1843             /* restore the fe->firstcb entry */
1844             if (cb_OldToNew(state, fe->firstcb, &fe->firstcb)) {
1845                 ret = 1;
1846                 goto done;
1847             }
1848         }
1849     }
1850     
1851     /* restore indices in the CallBack structures */
1852     for (i = 1; i < state->cb_map.len; i++) {
1853         if (state->cb_map.entries[i].new_idx) {
1854             cb = itocb(state->cb_map.entries[i].new_idx);
1855
1856             /* restore the cb->cnext entry */
1857             if (cb_OldToNew(state, cb->cnext, &cb->cnext)) {
1858                 ret = 1;
1859                 goto done;
1860             }
1861             
1862             /* restore the cb->fhead entry */
1863             if (fe_OldToNew(state, cb->fhead, &cb->fhead)) {
1864                 ret = 1;
1865                 goto done;
1866             }
1867
1868             /* restore the cb->hhead entry */
1869             if (h_OldToNew(state, cb->hhead, &cb->hhead)) {
1870                 ret = 1;
1871                 goto done;
1872             }
1873
1874             /* restore the cb->tprev entry */
1875             if (cb_OldToNew(state, cb->tprev, &cb->tprev)) {
1876                 ret = 1;
1877                 goto done;
1878             }
1879
1880             /* restore the cb->tnext entry */
1881             if (cb_OldToNew(state, cb->tnext, &cb->tnext)) {
1882                 ret = 1;
1883                 goto done;
1884             }
1885
1886             /* restore the cb->hprev entry */
1887             if (cb_OldToNew(state, cb->hprev, &cb->hprev)) {
1888                 ret = 1;
1889                 goto done;
1890             }
1891
1892             /* restore the cb->hnext entry */
1893             if (cb_OldToNew(state, cb->hnext, &cb->hnext)) {
1894                 ret = 1;
1895                 goto done;
1896             }
1897         }
1898     }
1899
1900     /* restore the timeout queue head indices */
1901     for (i = 0; i < state->cb_timeout_hdr->records; i++) {
1902         if (cb_OldToNew(state, timeout[i], &timeout[i])) {
1903             ret = 1;
1904             goto done;
1905         }
1906     }
1907
1908     /* restore the FE hash table queue heads */
1909     for (i = 0; i < state->cb_fehash_hdr->records; i++) {
1910         if (fe_OldToNew(state, HashTable[i], &HashTable[i])) {
1911             ret = 1;
1912             goto done;
1913         }
1914     }
1915
1916  done:
1917     return ret;
1918 }
1919
1920 int
1921 cb_stateVerify(struct fs_dump_state * state)
1922 {
1923     int ret = 0;
1924
1925     if (cb_stateVerifyFEHash(state)) {
1926         ret = 1;
1927     }
1928
1929     if (cb_stateVerifyTimeoutQueues(state)) {
1930         ret = 1;
1931     }
1932
1933  done:
1934     return ret;
1935 }
1936
1937 static int
1938 cb_stateVerifyFEHash(struct fs_dump_state * state)
1939 {
1940     int ret = 0, i;
1941     struct FileEntry * fe;
1942     afs_uint32 fei, chain_len;
1943
1944     for (i = 0; i < FEHASH_SIZE; i++) {
1945         chain_len = 0;
1946         for (fei = HashTable[i], fe = itofe(fei);
1947              fe;
1948              fei = fe->fnext, fe = itofe(fei)) {
1949             if (fei > cbstuff.nblks) {
1950                 ViceLog(0, ("cb_stateVerifyFEHash: error: index out of range (fei=%d)\n", fei));
1951                 ret = 1;
1952                 break;
1953             }
1954             if (cb_stateVerifyFE(state, fe)) {
1955                 ret = 1;
1956             }
1957             if (chain_len > FS_STATE_FE_MAX_HASH_CHAIN_LEN) {
1958                 ViceLog(0, ("cb_stateVerifyFEHash: error: hash chain %d length exceeds %d; assuming there's a loop\n",
1959                             i, FS_STATE_FE_MAX_HASH_CHAIN_LEN));
1960                 ret = 1;
1961                 break;
1962             }
1963             chain_len++;
1964         }
1965     }
1966
1967  done:
1968     return ret;
1969 }
1970
1971 static int
1972 cb_stateVerifyFE(struct fs_dump_state * state, struct FileEntry * fe)
1973 {
1974     int ret = 0;
1975
1976     if ((fe->firstcb && !fe->ncbs) ||
1977         (!fe->firstcb && fe->ncbs)) {
1978         ViceLog(0, ("cb_stateVerifyFE: error: fe->firstcb does not agree with fe->ncbs (fei=%d, fe->firstcb=%d, fe->ncbs=%d)\n",
1979                     fetoi(fe), fe->firstcb, fe->ncbs));
1980         ret = 1;
1981     }
1982     if (cb_stateVerifyFCBList(state, fe)) {
1983         ViceLog(0, ("cb_stateVerifyFE: error: FCBList failed verification (fei=%d)\n", fetoi(fe)));
1984         ret = 1;
1985     }
1986
1987  done:
1988     return ret;
1989 }
1990
1991 static int
1992 cb_stateVerifyFCBList(struct fs_dump_state * state, struct FileEntry * fe)
1993 {
1994     int ret = 0;
1995     afs_uint32 cbi, fei, chain_len = 0;
1996     struct CallBack * cb;
1997
1998     fei = fetoi(fe);
1999
2000     for (cbi = fe->firstcb, cb = itocb(cbi);
2001          cb;
2002          cbi = cb->cnext, cb = itocb(cbi)) {
2003         if (cbi > cbstuff.nblks) {
2004             ViceLog(0, ("cb_stateVerifyFCBList: error: list index out of range (cbi=%d, ncbs=%d)\n",
2005                         cbi, cbstuff.nblks));
2006             ret = 1;
2007             goto done;
2008         }
2009         if (cb->fhead != fei) {
2010             ViceLog(0, ("cb_stateVerifyFCBList: error: cb->fhead != fei (fei=%d, cb->fhead=%d)\n",
2011                         fei, cb->fhead));
2012             ret = 1;
2013         }
2014         if (chain_len > FS_STATE_FCB_MAX_LIST_LEN) {
2015             ViceLog(0, ("cb_stateVerifyFCBList: error: list length exceeds %d (fei=%d); assuming there's a loop\n",
2016                         FS_STATE_FCB_MAX_LIST_LEN, fei));
2017             ret = 1;
2018             goto done;
2019         }
2020         chain_len++;
2021     }
2022
2023     if (fe->ncbs != chain_len) {
2024         ViceLog(0, ("cb_stateVerifyFCBList: error: list length mismatch (len=%d, fe->ncbs=%d)\n",
2025                     chain_len, fe->ncbs));
2026         ret = 1;
2027     }
2028
2029  done:
2030     return ret;
2031 }
2032
2033 int
2034 cb_stateVerifyHCBList(struct fs_dump_state * state, struct host * host)
2035 {
2036     int ret = 0;
2037     afs_uint32 hi, chain_len, cbi;
2038     struct CallBack *cb, *ncb;
2039
2040     hi = h_htoi(host);
2041     chain_len = 0;
2042
2043     for (cbi = host->cblist, cb = itocb(cbi);
2044          cb;
2045          cbi = cb->hnext, cb = ncb) {
2046         if (chain_len && (host->cblist == cbi)) {
2047             /* we've wrapped around the circular list, and everything looks ok */
2048             break;
2049         }
2050         if (cb->hhead != hi) {
2051             ViceLog(0, ("cb_stateVerifyHCBList: error: incorrect cb->hhead (cbi=%d, h->index=%d, cb->hhead=%d)\n",
2052                         cbi, hi, cb->hhead));
2053             ret = 1;
2054         }
2055         if (!cb->hprev || !cb->hnext) {
2056             ViceLog(0, ("cb_stateVerifyHCBList: error: null index in circular list (cbi=%d, h->index=%d)\n",
2057                         cbi, hi));
2058             ret = 1;
2059             goto done;
2060         }
2061         if ((cb->hprev > cbstuff.nblks) ||
2062             (cb->hnext > cbstuff.nblks)) {
2063             ViceLog(0, ("cb_stateVerifyHCBList: error: list index out of range (cbi=%d, h->index=%d, cb->hprev=%d, cb->hnext=%d, nCBs=%d)\n",
2064                         cbi, hi, cb->hprev, cb->hnext, cbstuff.nblks));
2065             ret = 1;
2066             goto done;
2067         }
2068         ncb = itocb(cb->hnext);
2069         if (cbi != ncb->hprev) {
2070             ViceLog(0, ("cb_stateVerifyHCBList: error: corrupt linked list (cbi=%d, h->index=%d)\n",
2071                         cbi, hi));
2072             ret = 1;
2073             goto done;
2074         }
2075         if (chain_len > FS_STATE_HCB_MAX_LIST_LEN) {
2076             ViceLog(0, ("cb_stateVerifyFCBList: error: list length exceeds %d (h->index=%d); assuming there's a loop\n",
2077                         FS_STATE_HCB_MAX_LIST_LEN, hi));
2078             ret = 1;
2079             goto done;
2080         }
2081         chain_len++;
2082     }
2083
2084  done:
2085     return ret;
2086 }
2087
2088 static int
2089 cb_stateVerifyTimeoutQueues(struct fs_dump_state * state)
2090 {
2091     int ret = 0, i;
2092     afs_uint32 cbi, chain_len;
2093     struct CallBack *cb, *ncb;
2094
2095     for (i = 0; i < CB_NUM_TIMEOUT_QUEUES; i++) {
2096         chain_len = 0;
2097         for (cbi = timeout[i], cb = itocb(cbi);
2098              cb;
2099              cbi = cb->tnext, cb = ncb) {
2100             if (chain_len && (cbi == timeout[i])) {
2101                 /* we've wrapped around the circular list, and everything looks ok */
2102                 break;
2103             }
2104             if (cbi > cbstuff.nblks) {
2105                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: error: list index out of range (cbi=%d, tindex=%d)\n",
2106                             cbi, i));
2107                 ret = 1;
2108                 break;
2109             }
2110             if (itot(cb->thead) != &timeout[i]) {
2111                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: error: cb->thead points to wrong timeout queue (tindex=%d, cbi=%d, cb->thead=%d)\n",
2112                             i, cbi, cb->thead));
2113                 ret = 1;
2114             }
2115             if (!cb->tprev || !cb->tnext) {
2116                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: null index in circular list (cbi=%d, tindex=%d)\n",
2117                             cbi, i));
2118                 ret = 1;
2119                 break;
2120             }
2121             if ((cb->tprev > cbstuff.nblks) ||
2122                 (cb->tnext > cbstuff.nblks)) {
2123                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: list index out of range (cbi=%d, tindex=%d, cb->tprev=%d, cb->tnext=%d, nCBs=%d)\n",
2124                             cbi, i, cb->tprev, cb->tnext, cbstuff.nblks));
2125                 ret = 1;
2126                 break;
2127             }
2128             ncb = itocb(cb->tnext);
2129             if (cbi != ncb->tprev) {
2130                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: corrupt linked list (cbi=%d, tindex=%d)\n",
2131                             cbi, i));
2132                 ret = 1;
2133                 break;
2134             }
2135             if (chain_len > FS_STATE_TCB_MAX_LIST_LEN) {
2136                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: list length exceeds %d (tindex=%d); assuming there's a loop\n",
2137                             FS_STATE_TCB_MAX_LIST_LEN, i));
2138                 ret = 1;
2139                 break;
2140             }
2141             chain_len++;
2142         }
2143     }
2144
2145  done:
2146     return ret;
2147 }
2148
2149 static int
2150 cb_stateSaveTimeouts(struct fs_dump_state * state)
2151 {
2152     int ret = 0;
2153     struct iovec iov[2];
2154
2155     AssignInt64(state->eof_offset, &state->cb_hdr->timeout_offset);
2156
2157     memset(state->cb_timeout_hdr, 0, sizeof(struct callback_state_fehash_header));
2158     state->cb_timeout_hdr->magic = CALLBACK_STATE_TIMEOUT_MAGIC;
2159     state->cb_timeout_hdr->records = CB_NUM_TIMEOUT_QUEUES;
2160     state->cb_timeout_hdr->len = sizeof(struct callback_state_timeout_header) +
2161         (state->cb_timeout_hdr->records * sizeof(afs_uint32));
2162
2163     iov[0].iov_base = (char *)state->cb_timeout_hdr;
2164     iov[0].iov_len = sizeof(struct callback_state_timeout_header);
2165     iov[1].iov_base = (char *)timeout;
2166     iov[1].iov_len = sizeof(timeout);
2167
2168     if (fs_stateSeek(state, &state->cb_hdr->timeout_offset)) {
2169         ret = 1;
2170         goto done;
2171     }
2172
2173     if (fs_stateWriteV(state, iov, 2)) {
2174         ret = 1;
2175         goto done;
2176     }
2177
2178     fs_stateIncEOF(state, state->cb_timeout_hdr->len);
2179
2180  done:
2181     return ret;
2182 }
2183
2184 static int
2185 cb_stateRestoreTimeouts(struct fs_dump_state * state)
2186 {
2187     int ret = 0, len;
2188
2189     if (fs_stateReadHeader(state, &state->cb_hdr->timeout_offset,
2190                            state->cb_timeout_hdr, 
2191                            sizeof(struct callback_state_timeout_header))) {
2192         ret = 1;
2193         goto done;
2194     }
2195
2196     if (state->cb_timeout_hdr->magic != CALLBACK_STATE_TIMEOUT_MAGIC) {
2197         ret = 1;
2198         goto done;
2199     }
2200     if (state->cb_timeout_hdr->records != CB_NUM_TIMEOUT_QUEUES) {
2201         ret = 1;
2202         goto done;
2203     }
2204
2205     len = state->cb_timeout_hdr->records * sizeof(afs_uint32);
2206
2207     if (state->cb_timeout_hdr->len !=
2208         (sizeof(struct callback_state_timeout_header) + len)) {
2209         ret = 1;
2210         goto done;
2211     }
2212
2213     if (fs_stateRead(state, timeout, len)) {
2214         ret = 1;
2215         goto done;
2216     }
2217
2218  done:
2219     return ret;
2220 }
2221
2222 static int
2223 cb_stateSaveFEHash(struct fs_dump_state * state)
2224 {
2225     int ret = 0;
2226     struct iovec iov[2];
2227
2228     AssignInt64(state->eof_offset, &state->cb_hdr->fehash_offset);
2229
2230     memset(state->cb_fehash_hdr, 0, sizeof(struct callback_state_fehash_header));
2231     state->cb_fehash_hdr->magic = CALLBACK_STATE_FEHASH_MAGIC;
2232     state->cb_fehash_hdr->records = FEHASH_SIZE;
2233     state->cb_fehash_hdr->len = sizeof(struct callback_state_fehash_header) +
2234         (state->cb_fehash_hdr->records * sizeof(afs_uint32));
2235
2236     iov[0].iov_base = (char *)state->cb_fehash_hdr;
2237     iov[0].iov_len = sizeof(struct callback_state_fehash_header);
2238     iov[1].iov_base = (char *)HashTable;
2239     iov[1].iov_len = sizeof(HashTable);
2240
2241     if (fs_stateSeek(state, &state->cb_hdr->fehash_offset)) {
2242         ret = 1;
2243         goto done;
2244     }
2245
2246     if (fs_stateWriteV(state, iov, 2)) {
2247         ret = 1;
2248         goto done;
2249     }
2250
2251     fs_stateIncEOF(state, state->cb_fehash_hdr->len);
2252
2253  done:
2254     return ret;
2255 }
2256
2257 static int
2258 cb_stateRestoreFEHash(struct fs_dump_state * state)
2259 {
2260     int ret = 0, len;
2261
2262     if (fs_stateReadHeader(state, &state->cb_hdr->fehash_offset,
2263                            state->cb_fehash_hdr, 
2264                            sizeof(struct callback_state_fehash_header))) {
2265         ret = 1;
2266         goto done;
2267     }
2268
2269     if (state->cb_fehash_hdr->magic != CALLBACK_STATE_FEHASH_MAGIC) {
2270         ret = 1;
2271         goto done;
2272     }
2273     if (state->cb_fehash_hdr->records != FEHASH_SIZE) {
2274         ret = 1;
2275         goto done;
2276     }
2277
2278     len = state->cb_fehash_hdr->records * sizeof(afs_uint32);
2279
2280     if (state->cb_fehash_hdr->len !=
2281         (sizeof(struct callback_state_fehash_header) + len)) {
2282         ret = 1;
2283         goto done;
2284     }
2285
2286     if (fs_stateRead(state, HashTable, len)) {
2287         ret = 1;
2288         goto done;
2289     }
2290
2291  done:
2292     return ret;
2293 }
2294
2295 static int
2296 cb_stateSaveFEs(struct fs_dump_state * state)
2297 {
2298     int ret = 0;
2299     register int fei, hash;
2300     register struct FileEntry *fe;
2301
2302     AssignInt64(state->eof_offset, &state->cb_hdr->fe_offset);
2303
2304     for (hash = 0; hash < FEHASH_SIZE ; hash++) {
2305         for (fei = HashTable[hash]; fei; fei = fe->fnext) {
2306             fe = itofe(fei);
2307             if (cb_stateSaveFE(state, fe)) {
2308                 ret = 1;
2309                 goto done;
2310             }
2311         }
2312     }
2313
2314  done:
2315     return ret;
2316 }
2317
2318 static int
2319 cb_stateRestoreFEs(struct fs_dump_state * state)
2320 {
2321     int count, nFEs, ret = 0;
2322
2323     nFEs = state->cb_hdr->nFEs;
2324
2325     for (count = 0; count < nFEs; count++) {
2326         if (cb_stateRestoreFE(state)) {
2327             ret = 1;
2328             goto done;
2329         }
2330     }
2331
2332  done:
2333     return ret;
2334 }
2335
2336 static int
2337 cb_stateSaveFE(struct fs_dump_state * state, struct FileEntry * fe)
2338 {
2339     int ret = 0, iovcnt, cbi, written = 0;
2340     afs_uint32 fei;
2341     struct callback_state_entry_header hdr;
2342     struct FEDiskEntry fedsk;
2343     struct CBDiskEntry cbdsk[16];
2344     struct iovec iov[16];
2345     struct CallBack *cb;
2346
2347     fei = fetoi(fe);
2348     if (fei > state->cb_hdr->fe_max) {
2349         state->cb_hdr->fe_max = fei;
2350     }
2351
2352     memset(&hdr, 0, sizeof(struct callback_state_entry_header));
2353
2354     if (cb_stateFEToDiskEntry(fe, &fedsk)) {
2355         ret = 1;
2356         goto done;
2357     }
2358
2359     iov[0].iov_base = (char *)&hdr;
2360     iov[0].iov_len = sizeof(hdr);
2361     iov[1].iov_base = (char *)&fedsk;
2362     iov[1].iov_len = sizeof(struct FEDiskEntry);
2363     iovcnt = 2;
2364
2365     for (cbi = fe->firstcb, cb = itocb(cbi); 
2366          cb != NULL; 
2367          cbi = cb->cnext, cb = itocb(cbi), hdr.nCBs++) {
2368         if (cbi > state->cb_hdr->cb_max) {
2369             state->cb_hdr->cb_max = cbi;
2370         }
2371         if (cb_stateCBToDiskEntry(cb, &cbdsk[iovcnt])) {
2372             ret = 1;
2373             goto done;
2374         }
2375         cbdsk[iovcnt].index = cbi;
2376         iov[iovcnt].iov_base = (char *)&cbdsk[iovcnt];
2377         iov[iovcnt].iov_len = sizeof(struct CBDiskEntry);
2378         iovcnt++;
2379         if ((iovcnt == 16) || (!cb->cnext)) {
2380             if (fs_stateWriteV(state, iov, iovcnt)) {
2381                 ret = 1;
2382                 goto done;
2383             }
2384             written = 1;
2385             iovcnt = 0;
2386         }
2387     }
2388
2389     hdr.magic = CALLBACK_STATE_ENTRY_MAGIC;
2390     hdr.len = sizeof(hdr) + sizeof(struct FEDiskEntry) + 
2391         (hdr.nCBs * sizeof(struct CBDiskEntry));
2392
2393     if (!written) {
2394         if (fs_stateWriteV(state, iov, iovcnt)) {
2395             ret = 1;
2396             goto done;
2397         }
2398     } else {
2399         if (fs_stateWriteHeader(state, &state->eof_offset, &hdr, sizeof(hdr))) {
2400             ret = 1;
2401             goto done;
2402         }
2403     }
2404
2405     fs_stateIncEOF(state, hdr.len);
2406
2407     if (written) {
2408         if (fs_stateSeek(state, &state->eof_offset)) {
2409             ret = 1;
2410             goto done;
2411         }
2412     }
2413
2414     state->cb_hdr->nFEs++;
2415     state->cb_hdr->nCBs += hdr.nCBs;
2416
2417  done:
2418     return ret;
2419 }
2420
2421 static int
2422 cb_stateRestoreFE(struct fs_dump_state * state)
2423 {
2424     int ret = 0, iovcnt, nCBs;
2425     struct callback_state_entry_header hdr;
2426     struct FEDiskEntry fedsk;
2427     struct CBDiskEntry cbdsk[16];
2428     struct iovec iov[16];
2429     struct FileEntry * fe;
2430     struct CallBack * cb;
2431
2432     iov[0].iov_base = (char *)&hdr;
2433     iov[0].iov_len = sizeof(hdr);
2434     iov[1].iov_base = (char *)&fedsk;
2435     iov[1].iov_len = sizeof(fedsk);
2436     iovcnt = 2;
2437
2438     if (fs_stateReadV(state, iov, iovcnt)) {
2439         ret = 1;
2440         goto done;
2441     }
2442
2443     if (hdr.magic != CALLBACK_STATE_ENTRY_MAGIC) {
2444         ret = 1;
2445         goto done;
2446     }
2447
2448     fe = GetFE();
2449     if (fe == NULL) {
2450         ViceLog(0, ("cb_stateRestoreFE: ran out of free FileEntry structures\n"));
2451         ret = 1;
2452         goto done;
2453     }
2454
2455     if (cb_stateDiskEntryToFE(state, &fedsk, fe)) {
2456         ret = 1;
2457         goto done;
2458     }
2459
2460     if (hdr.nCBs) {
2461         for (iovcnt = 0, nCBs = 0;
2462              nCBs < hdr.nCBs;
2463              nCBs++) {
2464             iov[iovcnt].iov_base = (char *)&cbdsk[iovcnt];
2465             iov[iovcnt].iov_len = sizeof(struct CBDiskEntry);
2466             iovcnt++;
2467             if ((iovcnt == 16) || (nCBs == hdr.nCBs - 1)) {
2468                 if (fs_stateReadV(state, iov, iovcnt)) {
2469                     ret = 1;
2470                     goto done;
2471                 }
2472                 if (cb_stateRestoreCBs(state, fe, iov, iovcnt)) {
2473                     ret = 1;
2474                     goto done;
2475                 }
2476                 iovcnt = 0;
2477             }
2478         }
2479     }
2480     
2481  done:
2482     return ret;
2483 }
2484
2485 static int
2486 cb_stateRestoreCBs(struct fs_dump_state * state, struct FileEntry * fe, 
2487                    struct iovec * iov, int niovecs)
2488 {
2489     int ret = 0, idx;
2490     register struct CallBack * cb;
2491     struct CBDiskEntry * cbdsk;
2492     afs_uint32 fei;
2493
2494     fei = fetoi(fe);
2495
2496     for (idx = 0; idx < niovecs; idx++) {
2497         cbdsk = (struct CBDiskEntry *) iov[idx].iov_base;
2498         if ((cb = GetCB()) == NULL) {
2499             ViceLog(0, ("cb_stateRestoreCBs: ran out of free CallBack structures\n"));
2500             ret = 1;
2501             goto done;
2502         }
2503         if (cb_stateDiskEntryToCB(state, cbdsk, cb)) {
2504             ViceLog(0, ("cb_stateRestoreCBs: corrupt CallBack disk entry\n"));
2505             ret = 1;
2506             goto done;
2507         }
2508     }
2509
2510  done:
2511     return ret;
2512 }
2513
2514
2515 static int
2516 cb_stateFillHeader(struct callback_state_header * hdr)
2517 {
2518     hdr->stamp.magic = CALLBACK_STATE_MAGIC;
2519     hdr->stamp.version = CALLBACK_STATE_VERSION;
2520     hdr->tfirst = tfirst;
2521     return 0;
2522 }
2523
2524 static int
2525 cb_stateCheckHeader(struct callback_state_header * hdr)
2526 {
2527     int ret = 0;
2528
2529     if (hdr->stamp.magic != CALLBACK_STATE_MAGIC) {
2530         ret = 1;
2531     } else if (hdr->stamp.version != CALLBACK_STATE_VERSION) {
2532         ret = 1;
2533     } else if ((hdr->nFEs > cbstuff.nblks) || (hdr->nCBs > cbstuff.nblks)) {
2534         ViceLog(0, ("cb_stateCheckHeader: saved callback state larger than callback memory allocation\n"));
2535         ret = 1;
2536     }
2537     return ret;
2538 }
2539
2540 /* disk entry conversion routines */
2541 static int
2542 cb_stateFEToDiskEntry(struct FileEntry * in, struct FEDiskEntry * out)
2543 {
2544     memcpy(&out->fe, in, sizeof(struct FileEntry));
2545     out->index = fetoi(in);
2546     return 0;
2547 }
2548
2549 static int
2550 cb_stateDiskEntryToFE(struct fs_dump_state * state, 
2551                       struct FEDiskEntry * in, struct FileEntry * out)
2552 {
2553     int ret = 0;
2554
2555     memcpy(out, &in->fe, sizeof(struct FileEntry));
2556
2557     /* setup FE map entry */
2558     if (!in->index || (in->index >= state->fe_map.len)) {
2559         ViceLog(0, ("cb_stateDiskEntryToFE: index (%d) out of range",
2560                     in->index));
2561         ret = 1;
2562         goto done;
2563     }
2564     state->fe_map.entries[in->index].old_idx = in->index;
2565     state->fe_map.entries[in->index].new_idx = fetoi(out);
2566
2567  done:
2568     return ret;
2569 }
2570
2571 static int
2572 cb_stateCBToDiskEntry(struct CallBack * in, struct CBDiskEntry * out)
2573 {
2574     memcpy(&out->cb, in, sizeof(struct CallBack));
2575     out->index = cbtoi(in);
2576     return 0;
2577 }
2578
2579 static int
2580 cb_stateDiskEntryToCB(struct fs_dump_state * state,
2581                       struct CBDiskEntry * in, struct CallBack * out)
2582 {
2583     int ret = 0;
2584
2585     memcpy(out, &in->cb, sizeof(struct CallBack));
2586
2587     /* setup CB map entry */
2588     if (!in->index || (in->index >= state->cb_map.len)) {
2589         ViceLog(0, ("cb_stateDiskEntryToCB: index (%d) out of range\n",
2590                     in->index));
2591         ret = 1;
2592         goto done;
2593     }
2594     state->cb_map.entries[in->index].old_idx = in->index;
2595     state->cb_map.entries[in->index].new_idx = cbtoi(out);
2596
2597  done:
2598     return ret;
2599 }
2600
2601 /* index map routines */
2602 static int
2603 cb_stateAllocMap(struct fs_dump_state * state)
2604 {
2605     state->fe_map.len = state->cb_hdr->fe_max + 1;
2606     state->cb_map.len = state->cb_hdr->cb_max + 1;
2607     state->fe_map.entries = (struct idx_map_entry_t *)
2608         calloc(state->fe_map.len, sizeof(struct idx_map_entry_t));
2609     state->cb_map.entries = (struct idx_map_entry_t *)
2610         calloc(state->cb_map.len, sizeof(struct idx_map_entry_t));
2611     return ((state->fe_map.entries != NULL) && (state->cb_map.entries != NULL)) ? 0 : 1;
2612 }
2613
2614 int
2615 fe_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
2616 {
2617     int ret = 0;
2618
2619     /* FEs use a one-based indexing system, so old==0 implies no mapping */
2620     if (!old) {
2621         *new = 0;
2622         goto done;
2623     }
2624
2625     if (old >= state->fe_map.len) {
2626         ViceLog(0, ("fe_OldToNew: index %d is out of range\n", old));
2627         ret = 1;
2628     } else if (state->fe_map.entries[old].old_idx != old) { /* sanity check */
2629         ViceLog(0, ("fe_OldToNew: index %d points to an invalid FileEntry record\n", old));
2630         ret = 1;
2631     } else {
2632         *new = state->fe_map.entries[old].new_idx;
2633     }
2634
2635  done:
2636     return ret;
2637 }
2638
2639 int
2640 cb_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
2641 {
2642     int ret = 0;
2643
2644     /* CBs use a one-based indexing system, so old==0 implies no mapping */
2645     if (!old) {
2646         *new = 0;
2647         goto done;
2648     }
2649
2650     if (old >= state->cb_map.len) {
2651         ViceLog(0, ("cb_OldToNew: index %d is out of range\n", old));
2652         ret = 1;
2653     } else if (state->cb_map.entries[old].old_idx != old) { /* sanity check */
2654         ViceLog(0, ("cb_OldToNew: index %d points to an invalid CallBack record\n", old));
2655         ret = 1;
2656     } else {
2657         *new = state->cb_map.entries[old].new_idx;
2658     }
2659
2660  done:
2661     return ret;
2662 }
2663 #endif /* AFS_DEMAND_ATTACH_FS */
2664
2665 int
2666 DumpCallBackState(void)
2667 {
2668     int fd, oflag;
2669     afs_uint32 magic = MAGICV2, now = (afs_int32) FT_ApproxTime(), freelisthead;
2670
2671     oflag = O_WRONLY | O_CREAT | O_TRUNC;
2672 #ifdef AFS_NT40_ENV
2673     oflag |= O_BINARY;
2674 #endif
2675     fd = open(AFSDIR_SERVER_CBKDUMP_FILEPATH, oflag, 0666);
2676     if (fd < 0) {
2677         ViceLog(0,
2678                 ("Couldn't create callback dump file %s\n",
2679                  AFSDIR_SERVER_CBKDUMP_FILEPATH));
2680         return 0;
2681     }
2682     (void)write(fd, &magic, sizeof(magic));
2683     (void)write(fd, &now, sizeof(now));
2684     (void)write(fd, &cbstuff, sizeof(cbstuff));
2685     (void)write(fd, TimeOuts, sizeof(TimeOuts));
2686     (void)write(fd, timeout, sizeof(timeout));
2687     (void)write(fd, &tfirst, sizeof(tfirst));
2688     freelisthead = cbtoi((struct CallBack *)CBfree);
2689     (void)write(fd, &freelisthead, sizeof(freelisthead));       /* This is a pointer */
2690     freelisthead = fetoi((struct FileEntry *)FEfree);
2691     (void)write(fd, &freelisthead, sizeof(freelisthead));       /* This is a pointer */
2692     (void)write(fd, HashTable, sizeof(HashTable));
2693     (void)write(fd, &CB[1], sizeof(CB[1]) * cbstuff.nblks);     /* CB stuff */
2694     (void)write(fd, &FE[1], sizeof(FE[1]) * cbstuff.nblks);     /* FE stuff */
2695     close(fd);
2696
2697     return 0;
2698 }
2699
2700 #endif /* !INTERPRET_DUMP */
2701
2702 #ifdef INTERPRET_DUMP
2703
2704 /* This is only compiled in for the callback analyzer program */
2705 /* Returns the time of the dump */
2706 time_t
2707 ReadDump(char *file, int timebits)
2708 {
2709     int fd, oflag;
2710     afs_uint32 magic, freelisthead;
2711     afs_uint32 now;
2712 #ifdef AFS_64BIT_ENV
2713     afs_int64 now64;
2714 #endif
2715
2716     oflag = O_RDONLY;
2717 #ifdef AFS_NT40_ENV
2718     oflag |= O_BINARY;
2719 #endif
2720     fd = open(file, oflag);
2721     if (fd < 0) {
2722         fprintf(stderr, "Couldn't read dump file %s\n", file);
2723         exit(1);
2724     }
2725     read(fd, &magic, sizeof(magic));
2726     if (magic == MAGICV2) {
2727         timebits = 32;
2728     } else {
2729         if (magic != MAGIC) {
2730             fprintf(stderr,
2731                     "Magic number of %s is invalid.  You might be trying to\n",
2732                     file);
2733             fprintf(stderr,
2734                     "run this program on a machine type with a different byte ordering.\n");
2735             exit(1);
2736         }
2737     }
2738 #ifdef AFS_64BIT_ENV
2739     if (timebits == 64) {
2740         read(fd, &now64, sizeof(afs_int64));
2741         now = (afs_int32) now64;
2742     } else
2743 #endif
2744         read(fd, &now, sizeof(afs_int32));
2745     read(fd, &cbstuff, sizeof(cbstuff));
2746     read(fd, TimeOuts, sizeof(TimeOuts));
2747     read(fd, timeout, sizeof(timeout));
2748     read(fd, &tfirst, sizeof(tfirst));
2749     read(fd, &freelisthead, sizeof(freelisthead));
2750     CB = ((struct CallBack
2751            *)(calloc(cbstuff.nblks, sizeof(struct CallBack)))) - 1;
2752     FE = ((struct FileEntry
2753            *)(calloc(cbstuff.nblks, sizeof(struct FileEntry)))) - 1;
2754     CBfree = (struct CallBack *)itocb(freelisthead);
2755     read(fd, &freelisthead, sizeof(freelisthead));
2756     FEfree = (struct FileEntry *)itofe(freelisthead);
2757     read(fd, HashTable, sizeof(HashTable));
2758     read(fd, &CB[1], sizeof(CB[1]) * cbstuff.nblks);    /* CB stuff */
2759     read(fd, &FE[1], sizeof(FE[1]) * cbstuff.nblks);    /* FE stuff */
2760     if (close(fd)) {
2761         perror("Error reading dumpfile");
2762         exit(1);
2763     }
2764     return now;
2765 }
2766
2767 #ifdef AFS_NT40_ENV
2768 #include "AFS_component_version_number.h"
2769 #else
2770 #include "AFS_component_version_number.c"
2771 #endif
2772
2773 int
2774 main(int argc, char **argv)
2775 {
2776     int err = 0, cbi = 0, stats = 0, noptions = 0, all = 0, vol = 0, raw = 0;
2777     static AFSFid fid;
2778     register struct FileEntry *fe;
2779     register struct CallBack *cb;
2780     afs_int32 now;
2781     int timebits = 32;
2782     
2783     memset(&fid, 0, sizeof(fid));
2784     argc--;
2785     argv++;
2786     while (argc && **argv == '-') {
2787         noptions++;
2788         argc--;
2789         if (!strcmp(*argv, "-host")) {
2790             if (argc < 1) {
2791                 err++;
2792                 break;
2793             }
2794             argc--;
2795             cbi = atoi(*++argv);
2796         } else if (!strcmp(*argv, "-fid")) {
2797             if (argc < 2) {
2798                 err++;
2799                 break;
2800             }
2801             argc -= 3;
2802             fid.Volume = atoi(*++argv);
2803             fid.Vnode = atoi(*++argv);
2804             fid.Unique = atoi(*++argv);
2805         } else if (!strcmp(*argv, "-time")) {
2806             fprintf(stderr, "-time not supported\n");
2807             exit(1);
2808         } else if (!strcmp(*argv, "-stats")) {
2809             stats = 1;
2810         } else if (!strcmp(*argv, "-all")) {
2811             all = 1;
2812         } else if (!strcmp(*argv, "-raw")) {
2813             raw = 1;
2814         } else if (!strcmp(*argv, "-timebits")) {
2815             if (argc < 1) {
2816                 err++;
2817                 break;
2818             }
2819             argc--;
2820             timebits = atoi(*++argv);
2821             if ((timebits != 32)
2822 #ifdef AFS_64BIT_ENV
2823                 && (timebits != 64)
2824 #endif
2825                 ) 
2826                 err++;
2827         } else if (!strcmp(*argv, "-volume")) {
2828             if (argc < 1) {
2829                 err++;
2830                 break;
2831             }
2832             argc--;
2833             vol = atoi(*++argv);
2834         } else
2835             err++;
2836         argv++;
2837     }
2838     if (err || argc != 1) {
2839         fprintf(stderr,
2840                 "Usage: cbd [-host cbid] [-fid volume vnode] [-stats] [-all] [-timebits 32"
2841 #ifdef AFS_64BIT_ENV
2842                 "|64"
2843 #endif
2844                 "] callbackdumpfile\n");
2845         fprintf(stderr,
2846                 "[cbid is shown for each host in the hosts.dump file]\n");
2847         exit(1);
2848     }
2849     now = ReadDump(*argv, timebits);
2850     if (stats || noptions == 0) {
2851         time_t uxtfirst = UXtime(tfirst);
2852         printf("The time of the dump was %u %s", (unsigned int) now, ctime(&now));
2853         printf("The last time cleanup ran was %u %s", (unsigned int) uxtfirst,
2854                ctime(&uxtfirst));
2855         PrintCallBackStats();
2856     }
2857     if (all || vol) {
2858         int hash;
2859         afs_uint32 *feip;
2860         struct CallBack *cb;
2861         struct FileEntry *fe;
2862
2863         for (hash = 0; hash < FEHASH_SIZE; hash++) {
2864             for (feip = &HashTable[hash]; fe = itofe(*feip);) {
2865                 if (!vol || (fe->volid == vol)) {
2866                     register struct CallBack *cbnext;
2867                     for (cb = itocb(fe->firstcb); cb; cb = cbnext) {
2868                         PrintCB(cb, now);
2869                         cbnext = itocb(cb->cnext);
2870                     }
2871                     *feip = fe->fnext;
2872                 } else {
2873                     feip = &fe->fnext;
2874                 }
2875             }
2876         }
2877     }
2878     if (cbi) {
2879         afs_uint32 cfirst = cbi;
2880         do {
2881             cb = itocb(cbi);
2882             PrintCB(cb, now);
2883             cbi = cb->hnext;
2884         } while (cbi != cfirst);
2885     }
2886     if (fid.Volume) {
2887         fe = FindFE(&fid);
2888         if (!fe) {
2889             printf("No callback entries for %u.%u\n", fid.Volume, fid.Vnode);
2890             exit(1);
2891         }
2892         cb = itocb(fe->firstcb);
2893         while (cb) {
2894             PrintCB(cb, now);
2895             cb = itocb(cb->cnext);
2896         }
2897     }
2898     if (raw) {
2899         afs_int32 *p, i;
2900         for (i = 1; i < cbstuff.nblks; i++) {
2901             p = (afs_int32 *) & FE[i];
2902             printf("%d:%12x%12x%12x%12x\n", i, p[0], p[1], p[2], p[3]);
2903         }
2904     }
2905     exit(0);
2906 }
2907
2908 void
2909 PrintCB(register struct CallBack *cb, afs_uint32 now)
2910 {
2911     struct FileEntry *fe = itofe(cb->fhead);
2912     time_t expires = TIndexToTime(cb->thead);
2913
2914     if (fe == NULL)
2915         return;
2916
2917     printf("vol=%u vn=%u cbs=%d hi=%d st=%d fest=%d, exp in %lu secs at %s",
2918            fe->volid, fe->vnode, fe->ncbs, cb->hhead, cb->status, fe->status,
2919            expires - now, ctime(&expires));
2920 }
2921
2922 #endif
2923
2924 #if     !defined(INTERPRET_DUMP)
2925 /*
2926 ** try breaking calbacks on afidp from host. Use multi_rx.
2927 ** return 0 on success, non-zero on failure
2928 */
2929 int
2930 MultiBreakCallBackAlternateAddress(struct host *host, struct AFSCBFids *afidp)
2931 {
2932     int retVal;
2933     H_LOCK;
2934     retVal = MultiBreakCallBackAlternateAddress_r(host, afidp);
2935     H_UNLOCK;
2936     return retVal;
2937 }
2938
2939 int
2940 MultiBreakCallBackAlternateAddress_r(struct host *host,
2941                                      struct AFSCBFids *afidp)
2942 {
2943     int i, j;
2944     struct rx_connection **conns;
2945     struct rx_connection *connSuccess = 0;
2946     struct AddrPort *interfaces;
2947     static struct rx_securityClass *sc = 0;
2948     static struct AFSCBs tc = { 0, 0 };
2949     char hoststr[16];
2950
2951     /* nothing more can be done */
2952     if (!host->interface)
2953         return 1;               /* failure */
2954
2955     /* the only address is the primary interface */
2956     if (host->interface->numberOfInterfaces <= 1)
2957         return 1;               /* failure */
2958
2959     /* initialise a security object only once */
2960     if (!sc)
2961         sc = rxnull_NewClientSecurityObject();
2962
2963     i = host->interface->numberOfInterfaces;
2964     interfaces = calloc(i, sizeof(struct AddrPort));
2965     conns = calloc(i, sizeof(struct rx_connection *));
2966     if (!interfaces || !conns) {
2967         ViceLog(0,
2968                 ("Failed malloc in MultiBreakCallBackAlternateAddress_r\n"));
2969         assert(0);
2970     }
2971
2972     /* initialize alternate rx connections */
2973     for (i = 0, j = 0; i < host->interface->numberOfInterfaces; i++) {
2974         /* this is the current primary address */
2975         if (host->host == host->interface->interface[i].addr &&
2976             host->port == host->interface->interface[i].port)
2977             continue;
2978
2979         interfaces[j] = host->interface->interface[i];
2980         conns[j] =
2981             rx_NewConnection(interfaces[j].addr, 
2982                              interfaces[j].port, 1, sc, 0);
2983         rx_SetConnDeadTime(conns[j], 2);
2984         rx_SetConnHardDeadTime(conns[j], AFS_HARDDEADTIME);
2985         j++;
2986     }
2987
2988     assert(j);                  /* at least one alternate address */
2989     ViceLog(125,
2990             ("Starting multibreakcall back on all addr for host %x (%s:%d)\n",
2991              host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
2992     H_UNLOCK;
2993     multi_Rx(conns, j) {
2994         multi_RXAFSCB_CallBack(afidp, &tc);
2995         if (!multi_error) {
2996             /* first success */
2997             H_LOCK;
2998             if (host->callback_rxcon)
2999                 rx_DestroyConnection(host->callback_rxcon);
3000             host->callback_rxcon = conns[multi_i];
3001             h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
3002             host->host = interfaces[multi_i].addr;
3003             host->port = interfaces[multi_i].port;
3004             h_AddHostToAddrHashTable_r(host->host, host->port, host);
3005             connSuccess = conns[multi_i];
3006             rx_SetConnDeadTime(host->callback_rxcon, 50);
3007             rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
3008             ViceLog(125,
3009                     ("multibreakcall success with addr %s:%d\n",
3010                      afs_inet_ntoa_r(interfaces[multi_i].addr, hoststr),
3011                      ntohs(interfaces[multi_i].port)));
3012             H_UNLOCK;
3013             multi_Abort;
3014         }
3015     }
3016     multi_End_Ignore;
3017     H_LOCK;
3018     /* Destroy all connections except the one on which we succeeded */
3019     for (i = 0; i < j; i++)
3020         if (conns[i] != connSuccess)
3021             rx_DestroyConnection(conns[i]);
3022
3023     free(interfaces);
3024     free(conns);
3025
3026     if (connSuccess)
3027         return 0;               /* success */
3028     else
3029         return 1;               /* failure */
3030 }
3031
3032
3033 /*
3034 ** try multi_RX probes to host. 
3035 ** return 0 on success, non-0 on failure
3036 */
3037 int
3038 MultiProbeAlternateAddress_r(struct host *host)
3039 {
3040     int i, j;
3041     struct rx_connection **conns;
3042     struct rx_connection *connSuccess = 0;
3043     struct AddrPort *interfaces;
3044     static struct rx_securityClass *sc = 0;
3045     char hoststr[16];
3046
3047     /* nothing more can be done */
3048     if (!host->interface)
3049         return 1;               /* failure */
3050
3051     /* the only address is the primary interface */
3052     if (host->interface->numberOfInterfaces <= 1)
3053         return 1;               /* failure */
3054
3055     /* initialise a security object only once */
3056     if (!sc)
3057         sc = rxnull_NewClientSecurityObject();
3058
3059     i = host->interface->numberOfInterfaces;
3060     interfaces = calloc(i, sizeof(struct AddrPort));
3061     conns = calloc(i, sizeof(struct rx_connection *));
3062     if (!interfaces || !conns) {
3063         ViceLog(0, ("Failed malloc in MultiProbeAlternateAddress_r\n"));
3064         assert(0);
3065     }
3066
3067     /* initialize alternate rx connections */
3068     for (i = 0, j = 0; i < host->interface->numberOfInterfaces; i++) {
3069         /* this is the current primary address */
3070         if (host->host == host->interface->interface[i].addr &&
3071             host->port == host->interface->interface[i].port)
3072             continue;
3073
3074         interfaces[j] = host->interface->interface[i];
3075         conns[j] =
3076             rx_NewConnection(interfaces[j].addr, 
3077                              interfaces[j].port, 1, sc, 0);
3078         rx_SetConnDeadTime(conns[j], 2);
3079         rx_SetConnHardDeadTime(conns[j], AFS_HARDDEADTIME);
3080         j++;
3081     }
3082
3083     assert(j);                  /* at least one alternate address */
3084     ViceLog(125,
3085             ("Starting multiprobe on all addr for host %x (%s:%d)\n",
3086              host, afs_inet_ntoa_r(host->host, hoststr),
3087              ntohs(host->port)));
3088     H_UNLOCK;
3089     multi_Rx(conns, j) {
3090         multi_RXAFSCB_ProbeUuid(&host->interface->uuid);
3091         if (!multi_error) {
3092             /* first success */
3093             H_LOCK;
3094             if (host->callback_rxcon)
3095                 rx_DestroyConnection(host->callback_rxcon);
3096             host->callback_rxcon = conns[multi_i];
3097             h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
3098             host->host = interfaces[multi_i].addr;
3099             host->port = interfaces[multi_i].port;
3100             h_AddHostToAddrHashTable_r(host->host, host->port, host);
3101             connSuccess = conns[multi_i];
3102             rx_SetConnDeadTime(host->callback_rxcon, 50);
3103             rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
3104             ViceLog(125,
3105                     ("multiprobe success with addr %s:%d\n",
3106                      afs_inet_ntoa_r(interfaces[multi_i].addr, hoststr),
3107                      ntohs(interfaces[multi_i].port)));
3108             H_UNLOCK;
3109             multi_Abort;
3110         } else {
3111             ViceLog(125,
3112                     ("multiprobe failure with addr %s:%d\n",
3113                      afs_inet_ntoa_r(interfaces[multi_i].addr, hoststr),
3114                      ntohs(interfaces[multi_i].port)));
3115             
3116             /* This is less than desirable but its the best we can do.
3117              * The AFS Cache Manager will return either 0 for a Uuid  
3118              * match and a 1 for a non-match.   If the error is 1 we 
3119              * therefore know that our mapping of IP address to Uuid 
3120              * is wrong.   We should attempt to find the correct
3121              * Uuid and fix the host tables.
3122              */
3123             if (multi_error == 1) {
3124                 /* remove the current alternate address from this host */
3125                 H_LOCK;
3126                 removeInterfaceAddr_r(host, interfaces[multi_i].addr, interfaces[multi_i].port);
3127                 H_UNLOCK;
3128             }
3129         }
3130 #ifdef AFS_DEMAND_ATTACH_FS
3131         /* try to bail ASAP if the fileserver is shutting down */
3132         FS_STATE_RDLOCK;
3133         if (fs_state.mode == FS_MODE_SHUTDOWN) {
3134             FS_STATE_UNLOCK;
3135             multi_Abort;
3136         }
3137         FS_STATE_UNLOCK;
3138 #endif
3139     }
3140     multi_End_Ignore;
3141     H_LOCK;
3142     /* Destroy all connections except the one on which we succeeded */
3143     for (i = 0; i < j; i++)
3144         if (conns[i] != connSuccess)
3145             rx_DestroyConnection(conns[i]);
3146
3147     free(interfaces);
3148     free(conns);
3149
3150     if (connSuccess)
3151         return 0;               /* success */
3152     else
3153         return 1;               /* failure */
3154 }
3155
3156 #endif /* !defined(INTERPRET_DUMP) */