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