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