117a48e41ebe9cee4f39d2537ad5e73eae50bb5d
[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=%p, cba=%p, 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, "
744                                      "Host %p (%s:%d) is down\n",
745                                      afidp->AFSCBFids_val->Volume,
746                                      afidp->AFSCBFids_val->Vnode,
747                                      afidp->AFSCBFids_val->Unique,
748                                      hp,
749                                      afs_inet_ntoa_r(hp->host, hoststr),
750                                      ntohs(hp->port)));
751                         }
752
753                         H_LOCK;
754                         h_Lock_r(hp); 
755                         if (!(hp->hostFlags & HOSTDELETED)) {
756                             hp->hostFlags |= VENUSDOWN;
757                             /**
758                              * We always go into AddCallBack1_r with the host locked
759                              */
760                             AddCallBack1_r(hp, afidp->AFSCBFids_val, itot(idx),
761                                            CB_DELAYED, 1);
762                         }
763                         h_Unlock_r(hp); 
764                         H_UNLOCK;
765                     }
766                 }
767             }
768         }
769         multi_End;
770         H_LOCK;
771         cbstuff.nbreakers--;
772     }
773
774     for (i = 0; i < ncbas; i++) {
775         struct host *hp;
776         hp = cba[i].hp;
777         if (hp && xhost != hp) {
778             h_Release_r(hp);
779         }
780     }
781
782     /* H_UNLOCK around this so h_FreeConnection does not deadlock.
783        h_FreeConnection should *never* be called on a callback connection,
784        but on 10/27/04 a deadlock occurred where it was, when we know why,
785        this should be reverted. -- shadow */
786     H_UNLOCK;
787     for (i = 0; i < j; i++) {
788         rx_PutConnection(conns[i]);
789     }
790     H_LOCK;
791
792     return;
793 }
794
795 /*
796  * Break all call backs for fid, except for the specified host (unless flag
797  * is true, in which case all get a callback message. Assumption: the specified
798  * host is h_Held, by the caller; the others aren't.
799  * Specified host may be bogus, that's ok.  This used to check to see if the 
800  * host was down in two places, once right after the host was h_held, and 
801  * again after it was locked.  That race condition is incredibly rare and
802  * relatively harmless even when it does occur, so we don't check for it now. 
803  */
804 /* if flag is true, send a break callback msg to "host", too */
805 int
806 BreakCallBack(struct host *xhost, AFSFid * fid, int flag)
807 {
808     struct FileEntry *fe;
809     struct CallBack *cb, *nextcb;
810     struct cbstruct cba[MAX_CB_HOSTS];
811     int ncbas;
812     struct AFSCBFids tf;
813     int hostindex;
814     char hoststr[16];
815
816     ViceLog(7,
817             ("BCB: BreakCallBack(Host %p all but %s:%d, (%u,%u,%u))\n",
818              xhost, afs_inet_ntoa_r(xhost->host, hoststr), ntohs(xhost->port),
819              fid->Volume, fid->Vnode, fid->Unique));
820
821     H_LOCK;
822     cbstuff.BreakCallBacks++;
823     fe = FindFE(fid);
824     if (!fe) {
825         goto done;
826     }
827     hostindex = h_htoi(xhost);
828     cb = itocb(fe->firstcb);
829     if (!cb || ((fe->ncbs == 1) && (cb->hhead == hostindex) && !flag)) {
830         /* the most common case is what follows the || */
831         goto done;
832     }
833     tf.AFSCBFids_len = 1;
834     tf.AFSCBFids_val = fid;
835
836     for (; cb;) {
837         for (ncbas = 0; cb && ncbas < MAX_CB_HOSTS; cb = nextcb) {
838             nextcb = itocb(cb->cnext);
839             if ((cb->hhead != hostindex || flag)
840                 && (cb->status == CB_BULK || cb->status == CB_NORMAL
841                     || cb->status == CB_VOLUME)) {
842                 struct host *thishost = h_itoh(cb->hhead);
843                 if (!thishost) {
844                     ViceLog(0, ("BCB: BOGUS! cb->hhead is NULL!\n"));
845                 } else if (thishost->hostFlags & VENUSDOWN) {
846                     ViceLog(7,
847                             ("BCB: %p (%s:%d) is down; delaying break call back\n",
848                              thishost, afs_inet_ntoa_r(thishost->host, hoststr),
849                              ntohs(thishost->port)));
850                     cb->status = CB_DELAYED;
851                 } else {
852                     if (!(thishost->hostFlags & HOSTDELETED)) {
853                         h_Hold_r(thishost);
854                         cba[ncbas].hp = thishost;
855                         cba[ncbas].thead = cb->thead;
856                         ncbas++;
857                     }
858                     TDel(cb);
859                     HDel(cb);
860                     CDel(cb, 1);        /* Usually first; so this delete 
861                                          * is reasonably inexpensive */
862                 }
863             }
864         }
865
866         if (ncbas) {
867             MultiBreakCallBack_r(cba, ncbas, &tf, xhost);
868
869             /* we need to to all these initializations again because MultiBreakCallBack may block */
870             fe = FindFE(fid);
871             if (!fe) {
872                 goto done;
873             }
874             cb = itocb(fe->firstcb);
875             if (!cb || ((fe->ncbs == 1) && (cb->hhead == hostindex) && !flag)) {
876                 /* the most common case is what follows the || */
877                 goto done;
878             }
879         }
880     }
881
882   done:
883     H_UNLOCK;
884     return 0;
885 }
886
887 /* Delete (do not break) single call back for fid */
888 int
889 DeleteCallBack(struct host *host, AFSFid * fid)
890 {
891     register struct FileEntry *fe;
892     register afs_uint32 *pcb;
893     char hoststr[16];
894
895     H_LOCK;
896     cbstuff.DeleteCallBacks++;
897
898     h_Lock_r(host);
899     /* do not care if the host has been HOSTDELETED */
900     fe = FindFE(fid);
901     if (!fe) {
902         h_Unlock_r(host);
903         H_UNLOCK;
904         ViceLog(8,
905                 ("DCB: No call backs for fid (%u, %u, %u)\n", fid->Volume,
906                  fid->Vnode, fid->Unique));
907         return 0;
908     }
909     pcb = FindCBPtr(fe, host);
910     if (!*pcb) {
911         ViceLog(8,
912                 ("DCB: No call back for host %p (%s:%d), (%u, %u, %u)\n",
913                  host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port),
914                  fid->Volume, fid->Vnode, fid->Unique));
915         h_Unlock_r(host);
916         H_UNLOCK;
917         return 0;
918     }
919     HDel(itocb(*pcb));
920     TDel(itocb(*pcb));
921     CDelPtr(fe, pcb, 1);
922     h_Unlock_r(host);
923     H_UNLOCK;
924     return 0;
925 }
926
927 /*
928  * Delete (do not break) all call backs for fid.  This call doesn't
929  * set all of the various host locks, but it shouldn't really matter
930  * since we're not adding callbacks, but deleting them.  I'm not sure
931  * why it doesn't set the lock, however; perhaps it should.
932  */
933 int
934 DeleteFileCallBacks(AFSFid * fid)
935 {
936     register struct FileEntry *fe;
937     register struct CallBack *cb;
938     register afs_uint32 cbi;
939     register int n;
940
941     H_LOCK;
942     cbstuff.DeleteFiles++;
943     fe = FindFE(fid);
944     if (!fe) {
945         H_UNLOCK;
946         ViceLog(8,
947                 ("DF: No fid (%u,%u,%u) to delete\n", fid->Volume, fid->Vnode,
948                  fid->Unique));
949         return 0;
950     }
951     for (n = 0, cbi = fe->firstcb; cbi; n++) {
952         cb = itocb(cbi);
953         cbi = cb->cnext;
954         TDel(cb);
955         HDel(cb);
956         FreeCB(cb);
957         fe->ncbs--;
958     }
959     FDel(fe);
960     H_UNLOCK;
961     return 0;
962 }
963
964 /* Delete (do not break) all call backs for host.  The host should be
965  * locked. */
966 int
967 DeleteAllCallBacks_r(struct host *host, int deletefe)
968 {
969     register struct CallBack *cb;
970     register int cbi, first;
971
972     cbstuff.DeleteAllCallBacks++;
973     cbi = first = host->cblist;
974     if (!cbi) {
975         ViceLog(8, ("DV: no call backs\n"));
976         return 0;
977     }
978     do {
979         cb = itocb(cbi);
980         cbi = cb->hnext;
981         TDel(cb);
982         CDel(cb, deletefe);
983     } while (cbi != first);
984     host->cblist = 0;
985     return 0;
986 }
987
988 /*
989  * Break all delayed call backs for host.  Returns 1 if all call backs
990  * successfully broken; 0 otherwise.  Assumes host is h_Held and h_Locked.
991  * Must be called with VenusDown set for this host
992  */
993 int
994 BreakDelayedCallBacks(struct host *host)
995 {
996     int retVal;
997     H_LOCK;
998     retVal = BreakDelayedCallBacks_r(host);
999     H_UNLOCK;
1000     return retVal;
1001 }
1002
1003 int
1004 BreakDelayedCallBacks_r(struct host *host)
1005 {
1006     struct AFSFid fids[AFSCBMAX];
1007     u_byte thead[AFSCBMAX];     /* This should match thead in struct Callback */
1008     int cbi, first, nfids;
1009     struct CallBack *cb;
1010     int code;
1011     char hoststr[16];
1012     struct rx_connection *cb_conn;
1013
1014     cbstuff.nbreakers++;
1015     if (!(host->hostFlags & RESETDONE) && !(host->hostFlags & HOSTDELETED)) {
1016         host->hostFlags &= ~ALTADDR;    /* alternate addresses are invalid */
1017         cb_conn = host->callback_rxcon;
1018         rx_GetConnection(cb_conn);
1019         if (host->interface) {
1020             H_UNLOCK;
1021             code =
1022                 RXAFSCB_InitCallBackState3(cb_conn, &FS_HostUUID);
1023         } else {
1024             H_UNLOCK;
1025             code = RXAFSCB_InitCallBackState(cb_conn);
1026         }
1027         rx_PutConnection(cb_conn);
1028         cb_conn = NULL;
1029         H_LOCK;
1030         host->hostFlags |= ALTADDR;     /* alternate addresses are valid */
1031         if (code) {
1032             if (ShowProblems) {
1033                 ViceLog(0,
1034                         ("CB: Call back connect back failed (in break delayed) "
1035                          "for Host %p (%s:%d)\n",
1036                          host, afs_inet_ntoa_r(host->host, hoststr),
1037                          ntohs(host->port)));
1038             }
1039             host->hostFlags |= VENUSDOWN;
1040         } else {
1041             ViceLog(25,
1042                     ("InitCallBackState success on %p (%s:%d)\n",
1043                      host, afs_inet_ntoa_r(host->host, hoststr),
1044                      ntohs(host->port)));
1045             /* reset was done successfully */
1046             host->hostFlags |= RESETDONE;
1047             host->hostFlags &= ~VENUSDOWN;
1048         }
1049     } else
1050         while (!(host->hostFlags & HOSTDELETED)) {
1051             nfids = 0;
1052             host->hostFlags &= ~VENUSDOWN;      /* presume up */
1053             cbi = first = host->cblist;
1054             if (!cbi)
1055                 break;
1056             do {
1057                 first = host->cblist;
1058                 cb = itocb(cbi);
1059                 cbi = cb->hnext;
1060                 if (cb->status == CB_DELAYED) {
1061                     register struct FileEntry *fe = itofe(cb->fhead);
1062                     thead[nfids] = cb->thead;
1063                     fids[nfids].Volume = fe->volid;
1064                     fids[nfids].Vnode = fe->vnode;
1065                     fids[nfids].Unique = fe->unique;
1066                     nfids++;
1067                     HDel(cb);
1068                     TDel(cb);
1069                     CDel(cb, 1);
1070                 }
1071             } while (cbi && cbi != first && nfids < AFSCBMAX);
1072
1073             if (nfids == 0) {
1074                 break;
1075             }
1076
1077             if (XCallBackBulk_r(host, fids, nfids)) {
1078                 /* Failed, again:  put them back, probably with old
1079                  * timeout values */
1080                 int i;
1081                 if (ShowProblems) {
1082                     ViceLog(0,
1083                             ("CB: XCallBackBulk failed, Host %p (%s:%d); "
1084                              "callback list follows:\n",
1085                              host, afs_inet_ntoa_r(host->host, hoststr),
1086                              ntohs(host->port)));
1087                 }
1088                 for (i = 0; i < nfids; i++) {
1089                     if (ShowProblems) {
1090                         ViceLog(0,
1091                                 ("CB: Host %p (%s:%d), file %u.%u.%u "
1092                                  "(part of bulk callback)\n",
1093                                  host, afs_inet_ntoa_r(host->host, hoststr),
1094                                  ntohs(host->port), fids[i].Volume,
1095                                  fids[i].Vnode, fids[i].Unique));
1096                     }
1097                     /* used to do this:
1098                      * AddCallBack1_r(host, &fids[i], itot(thead[i]), CB_DELAYED, 1);
1099                      * * but it turns out to cause too many tricky locking problems.
1100                      * * now, if break delayed fails, screw it. */
1101                 }
1102                 host->hostFlags |= VENUSDOWN;   /* Failed */
1103                 ClearHostCallbacks_r(host, 1 /* locked */ );
1104                 nfids = 0;
1105                 break;
1106             }
1107             if (nfids < AFSCBMAX)
1108                 break;
1109         }
1110
1111     cbstuff.nbreakers--;
1112     /* If we succeeded it's always ok to unset HFE_LATER */
1113     if (!(host->hostFlags & VENUSDOWN))
1114         host->hostFlags &= ~HFE_LATER;
1115     return (host->hostFlags & VENUSDOWN);
1116 }
1117
1118 /*
1119 ** isheld is 0 if the host is held in h_Enumerate
1120 ** isheld is 1 if the host is held in BreakVolumeCallBacks
1121 */
1122 static int
1123 MultiBreakVolumeCallBack_r(struct host *host, int isheld,
1124                            struct VCBParams *parms, int deletefe)
1125 {
1126     char hoststr[16];
1127
1128     if (!isheld)
1129         return isheld;          /* host is held only by h_Enumerate, do nothing */
1130     if (host->hostFlags & HOSTDELETED)
1131         return 0;               /* host is deleted, release hold */
1132
1133     if (host->hostFlags & VENUSDOWN) {
1134         h_Lock_r(host);
1135         /* Do not care if the host is now HOSTDELETED */
1136         if (ShowProblems) {
1137             ViceLog(0,
1138                     ("BVCB: volume callback for Host %p (%s:%d) failed\n",
1139                      host, afs_inet_ntoa_r(host->host, hoststr),
1140                      ntohs(host->port)));
1141         }
1142         DeleteAllCallBacks_r(host, deletefe);   /* Delete all callback state 
1143                                                  * rather than attempting to 
1144                                                  * selectively remember to
1145                                                  * delete the volume callbacks
1146                                                  * later */
1147         host->hostFlags &= ~RESETDONE;  /* Do InitCallBackState when host returns */
1148         h_Unlock_r(host);
1149         return 0;               /* release hold */
1150     }
1151     assert(parms->ncbas <= MAX_CB_HOSTS);
1152
1153     /* Do not call MultiBreakCallBack on the current host structure
1154      ** because it would prematurely release the hold on the host
1155      */
1156     if (parms->ncbas == MAX_CB_HOSTS) {
1157         struct AFSCBFids tf;
1158
1159         tf.AFSCBFids_len = 1;
1160         tf.AFSCBFids_val = parms->fid;
1161
1162         /* this releases all the hosts */
1163         MultiBreakCallBack_r(parms->cba, parms->ncbas, &tf, 0 /* xhost */ );
1164
1165         parms->ncbas = 0;
1166     }
1167     parms->cba[parms->ncbas].hp = host;
1168     parms->cba[(parms->ncbas)++].thead = parms->thead;
1169     return 1;                   /* DON'T release hold, because we still need it. */
1170 }
1171
1172 /*
1173 ** isheld is 0 if the host is held in h_Enumerate
1174 ** isheld is 1 if the host is held in BreakVolumeCallBacks
1175 */
1176 static int
1177 MultiBreakVolumeCallBack(struct host *host, int isheld, void *rock)
1178 {
1179     struct VCBParams *parms = (struct VCBParams *) rock;
1180     
1181     int retval;
1182     H_LOCK;
1183     retval = MultiBreakVolumeCallBack_r(host, isheld, parms, 1);
1184     H_UNLOCK;
1185     return retval;
1186 }
1187
1188 /*
1189 ** isheld is 0 if the host is held in h_Enumerate
1190 ** isheld is 1 if the host is held in BreakVolumeCallBacks
1191 */
1192 static int
1193 MultiBreakVolumeLaterCallBack(struct host *host, int isheld, void *rock)
1194 {
1195     struct VCBParams *parms = (struct VCBParams *)rock;
1196     int retval;
1197     H_LOCK;
1198     retval = MultiBreakVolumeCallBack_r(host, isheld, parms, 0);
1199     H_UNLOCK;
1200     return retval;
1201 }
1202
1203 /*
1204  * Break all call backs on a single volume.  Don't call this with any
1205  * hosts h_held.  Note that this routine clears the callbacks before
1206  * actually breaking them, and that the vnode isn't locked during this
1207  * operation, so that people might see temporary callback loss while
1208  * this function is executing.  It is just a temporary state, however,
1209  * since the callback will be broken later by this same function.
1210  *
1211  * Now uses multi-RX for CallBack RPC.  Note that the
1212  * multiBreakCallBacks routine does not force a reset if the RPC
1213  * fails, unlike the previous version of this routine, but does create
1214  * a delayed callback.  Resets will be forced if the host is
1215  * determined to be down before the RPC is executed.
1216  */
1217 int
1218 BreakVolumeCallBacks(afs_uint32 volume)
1219 {
1220     struct AFSFid fid;
1221     int hash;
1222     afs_uint32 *feip;
1223     struct CallBack *cb;
1224     struct FileEntry *fe;
1225     struct host *host;
1226     struct VCBParams henumParms;
1227     afs_uint32 tthead = 0;      /* zero is illegal value */
1228
1229     H_LOCK;
1230     fid.Volume = volume, fid.Vnode = fid.Unique = 0;
1231     for (hash = 0; hash < FEHASH_SIZE; hash++) {
1232         for (feip = &HashTable[hash]; (fe = itofe(*feip));) {
1233             if (fe->volid == volume) {
1234                 register struct CallBack *cbnext;
1235                 for (cb = itocb(fe->firstcb); cb; cb = cbnext) {
1236                     host = h_itoh(cb->hhead);
1237
1238                     if (!(host->hostFlags & HOSTDELETED)) {
1239                         h_Hold_r(host);
1240                         if (!tthead || (TNorm(tthead) < TNorm(cb->thead))) {
1241                             tthead = cb->thead;
1242                         }
1243                     }
1244                     cbnext = itocb(cb->cnext);
1245                     TDel(cb);
1246                     HDel(cb);
1247                     FreeCB(cb);
1248                     /* leave hold for MultiBreakVolumeCallBack to clear */
1249                 }
1250                 *feip = fe->fnext;
1251                 FreeFE(fe);
1252             } else {
1253                 feip = &fe->fnext;
1254             }
1255         }
1256     }
1257
1258     if (!tthead) {
1259         /* didn't find any callbacks, so return right away. */
1260         H_UNLOCK;
1261         return 0;
1262     }
1263     henumParms.ncbas = 0;
1264     henumParms.fid = &fid;
1265     henumParms.thead = tthead;
1266     H_UNLOCK;
1267     h_Enumerate(MultiBreakVolumeCallBack, &henumParms);
1268     H_LOCK;
1269     if (henumParms.ncbas) {     /* do left-overs */
1270         struct AFSCBFids tf;
1271         tf.AFSCBFids_len = 1;
1272         tf.AFSCBFids_val = &fid;
1273
1274         MultiBreakCallBack_r(henumParms.cba, henumParms.ncbas, &tf, 0);
1275
1276         henumParms.ncbas = 0;
1277     }
1278     H_UNLOCK;
1279     return 0;
1280 }
1281
1282 #ifdef AFS_PTHREAD_ENV
1283 extern pthread_cond_t fsync_cond;
1284 #else
1285 extern char fsync_wait[];
1286 #endif
1287
1288 int
1289 BreakVolumeCallBacksLater(afs_uint32 volume)
1290 {
1291     int hash;
1292     afs_uint32 *feip;
1293     struct FileEntry *fe;
1294     struct CallBack *cb;
1295     struct host *host;
1296     int found = 0;
1297
1298     ViceLog(25, ("Setting later on volume %u\n", volume));
1299     H_LOCK;
1300     for (hash = 0; hash < FEHASH_SIZE; hash++) {
1301         for (feip = &HashTable[hash]; (fe = itofe(*feip)) != NULL; ) {
1302             if (fe->volid == volume) {
1303                 register struct CallBack *cbnext;
1304                 for (cb = itocb(fe->firstcb); cb; cb = cbnext) {
1305                     host = h_itoh(cb->hhead);
1306                     host->hostFlags |= HFE_LATER;
1307                     cb->status = CB_DELAYED;
1308                     cbnext = itocb(cb->cnext);
1309                 }
1310                 FSYNC_LOCK;
1311                 fe->status |= FE_LATER;
1312                 FSYNC_UNLOCK;
1313                 found = 1;
1314             }
1315             feip = &fe->fnext;
1316         }
1317     }
1318     H_UNLOCK;
1319     if (!found) {
1320         /* didn't find any callbacks, so return right away. */
1321         return 0;
1322     }
1323
1324     ViceLog(25, ("Fsync thread wakeup\n"));
1325 #ifdef AFS_PTHREAD_ENV
1326     FSYNC_LOCK;
1327     assert(pthread_cond_broadcast(&fsync_cond) == 0);
1328     FSYNC_UNLOCK;
1329 #else
1330     LWP_NoYieldSignal(fsync_wait);
1331 #endif
1332     return 0;
1333 }
1334
1335 int
1336 BreakLaterCallBacks(void)
1337 {
1338     struct AFSFid fid;
1339     int hash;
1340     afs_uint32 *feip;
1341     struct CallBack *cb;
1342     struct FileEntry *fe = NULL;
1343     struct FileEntry *myfe = NULL;
1344     struct host *host;
1345     struct VCBParams henumParms;
1346     unsigned short tthead = 0;  /* zero is illegal value */
1347     char hoststr[16];
1348
1349     /* Unchain first */
1350     ViceLog(25, ("Looking for FileEntries to unchain\n"));
1351     H_LOCK;
1352     FSYNC_LOCK;
1353     /* Pick the first volume we see to clean up */
1354     fid.Volume = fid.Vnode = fid.Unique = 0;
1355
1356     for (hash = 0; hash < FEHASH_SIZE; hash++) {
1357         for (feip = &HashTable[hash]; (fe = itofe(*feip)) != NULL; ) {
1358             if (fe && (fe->status & FE_LATER)
1359                 && (fid.Volume == 0 || fid.Volume == fe->volid)) {
1360                 /* Ugly, but used to avoid left side casting */
1361                 struct object *tmpfe;
1362                 ViceLog(125,
1363                         ("Unchaining for %u:%u:%u\n", fe->vnode, fe->unique,
1364                          fe->volid));
1365                 fid.Volume = fe->volid;
1366                 *feip = fe->fnext;
1367                 fe->status &= ~FE_LATER; /* not strictly needed */
1368                 /* Works since volid is deeper than the largest pointer */
1369                 tmpfe = (struct object *)fe;
1370                 tmpfe->next = (struct object *)myfe;
1371                 myfe = fe;
1372             } else
1373                 feip = &fe->fnext;
1374         }
1375     }
1376     FSYNC_UNLOCK;
1377
1378     if (!myfe) {
1379         H_UNLOCK;
1380         return 0;
1381     }
1382
1383     /* loop over FEs from myfe and free/break */
1384     tthead = 0;
1385     for (fe = myfe; fe;) {
1386         register struct CallBack *cbnext;
1387         for (cb = itocb(fe->firstcb); cb; cb = cbnext) {
1388             cbnext = itocb(cb->cnext);
1389             host = h_itoh(cb->hhead);
1390             if (cb->status == CB_DELAYED) {
1391                 if (!(host->hostFlags & HOSTDELETED)) {
1392                     h_Hold_r(host);
1393                     if (!tthead || (TNorm(tthead) < TNorm(cb->thead))) {
1394                         tthead = cb->thead;
1395                     }
1396                 }
1397                 TDel(cb);
1398                 HDel(cb);
1399                 CDel(cb, 0);    /* Don't let CDel clean up the fe */
1400                 /* leave hold for MultiBreakVolumeCallBack to clear */
1401             } else {
1402                 ViceLog(125,
1403                         ("Found host %p (%s:%d) non-DELAYED cb for %u:%u:%u\n",
1404                          host, afs_inet_ntoa_r(host->host, hoststr),
1405                          ntohs(host->port), fe->vnode, fe->unique, fe->volid));
1406             }
1407         }
1408         myfe = fe;
1409         fe = (struct FileEntry *)((struct object *)fe)->next;
1410         FreeFE(myfe);
1411     }
1412
1413     if (tthead) {
1414         ViceLog(125, ("Breaking volume %u\n", fid.Volume));
1415         henumParms.ncbas = 0;
1416         henumParms.fid = &fid;
1417         henumParms.thead = tthead;
1418         H_UNLOCK;
1419         h_Enumerate(MultiBreakVolumeLaterCallBack, (char *)&henumParms);
1420         H_LOCK;
1421         if (henumParms.ncbas) { /* do left-overs */
1422             struct AFSCBFids tf;
1423             tf.AFSCBFids_len = 1;
1424             tf.AFSCBFids_val = &fid;
1425
1426             MultiBreakCallBack_r(henumParms.cba, henumParms.ncbas, &tf, 0);
1427             henumParms.ncbas = 0;
1428         }
1429     }
1430     H_UNLOCK;
1431
1432     /* Arrange to be called again */
1433     return 1;
1434 }
1435
1436 /*
1437  * Delete all timed-out call back entries (to be called periodically by file
1438  * server)
1439  */
1440 int
1441 CleanupTimedOutCallBacks(void)
1442 {
1443     H_LOCK;
1444     CleanupTimedOutCallBacks_r();
1445     H_UNLOCK;
1446     return 0;
1447 }
1448
1449 int
1450 CleanupTimedOutCallBacks_r(void)
1451 {
1452     afs_uint32 now = CBtime(FT_ApproxTime());
1453     register afs_uint32 *thead;
1454     register struct CallBack *cb;
1455     register int ntimedout = 0;
1456     char hoststr[16];
1457
1458     while (tfirst <= now) {
1459         register int cbi;
1460         cbi = *(thead = THead(tfirst));
1461         if (cbi) {
1462             do {
1463                 cb = itocb(cbi);
1464                 cbi = cb->tnext;
1465                 ViceLog(8,
1466                         ("CCB: deleting timed out call back %x (%s:%d), (%u,%u,%u)\n",
1467                          h_itoh(cb->hhead)->host,
1468                          afs_inet_ntoa_r(h_itoh(cb->hhead)->host, hoststr),
1469                          h_itoh(cb->hhead)->port, itofe(cb->fhead)->volid,
1470                          itofe(cb->fhead)->vnode, itofe(cb->fhead)->unique));
1471                 HDel(cb);
1472                 CDel(cb, 1);
1473                 ntimedout++;
1474                 if (ntimedout > cbstuff.nblks) {
1475                     ViceLog(0, ("CCB: Internal Error -- shutting down...\n"));
1476                     DumpCallBackState();
1477                     ShutDownAndCore(PANIC);
1478                 }
1479             } while (cbi != *thead);
1480             *thead = 0;
1481         }
1482         tfirst++;
1483     }
1484     cbstuff.CBsTimedOut += ntimedout;
1485     ViceLog(7, ("CCB: deleted %d timed out callbacks\n", ntimedout));
1486     return (ntimedout > 0);
1487 }
1488
1489 static struct host *lih_host;
1490 static int lih_host_held;
1491
1492 /* Value of host->refCount that allows us to reliably infer that
1493  * host may be held by some other thread */
1494 #define OTHER_MUSTHOLD_LIH 2
1495
1496 /* This version does not allow 'host' to be selected unless its ActiveCall 
1497  * is newer than 'hostp' which is the host with the oldest ActiveCall from
1498  * the last pass (if it is provided).  We filter out any hosts that are
1499  * are held by other threads.
1500  */
1501 static int
1502 lih0_r(register struct host *host, register int flags, void *rock)
1503 {
1504     struct host *hostp = (struct host *) rock;
1505     if (host->cblist
1506         && (hostp && host != hostp) 
1507         && (host->refCount < OTHER_MUSTHOLD_LIH)
1508         && (!lih_host || host->ActiveCall < lih_host->ActiveCall) 
1509         && (!hostp || host->ActiveCall > hostp->ActiveCall)) {
1510         if (lih_host != NULL && lih_host_held) {
1511             h_Release_r(lih_host); /* release prev host */
1512         }
1513         lih_host = host;
1514         lih_host_held = !flags; /* on i==1, this === (lih_host_held = 1) */
1515         flags = 1; /* now flags is 1, but at next(i), it will be 0 again */
1516     }
1517     return flags;
1518 }
1519
1520 /* This version does not allow 'host' to be selected unless its ActiveCall 
1521  * is newer than 'hostp' which is the host with the oldest ActiveCall from
1522  * the last pass (if it is provided).  In this second varient, we do not 
1523  * prevent held hosts from being selected.
1524  */
1525 static int
1526 lih1_r(register struct host *host, register int flags, void *rock)
1527 {
1528     struct host *hostp = (struct host *) rock;
1529
1530     if (host->cblist
1531         && (hostp && host != hostp) 
1532         && (!lih_host || host->ActiveCall < lih_host->ActiveCall) 
1533         && (!hostp || host->ActiveCall > hostp->ActiveCall)) {
1534             if (lih_host != NULL && lih_host_held) {
1535                     h_Release_r(lih_host); /* really? */
1536             }
1537             lih_host = host;
1538             lih_host_held = !flags; /* see note above */
1539             flags = 1; /* see note above */
1540     }
1541     return flags;
1542 }
1543
1544 /* This could be upgraded to get more space each time */
1545 /* first pass: sequentially find the oldest host which isn't held by
1546                anyone for which we can clear callbacks;
1547                skipping 'hostp' */
1548 /* second pass: sequentially find the oldest host regardless of 
1549                whether or not the host is held; skipping 'hostp' */
1550 /* third pass: attempt to clear callbacks from 'hostp' */
1551 /* always called with hostp unlocked */
1552
1553 /* Note: hostlist is ordered most recently created host first and 
1554  * its order has no relationship to the most recently used. */
1555 extern struct host *hostList;
1556 static int
1557 GetSomeSpace_r(struct host *hostp, int locked)
1558 {
1559     register struct host *hp, *hp1, *hp2;
1560     int i = 0;
1561
1562     cbstuff.GotSomeSpaces++;
1563     ViceLog(5,
1564             ("GSS: First looking for timed out call backs via CleanupCallBacks\n"));
1565     if (CleanupTimedOutCallBacks_r()) {
1566         cbstuff.GSS3++;
1567         return 0;
1568     }
1569
1570     i = 0;
1571     hp1 = NULL;
1572     hp2 = hostList;
1573     do {
1574         lih_host = 0;
1575         h_Enumerate_r(i == 0 ? lih0_r : lih1_r, hp2, (char *)hp1);
1576         hp = lih_host;
1577         if (hp) {
1578             /* set in lih_r! private copy before giving up H_LOCK */
1579             int lih_host_held2=lih_host_held;   
1580             cbstuff.GSS4++;
1581             if ((hp != hostp) && !ClearHostCallbacks_r(hp, 0 /* not locked or held */ )) {
1582                 if (lih_host_held2)
1583                     h_Release_r(hp);
1584                 return 0;
1585             }
1586             if (lih_host_held2) {
1587                 h_Release_r(hp);
1588                 hp = NULL;
1589             }
1590             hp1 = hp;
1591             hp2 = hostList;
1592         } else {
1593             /*
1594              * Next time try getting callbacks from any host even if
1595              * it's deleted (that's actually great since we can freely
1596              * remove its callbacks) or it's held since the only other
1597              * option is starvation for the file server (i.e. until the
1598              * callback timeout arrives).
1599              */
1600             i++;
1601             hp1 = NULL;
1602             hp2 = hostList;
1603             cbstuff.GSS1++;
1604             ViceLog(5,
1605                     ("GSS: Try harder for longest inactive host cnt= %d\n",
1606                      i));
1607         }
1608     } while (i < 2);
1609
1610     /* Could not obtain space from other hosts, clear hostp's callback state */
1611     cbstuff.GSS2++;
1612     if (!locked) {
1613         h_Lock_r(hostp);
1614     }
1615     ClearHostCallbacks_r(hostp, 1 /*already locked */ );
1616     if (!locked) {
1617         h_Unlock_r(hostp);
1618     }
1619     return 0;
1620 }
1621
1622 /* locked - set if caller has already locked the host */
1623 static int
1624 ClearHostCallbacks_r(struct host *hp, int locked)
1625 {
1626     int code;
1627     char hoststr[16];
1628     struct rx_connection *cb_conn = NULL;
1629
1630     ViceLog(5,
1631             ("GSS: Delete longest inactive host %p (%s:%d)\n",
1632              hp, afs_inet_ntoa_r(hp->host, hoststr), ntohs(hp->port)));
1633
1634     if ((hp->hostFlags & HOSTDELETED)) {
1635         /* hp could go away after reacquiring H_LOCK in h_NBLock_r, so we can't
1636          * really use it; its callbacks will get cleared anyway when
1637          * h_TossStuff_r gets its hands on it */
1638         return 1;
1639     }
1640
1641     h_Hold_r(hp);
1642
1643     /** Try a non-blocking lock. If the lock is already held return
1644       * after releasing hold on hp
1645       */
1646     if (!locked) {
1647         if (h_NBLock_r(hp)) {
1648             h_Release_r(hp);
1649             return 1;
1650         }
1651     }
1652     if (hp->Console & 2) {
1653         /*
1654          * If the special console field is set it means that a thread
1655          * is waiting in AddCallBack1 after it set pointers to the
1656          * file entry and/or callback entry. Because of the bogus
1657          * usage of h_hold it won't prevent from another thread, this
1658          * one, to remove all the callbacks so just to be safe we keep
1659          * a reference. NOTE, on the last phase we'll free the calling
1660          * host's callbacks but that's ok...
1661          */
1662         cbstuff.GSS5++;
1663     }
1664     DeleteAllCallBacks_r(hp, 1);
1665     if (hp->hostFlags & VENUSDOWN) {
1666         hp->hostFlags &= ~RESETDONE;    /* remember that we must do a reset */
1667     } else if (!(hp->hostFlags & HOSTDELETED)) {
1668         /* host is up, try a call */
1669         hp->hostFlags &= ~ALTADDR;      /* alternate addresses are invalid */
1670         cb_conn = hp->callback_rxcon;
1671         rx_GetConnection(hp->callback_rxcon);
1672         if (hp->interface) {
1673             H_UNLOCK;
1674             code =
1675                 RXAFSCB_InitCallBackState3(cb_conn, &FS_HostUUID);
1676         } else {
1677             H_UNLOCK;
1678             code = RXAFSCB_InitCallBackState(cb_conn);
1679         }
1680         rx_PutConnection(cb_conn);
1681         cb_conn = NULL;
1682         H_LOCK;
1683         hp->hostFlags |= ALTADDR;       /* alternate addresses are valid */
1684         if (code) {
1685             /* failed, mark host down and need reset */
1686             hp->hostFlags |= VENUSDOWN;
1687             hp->hostFlags &= ~RESETDONE;
1688         } else {
1689             /* reset succeeded, we're done */
1690             hp->hostFlags |= RESETDONE;
1691         }
1692     }
1693     if (!locked)
1694         h_Unlock_r(hp);
1695     h_Release_r(hp);
1696
1697     return 0;
1698 }
1699 #endif /* INTERPRET_DUMP */
1700
1701
1702 int
1703 PrintCallBackStats(void)
1704 {
1705     fprintf(stderr,
1706             "%d add CB, %d break CB, %d del CB, %d del FE, %d CB's timed out, %d space reclaim, %d del host\n",
1707             cbstuff.AddCallBacks, cbstuff.BreakCallBacks,
1708             cbstuff.DeleteCallBacks, cbstuff.DeleteFiles, cbstuff.CBsTimedOut,
1709             cbstuff.GotSomeSpaces, cbstuff.DeleteAllCallBacks);
1710     fprintf(stderr, "%d CBs, %d FEs, (%d of total of %d 16-byte blocks)\n",
1711             cbstuff.nCBs, cbstuff.nFEs, cbstuff.nCBs + cbstuff.nFEs,
1712             cbstuff.nblks);
1713
1714     return 0;
1715 }
1716
1717 #define MAGIC 0x12345678        /* To check byte ordering of dump when it is read in */
1718 #define MAGICV2 0x12345679      /* To check byte ordering & version of dump when it is read in */
1719
1720
1721 #ifndef INTERPRET_DUMP
1722
1723 #ifdef AFS_DEMAND_ATTACH_FS
1724 /*
1725  * demand attach fs
1726  * callback state serialization
1727  */
1728 static int cb_stateSaveTimeouts(struct fs_dump_state * state);
1729 static int cb_stateSaveFEHash(struct fs_dump_state * state);
1730 static int cb_stateSaveFEs(struct fs_dump_state * state);
1731 static int cb_stateSaveFE(struct fs_dump_state * state, struct FileEntry * fe);
1732 static int cb_stateRestoreTimeouts(struct fs_dump_state * state);
1733 static int cb_stateRestoreFEHash(struct fs_dump_state * state);
1734 static int cb_stateRestoreFEs(struct fs_dump_state * state);
1735 static int cb_stateRestoreFE(struct fs_dump_state * state);
1736 static int cb_stateRestoreCBs(struct fs_dump_state * state, struct FileEntry * fe, 
1737                               struct iovec * iov, int niovecs);
1738
1739 static int cb_stateVerifyFEHash(struct fs_dump_state * state);
1740 static int cb_stateVerifyFE(struct fs_dump_state * state, struct FileEntry * fe);
1741 static int cb_stateVerifyFCBList(struct fs_dump_state * state, struct FileEntry * fe);
1742 static int cb_stateVerifyTimeoutQueues(struct fs_dump_state * state);
1743
1744 static int cb_stateFEToDiskEntry(struct FileEntry *, struct FEDiskEntry *);
1745 static int cb_stateDiskEntryToFE(struct fs_dump_state * state,
1746                                  struct FEDiskEntry *, struct FileEntry *);
1747
1748 static int cb_stateCBToDiskEntry(struct CallBack *, struct CBDiskEntry *);
1749 static int cb_stateDiskEntryToCB(struct fs_dump_state * state,
1750                                  struct CBDiskEntry *, struct CallBack *);
1751
1752 static int cb_stateFillHeader(struct callback_state_header * hdr);
1753 static int cb_stateCheckHeader(struct callback_state_header * hdr);
1754
1755 static int cb_stateAllocMap(struct fs_dump_state * state);
1756
1757 int
1758 cb_stateSave(struct fs_dump_state * state)
1759 {
1760     int ret = 0;
1761
1762     AssignInt64(state->eof_offset, &state->hdr->cb_offset);
1763
1764     /* invalidate callback state header */
1765     memset(state->cb_hdr, 0, sizeof(struct callback_state_header));
1766     if (fs_stateWriteHeader(state, &state->hdr->cb_offset, state->cb_hdr,
1767                             sizeof(struct callback_state_header))) {
1768         ret = 1;
1769         goto done;
1770     }
1771
1772     fs_stateIncEOF(state, sizeof(struct callback_state_header));
1773
1774     /* dump timeout state */
1775     if (cb_stateSaveTimeouts(state)) {
1776         ret = 1;
1777         goto done;
1778     }
1779
1780     /* dump fe hashtable state */
1781     if (cb_stateSaveFEHash(state)) {
1782         ret = 1;
1783         goto done;
1784     }
1785
1786     /* dump callback state */
1787     if (cb_stateSaveFEs(state)) {
1788         ret = 1;
1789         goto done;
1790     }
1791
1792     /* write the callback state header to disk */
1793     cb_stateFillHeader(state->cb_hdr);
1794     if (fs_stateWriteHeader(state, &state->hdr->cb_offset, state->cb_hdr,
1795                             sizeof(struct callback_state_header))) {
1796         ret = 1;
1797         goto done;
1798     }
1799     
1800  done:
1801     return ret;
1802 }
1803
1804 int
1805 cb_stateRestore(struct fs_dump_state * state)
1806 {
1807     int ret = 0;
1808
1809     if (fs_stateReadHeader(state, &state->hdr->cb_offset, state->cb_hdr,
1810                            sizeof(struct callback_state_header))) {
1811         ret = 1;
1812         goto done;
1813     }
1814
1815     if (cb_stateCheckHeader(state->cb_hdr)) {
1816         ret = 1;
1817         goto done;
1818     }
1819
1820     if (cb_stateAllocMap(state)) {
1821         ret = 1;
1822         goto done;
1823     }
1824
1825     if (cb_stateRestoreTimeouts(state)) {
1826         ret = 1;
1827         goto done;
1828     }
1829
1830     if (cb_stateRestoreFEHash(state)) {
1831         ret = 1;
1832         goto done;
1833     }
1834
1835     /* restore FEs and CBs from disk */
1836     if (cb_stateRestoreFEs(state)) {
1837         ret = 1;
1838         goto done;
1839     }
1840
1841     /* restore the timeout queue heads */
1842     tfirst = state->cb_hdr->tfirst;
1843
1844  done:
1845     return ret;
1846 }
1847
1848 int
1849 cb_stateRestoreIndices(struct fs_dump_state * state)
1850 {
1851     int i, ret = 0;
1852     struct FileEntry * fe;
1853     struct CallBack * cb;
1854
1855     /* restore indices in the FileEntry structures */
1856     for (i = 1; i < state->fe_map.len; i++) {
1857         if (state->fe_map.entries[i].new_idx) {
1858             fe = itofe(state->fe_map.entries[i].new_idx);
1859
1860             /* restore the fe->fnext entry */
1861             if (fe_OldToNew(state, fe->fnext, &fe->fnext)) {
1862                 ret = 1;
1863                 goto done;
1864             }
1865
1866             /* restore the fe->firstcb entry */
1867             if (cb_OldToNew(state, fe->firstcb, &fe->firstcb)) {
1868                 ret = 1;
1869                 goto done;
1870             }
1871         }
1872     }
1873     
1874     /* restore indices in the CallBack structures */
1875     for (i = 1; i < state->cb_map.len; i++) {
1876         if (state->cb_map.entries[i].new_idx) {
1877             cb = itocb(state->cb_map.entries[i].new_idx);
1878
1879             /* restore the cb->cnext entry */
1880             if (cb_OldToNew(state, cb->cnext, &cb->cnext)) {
1881                 ret = 1;
1882                 goto done;
1883             }
1884             
1885             /* restore the cb->fhead entry */
1886             if (fe_OldToNew(state, cb->fhead, &cb->fhead)) {
1887                 ret = 1;
1888                 goto done;
1889             }
1890
1891             /* restore the cb->hhead entry */
1892             if (h_OldToNew(state, cb->hhead, &cb->hhead)) {
1893                 ret = 1;
1894                 goto done;
1895             }
1896
1897             /* restore the cb->tprev entry */
1898             if (cb_OldToNew(state, cb->tprev, &cb->tprev)) {
1899                 ret = 1;
1900                 goto done;
1901             }
1902
1903             /* restore the cb->tnext entry */
1904             if (cb_OldToNew(state, cb->tnext, &cb->tnext)) {
1905                 ret = 1;
1906                 goto done;
1907             }
1908
1909             /* restore the cb->hprev entry */
1910             if (cb_OldToNew(state, cb->hprev, &cb->hprev)) {
1911                 ret = 1;
1912                 goto done;
1913             }
1914
1915             /* restore the cb->hnext entry */
1916             if (cb_OldToNew(state, cb->hnext, &cb->hnext)) {
1917                 ret = 1;
1918                 goto done;
1919             }
1920         }
1921     }
1922
1923     /* restore the timeout queue head indices */
1924     for (i = 0; i < state->cb_timeout_hdr->records; i++) {
1925         if (cb_OldToNew(state, timeout[i], &timeout[i])) {
1926             ret = 1;
1927             goto done;
1928         }
1929     }
1930
1931     /* restore the FE hash table queue heads */
1932     for (i = 0; i < state->cb_fehash_hdr->records; i++) {
1933         if (fe_OldToNew(state, HashTable[i], &HashTable[i])) {
1934             ret = 1;
1935             goto done;
1936         }
1937     }
1938
1939  done:
1940     return ret;
1941 }
1942
1943 int
1944 cb_stateVerify(struct fs_dump_state * state)
1945 {
1946     int ret = 0;
1947
1948     if (cb_stateVerifyFEHash(state)) {
1949         ret = 1;
1950     }
1951
1952     if (cb_stateVerifyTimeoutQueues(state)) {
1953         ret = 1;
1954     }
1955
1956     return ret;
1957 }
1958
1959 static int
1960 cb_stateVerifyFEHash(struct fs_dump_state * state)
1961 {
1962     int ret = 0, i;
1963     struct FileEntry * fe;
1964     afs_uint32 fei, chain_len;
1965
1966     for (i = 0; i < FEHASH_SIZE; i++) {
1967         chain_len = 0;
1968         for (fei = HashTable[i], fe = itofe(fei);
1969              fe;
1970              fei = fe->fnext, fe = itofe(fei)) {
1971             if (fei > cbstuff.nblks) {
1972                 ViceLog(0, ("cb_stateVerifyFEHash: error: index out of range (fei=%d)\n", fei));
1973                 ret = 1;
1974                 break;
1975             }
1976             if (cb_stateVerifyFE(state, fe)) {
1977                 ret = 1;
1978             }
1979             if (chain_len > FS_STATE_FE_MAX_HASH_CHAIN_LEN) {
1980                 ViceLog(0, ("cb_stateVerifyFEHash: error: hash chain %d length exceeds %d; assuming there's a loop\n",
1981                             i, FS_STATE_FE_MAX_HASH_CHAIN_LEN));
1982                 ret = 1;
1983                 break;
1984             }
1985             chain_len++;
1986         }
1987     }
1988
1989     return ret;
1990 }
1991
1992 static int
1993 cb_stateVerifyFE(struct fs_dump_state * state, struct FileEntry * fe)
1994 {
1995     int ret = 0;
1996
1997     if ((fe->firstcb && !fe->ncbs) ||
1998         (!fe->firstcb && fe->ncbs)) {
1999         ViceLog(0, ("cb_stateVerifyFE: error: fe->firstcb does not agree with fe->ncbs (fei=%lu, fe->firstcb=%lu, fe->ncbs=%lu)\n",
2000                     afs_printable_uint32_lu(fetoi(fe)),
2001                     afs_printable_uint32_lu(fe->firstcb),
2002                     afs_printable_uint32_lu(fe->ncbs)));
2003         ret = 1;
2004     }
2005     if (cb_stateVerifyFCBList(state, fe)) {
2006         ViceLog(0, ("cb_stateVerifyFE: error: FCBList failed verification (fei=%lu)\n",
2007                     afs_printable_uint32_lu(fetoi(fe))));
2008         ret = 1;
2009     }
2010
2011     return ret;
2012 }
2013
2014 static int
2015 cb_stateVerifyFCBList(struct fs_dump_state * state, struct FileEntry * fe)
2016 {
2017     int ret = 0;
2018     afs_uint32 cbi, fei, chain_len = 0;
2019     struct CallBack * cb;
2020
2021     fei = fetoi(fe);
2022
2023     for (cbi = fe->firstcb, cb = itocb(cbi);
2024          cb;
2025          cbi = cb->cnext, cb = itocb(cbi)) {
2026         if (cbi > cbstuff.nblks) {
2027             ViceLog(0, ("cb_stateVerifyFCBList: error: list index out of range (cbi=%d, ncbs=%d)\n",
2028                         cbi, cbstuff.nblks));
2029             ret = 1;
2030             goto done;
2031         }
2032         if (cb->fhead != fei) {
2033             ViceLog(0, ("cb_stateVerifyFCBList: error: cb->fhead != fei (fei=%d, cb->fhead=%d)\n",
2034                         fei, cb->fhead));
2035             ret = 1;
2036         }
2037         if (chain_len > FS_STATE_FCB_MAX_LIST_LEN) {
2038             ViceLog(0, ("cb_stateVerifyFCBList: error: list length exceeds %d (fei=%d); assuming there's a loop\n",
2039                         FS_STATE_FCB_MAX_LIST_LEN, fei));
2040             ret = 1;
2041             goto done;
2042         }
2043         chain_len++;
2044     }
2045
2046     if (fe->ncbs != chain_len) {
2047         ViceLog(0, ("cb_stateVerifyFCBList: error: list length mismatch (len=%d, fe->ncbs=%d)\n",
2048                     chain_len, fe->ncbs));
2049         ret = 1;
2050     }
2051
2052  done:
2053     return ret;
2054 }
2055
2056 int
2057 cb_stateVerifyHCBList(struct fs_dump_state * state, struct host * host)
2058 {
2059     int ret = 0;
2060     afs_uint32 hi, chain_len, cbi;
2061     struct CallBack *cb, *ncb;
2062
2063     hi = h_htoi(host);
2064     chain_len = 0;
2065
2066     for (cbi = host->cblist, cb = itocb(cbi);
2067          cb;
2068          cbi = cb->hnext, cb = ncb) {
2069         if (chain_len && (host->cblist == cbi)) {
2070             /* we've wrapped around the circular list, and everything looks ok */
2071             break;
2072         }
2073         if (cb->hhead != hi) {
2074             ViceLog(0, ("cb_stateVerifyHCBList: error: incorrect cb->hhead (cbi=%d, h->index=%d, cb->hhead=%d)\n",
2075                         cbi, hi, cb->hhead));
2076             ret = 1;
2077         }
2078         if (!cb->hprev || !cb->hnext) {
2079             ViceLog(0, ("cb_stateVerifyHCBList: error: null index in circular list (cbi=%d, h->index=%d)\n",
2080                         cbi, hi));
2081             ret = 1;
2082             goto done;
2083         }
2084         if ((cb->hprev > cbstuff.nblks) ||
2085             (cb->hnext > cbstuff.nblks)) {
2086             ViceLog(0, ("cb_stateVerifyHCBList: error: list index out of range (cbi=%d, h->index=%d, cb->hprev=%d, cb->hnext=%d, nCBs=%d)\n",
2087                         cbi, hi, cb->hprev, cb->hnext, cbstuff.nblks));
2088             ret = 1;
2089             goto done;
2090         }
2091         ncb = itocb(cb->hnext);
2092         if (cbi != ncb->hprev) {
2093             ViceLog(0, ("cb_stateVerifyHCBList: error: corrupt linked list (cbi=%d, h->index=%d)\n",
2094                         cbi, hi));
2095             ret = 1;
2096             goto done;
2097         }
2098         if (chain_len > FS_STATE_HCB_MAX_LIST_LEN) {
2099             ViceLog(0, ("cb_stateVerifyFCBList: error: list length exceeds %d (h->index=%d); assuming there's a loop\n",
2100                         FS_STATE_HCB_MAX_LIST_LEN, hi));
2101             ret = 1;
2102             goto done;
2103         }
2104         chain_len++;
2105     }
2106
2107  done:
2108     return ret;
2109 }
2110
2111 static int
2112 cb_stateVerifyTimeoutQueues(struct fs_dump_state * state)
2113 {
2114     int ret = 0, i;
2115     afs_uint32 cbi, chain_len;
2116     struct CallBack *cb, *ncb;
2117
2118     for (i = 0; i < CB_NUM_TIMEOUT_QUEUES; i++) {
2119         chain_len = 0;
2120         for (cbi = timeout[i], cb = itocb(cbi);
2121              cb;
2122              cbi = cb->tnext, cb = ncb) {
2123             if (chain_len && (cbi == timeout[i])) {
2124                 /* we've wrapped around the circular list, and everything looks ok */
2125                 break;
2126             }
2127             if (cbi > cbstuff.nblks) {
2128                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: error: list index out of range (cbi=%d, tindex=%d)\n",
2129                             cbi, i));
2130                 ret = 1;
2131                 break;
2132             }
2133             if (itot(cb->thead) != &timeout[i]) {
2134                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: error: cb->thead points to wrong timeout queue (tindex=%d, cbi=%d, cb->thead=%d)\n",
2135                             i, cbi, cb->thead));
2136                 ret = 1;
2137             }
2138             if (!cb->tprev || !cb->tnext) {
2139                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: null index in circular list (cbi=%d, tindex=%d)\n",
2140                             cbi, i));
2141                 ret = 1;
2142                 break;
2143             }
2144             if ((cb->tprev > cbstuff.nblks) ||
2145                 (cb->tnext > cbstuff.nblks)) {
2146                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: list index out of range (cbi=%d, tindex=%d, cb->tprev=%d, cb->tnext=%d, nCBs=%d)\n",
2147                             cbi, i, cb->tprev, cb->tnext, cbstuff.nblks));
2148                 ret = 1;
2149                 break;
2150             }
2151             ncb = itocb(cb->tnext);
2152             if (cbi != ncb->tprev) {
2153                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: corrupt linked list (cbi=%d, tindex=%d)\n",
2154                             cbi, i));
2155                 ret = 1;
2156                 break;
2157             }
2158             if (chain_len > FS_STATE_TCB_MAX_LIST_LEN) {
2159                 ViceLog(0, ("cb_stateVerifyTimeoutQueues: list length exceeds %d (tindex=%d); assuming there's a loop\n",
2160                             FS_STATE_TCB_MAX_LIST_LEN, i));
2161                 ret = 1;
2162                 break;
2163             }
2164             chain_len++;
2165         }
2166     }
2167
2168     return ret;
2169 }
2170
2171 static int
2172 cb_stateSaveTimeouts(struct fs_dump_state * state)
2173 {
2174     int ret = 0;
2175     struct iovec iov[2];
2176
2177     AssignInt64(state->eof_offset, &state->cb_hdr->timeout_offset);
2178
2179     memset(state->cb_timeout_hdr, 0, sizeof(struct callback_state_fehash_header));
2180     state->cb_timeout_hdr->magic = CALLBACK_STATE_TIMEOUT_MAGIC;
2181     state->cb_timeout_hdr->records = CB_NUM_TIMEOUT_QUEUES;
2182     state->cb_timeout_hdr->len = sizeof(struct callback_state_timeout_header) +
2183         (state->cb_timeout_hdr->records * sizeof(afs_uint32));
2184
2185     iov[0].iov_base = (char *)state->cb_timeout_hdr;
2186     iov[0].iov_len = sizeof(struct callback_state_timeout_header);
2187     iov[1].iov_base = (char *)timeout;
2188     iov[1].iov_len = sizeof(timeout);
2189
2190     if (fs_stateSeek(state, &state->cb_hdr->timeout_offset)) {
2191         ret = 1;
2192         goto done;
2193     }
2194
2195     if (fs_stateWriteV(state, iov, 2)) {
2196         ret = 1;
2197         goto done;
2198     }
2199
2200     fs_stateIncEOF(state, state->cb_timeout_hdr->len);
2201
2202  done:
2203     return ret;
2204 }
2205
2206 static int
2207 cb_stateRestoreTimeouts(struct fs_dump_state * state)
2208 {
2209     int ret = 0, len;
2210
2211     if (fs_stateReadHeader(state, &state->cb_hdr->timeout_offset,
2212                            state->cb_timeout_hdr, 
2213                            sizeof(struct callback_state_timeout_header))) {
2214         ret = 1;
2215         goto done;
2216     }
2217
2218     if (state->cb_timeout_hdr->magic != CALLBACK_STATE_TIMEOUT_MAGIC) {
2219         ret = 1;
2220         goto done;
2221     }
2222     if (state->cb_timeout_hdr->records != CB_NUM_TIMEOUT_QUEUES) {
2223         ret = 1;
2224         goto done;
2225     }
2226
2227     len = state->cb_timeout_hdr->records * sizeof(afs_uint32);
2228
2229     if (state->cb_timeout_hdr->len !=
2230         (sizeof(struct callback_state_timeout_header) + len)) {
2231         ret = 1;
2232         goto done;
2233     }
2234
2235     if (fs_stateRead(state, timeout, len)) {
2236         ret = 1;
2237         goto done;
2238     }
2239
2240  done:
2241     return ret;
2242 }
2243
2244 static int
2245 cb_stateSaveFEHash(struct fs_dump_state * state)
2246 {
2247     int ret = 0;
2248     struct iovec iov[2];
2249
2250     AssignInt64(state->eof_offset, &state->cb_hdr->fehash_offset);
2251
2252     memset(state->cb_fehash_hdr, 0, sizeof(struct callback_state_fehash_header));
2253     state->cb_fehash_hdr->magic = CALLBACK_STATE_FEHASH_MAGIC;
2254     state->cb_fehash_hdr->records = FEHASH_SIZE;
2255     state->cb_fehash_hdr->len = sizeof(struct callback_state_fehash_header) +
2256         (state->cb_fehash_hdr->records * sizeof(afs_uint32));
2257
2258     iov[0].iov_base = (char *)state->cb_fehash_hdr;
2259     iov[0].iov_len = sizeof(struct callback_state_fehash_header);
2260     iov[1].iov_base = (char *)HashTable;
2261     iov[1].iov_len = sizeof(HashTable);
2262
2263     if (fs_stateSeek(state, &state->cb_hdr->fehash_offset)) {
2264         ret = 1;
2265         goto done;
2266     }
2267
2268     if (fs_stateWriteV(state, iov, 2)) {
2269         ret = 1;
2270         goto done;
2271     }
2272
2273     fs_stateIncEOF(state, state->cb_fehash_hdr->len);
2274
2275  done:
2276     return ret;
2277 }
2278
2279 static int
2280 cb_stateRestoreFEHash(struct fs_dump_state * state)
2281 {
2282     int ret = 0, len;
2283
2284     if (fs_stateReadHeader(state, &state->cb_hdr->fehash_offset,
2285                            state->cb_fehash_hdr, 
2286                            sizeof(struct callback_state_fehash_header))) {
2287         ret = 1;
2288         goto done;
2289     }
2290
2291     if (state->cb_fehash_hdr->magic != CALLBACK_STATE_FEHASH_MAGIC) {
2292         ret = 1;
2293         goto done;
2294     }
2295     if (state->cb_fehash_hdr->records != FEHASH_SIZE) {
2296         ret = 1;
2297         goto done;
2298     }
2299
2300     len = state->cb_fehash_hdr->records * sizeof(afs_uint32);
2301
2302     if (state->cb_fehash_hdr->len !=
2303         (sizeof(struct callback_state_fehash_header) + len)) {
2304         ret = 1;
2305         goto done;
2306     }
2307
2308     if (fs_stateRead(state, HashTable, len)) {
2309         ret = 1;
2310         goto done;
2311     }
2312
2313  done:
2314     return ret;
2315 }
2316
2317 static int
2318 cb_stateSaveFEs(struct fs_dump_state * state)
2319 {
2320     int ret = 0;
2321     register int fei, hash;
2322     register struct FileEntry *fe;
2323
2324     AssignInt64(state->eof_offset, &state->cb_hdr->fe_offset);
2325
2326     for (hash = 0; hash < FEHASH_SIZE ; hash++) {
2327         for (fei = HashTable[hash]; fei; fei = fe->fnext) {
2328             fe = itofe(fei);
2329             if (cb_stateSaveFE(state, fe)) {
2330                 ret = 1;
2331                 goto done;
2332             }
2333         }
2334     }
2335
2336  done:
2337     return ret;
2338 }
2339
2340 static int
2341 cb_stateRestoreFEs(struct fs_dump_state * state)
2342 {
2343     int count, nFEs, ret = 0;
2344
2345     nFEs = state->cb_hdr->nFEs;
2346
2347     for (count = 0; count < nFEs; count++) {
2348         if (cb_stateRestoreFE(state)) {
2349             ret = 1;
2350             goto done;
2351         }
2352     }
2353
2354  done:
2355     return ret;
2356 }
2357
2358 static int
2359 cb_stateSaveFE(struct fs_dump_state * state, struct FileEntry * fe)
2360 {
2361     int ret = 0, iovcnt, cbi, written = 0;
2362     afs_uint32 fei;
2363     struct callback_state_entry_header hdr;
2364     struct FEDiskEntry fedsk;
2365     struct CBDiskEntry cbdsk[16];
2366     struct iovec iov[16];
2367     struct CallBack *cb;
2368
2369     fei = fetoi(fe);
2370     if (fei > state->cb_hdr->fe_max) {
2371         state->cb_hdr->fe_max = fei;
2372     }
2373
2374     memset(&hdr, 0, sizeof(struct callback_state_entry_header));
2375
2376     if (cb_stateFEToDiskEntry(fe, &fedsk)) {
2377         ret = 1;
2378         goto done;
2379     }
2380
2381     iov[0].iov_base = (char *)&hdr;
2382     iov[0].iov_len = sizeof(hdr);
2383     iov[1].iov_base = (char *)&fedsk;
2384     iov[1].iov_len = sizeof(struct FEDiskEntry);
2385     iovcnt = 2;
2386
2387     for (cbi = fe->firstcb, cb = itocb(cbi); 
2388          cb != NULL; 
2389          cbi = cb->cnext, cb = itocb(cbi), hdr.nCBs++) {
2390         if (cbi > state->cb_hdr->cb_max) {
2391             state->cb_hdr->cb_max = cbi;
2392         }
2393         if (cb_stateCBToDiskEntry(cb, &cbdsk[iovcnt])) {
2394             ret = 1;
2395             goto done;
2396         }
2397         cbdsk[iovcnt].index = cbi;
2398         iov[iovcnt].iov_base = (char *)&cbdsk[iovcnt];
2399         iov[iovcnt].iov_len = sizeof(struct CBDiskEntry);
2400         iovcnt++;
2401         if ((iovcnt == 16) || (!cb->cnext)) {
2402             if (fs_stateWriteV(state, iov, iovcnt)) {
2403                 ret = 1;
2404                 goto done;
2405             }
2406             written = 1;
2407             iovcnt = 0;
2408         }
2409     }
2410
2411     hdr.magic = CALLBACK_STATE_ENTRY_MAGIC;
2412     hdr.len = sizeof(hdr) + sizeof(struct FEDiskEntry) + 
2413         (hdr.nCBs * sizeof(struct CBDiskEntry));
2414
2415     if (!written) {
2416         if (fs_stateWriteV(state, iov, iovcnt)) {
2417             ret = 1;
2418             goto done;
2419         }
2420     } else {
2421         if (fs_stateWriteHeader(state, &state->eof_offset, &hdr, sizeof(hdr))) {
2422             ret = 1;
2423             goto done;
2424         }
2425     }
2426
2427     fs_stateIncEOF(state, hdr.len);
2428
2429     if (written) {
2430         if (fs_stateSeek(state, &state->eof_offset)) {
2431             ret = 1;
2432             goto done;
2433         }
2434     }
2435
2436     state->cb_hdr->nFEs++;
2437     state->cb_hdr->nCBs += hdr.nCBs;
2438
2439  done:
2440     return ret;
2441 }
2442
2443 static int
2444 cb_stateRestoreFE(struct fs_dump_state * state)
2445 {
2446     int ret = 0, iovcnt, nCBs;
2447     struct callback_state_entry_header hdr;
2448     struct FEDiskEntry fedsk;
2449     struct CBDiskEntry cbdsk[16];
2450     struct iovec iov[16];
2451     struct FileEntry * fe;
2452
2453     iov[0].iov_base = (char *)&hdr;
2454     iov[0].iov_len = sizeof(hdr);
2455     iov[1].iov_base = (char *)&fedsk;
2456     iov[1].iov_len = sizeof(fedsk);
2457     iovcnt = 2;
2458
2459     if (fs_stateReadV(state, iov, iovcnt)) {
2460         ret = 1;
2461         goto done;
2462     }
2463
2464     if (hdr.magic != CALLBACK_STATE_ENTRY_MAGIC) {
2465         ret = 1;
2466         goto done;
2467     }
2468
2469     fe = GetFE();
2470     if (fe == NULL) {
2471         ViceLog(0, ("cb_stateRestoreFE: ran out of free FileEntry structures\n"));
2472         ret = 1;
2473         goto done;
2474     }
2475
2476     if (cb_stateDiskEntryToFE(state, &fedsk, fe)) {
2477         ret = 1;
2478         goto done;
2479     }
2480
2481     if (hdr.nCBs) {
2482         for (iovcnt = 0, nCBs = 0;
2483              nCBs < hdr.nCBs;
2484              nCBs++) {
2485             iov[iovcnt].iov_base = (char *)&cbdsk[iovcnt];
2486             iov[iovcnt].iov_len = sizeof(struct CBDiskEntry);
2487             iovcnt++;
2488             if ((iovcnt == 16) || (nCBs == hdr.nCBs - 1)) {
2489                 if (fs_stateReadV(state, iov, iovcnt)) {
2490                     ret = 1;
2491                     goto done;
2492                 }
2493                 if (cb_stateRestoreCBs(state, fe, iov, iovcnt)) {
2494                     ret = 1;
2495                     goto done;
2496                 }
2497                 iovcnt = 0;
2498             }
2499         }
2500     }
2501     
2502  done:
2503     return ret;
2504 }
2505
2506 static int
2507 cb_stateRestoreCBs(struct fs_dump_state * state, struct FileEntry * fe, 
2508                    struct iovec * iov, int niovecs)
2509 {
2510     int ret = 0, idx;
2511     register struct CallBack * cb;
2512     struct CBDiskEntry * cbdsk;
2513     afs_uint32 fei;
2514
2515     fei = fetoi(fe);
2516
2517     for (idx = 0; idx < niovecs; idx++) {
2518         cbdsk = (struct CBDiskEntry *) iov[idx].iov_base;
2519         if ((cb = GetCB()) == NULL) {
2520             ViceLog(0, ("cb_stateRestoreCBs: ran out of free CallBack structures\n"));
2521             ret = 1;
2522             goto done;
2523         }
2524         if (cb_stateDiskEntryToCB(state, cbdsk, cb)) {
2525             ViceLog(0, ("cb_stateRestoreCBs: corrupt CallBack disk entry\n"));
2526             ret = 1;
2527             goto done;
2528         }
2529     }
2530
2531  done:
2532     return ret;
2533 }
2534
2535
2536 static int
2537 cb_stateFillHeader(struct callback_state_header * hdr)
2538 {
2539     hdr->stamp.magic = CALLBACK_STATE_MAGIC;
2540     hdr->stamp.version = CALLBACK_STATE_VERSION;
2541     hdr->tfirst = tfirst;
2542     return 0;
2543 }
2544
2545 static int
2546 cb_stateCheckHeader(struct callback_state_header * hdr)
2547 {
2548     int ret = 0;
2549
2550     if (hdr->stamp.magic != CALLBACK_STATE_MAGIC) {
2551         ret = 1;
2552     } else if (hdr->stamp.version != CALLBACK_STATE_VERSION) {
2553         ret = 1;
2554     } else if ((hdr->nFEs > cbstuff.nblks) || (hdr->nCBs > cbstuff.nblks)) {
2555         ViceLog(0, ("cb_stateCheckHeader: saved callback state larger than callback memory allocation\n"));
2556         ret = 1;
2557     }
2558     return ret;
2559 }
2560
2561 /* disk entry conversion routines */
2562 static int
2563 cb_stateFEToDiskEntry(struct FileEntry * in, struct FEDiskEntry * out)
2564 {
2565     memcpy(&out->fe, in, sizeof(struct FileEntry));
2566     out->index = fetoi(in);
2567     return 0;
2568 }
2569
2570 static int
2571 cb_stateDiskEntryToFE(struct fs_dump_state * state, 
2572                       struct FEDiskEntry * in, struct FileEntry * out)
2573 {
2574     int ret = 0;
2575
2576     memcpy(out, &in->fe, sizeof(struct FileEntry));
2577
2578     /* setup FE map entry */
2579     if (!in->index || (in->index >= state->fe_map.len)) {
2580         ViceLog(0, ("cb_stateDiskEntryToFE: index (%d) out of range",
2581                     in->index));
2582         ret = 1;
2583         goto done;
2584     }
2585     state->fe_map.entries[in->index].old_idx = in->index;
2586     state->fe_map.entries[in->index].new_idx = fetoi(out);
2587
2588  done:
2589     return ret;
2590 }
2591
2592 static int
2593 cb_stateCBToDiskEntry(struct CallBack * in, struct CBDiskEntry * out)
2594 {
2595     memcpy(&out->cb, in, sizeof(struct CallBack));
2596     out->index = cbtoi(in);
2597     return 0;
2598 }
2599
2600 static int
2601 cb_stateDiskEntryToCB(struct fs_dump_state * state,
2602                       struct CBDiskEntry * in, struct CallBack * out)
2603 {
2604     int ret = 0;
2605
2606     memcpy(out, &in->cb, sizeof(struct CallBack));
2607
2608     /* setup CB map entry */
2609     if (!in->index || (in->index >= state->cb_map.len)) {
2610         ViceLog(0, ("cb_stateDiskEntryToCB: index (%d) out of range\n",
2611                     in->index));
2612         ret = 1;
2613         goto done;
2614     }
2615     state->cb_map.entries[in->index].old_idx = in->index;
2616     state->cb_map.entries[in->index].new_idx = cbtoi(out);
2617
2618  done:
2619     return ret;
2620 }
2621
2622 /* index map routines */
2623 static int
2624 cb_stateAllocMap(struct fs_dump_state * state)
2625 {
2626     state->fe_map.len = state->cb_hdr->fe_max + 1;
2627     state->cb_map.len = state->cb_hdr->cb_max + 1;
2628     state->fe_map.entries = (struct idx_map_entry_t *)
2629         calloc(state->fe_map.len, sizeof(struct idx_map_entry_t));
2630     state->cb_map.entries = (struct idx_map_entry_t *)
2631         calloc(state->cb_map.len, sizeof(struct idx_map_entry_t));
2632     return ((state->fe_map.entries != NULL) && (state->cb_map.entries != NULL)) ? 0 : 1;
2633 }
2634
2635 int
2636 fe_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
2637 {
2638     int ret = 0;
2639
2640     /* FEs use a one-based indexing system, so old==0 implies no mapping */
2641     if (!old) {
2642         *new = 0;
2643         goto done;
2644     }
2645
2646     if (old >= state->fe_map.len) {
2647         ViceLog(0, ("fe_OldToNew: index %d is out of range\n", old));
2648         ret = 1;
2649     } else if (state->fe_map.entries[old].old_idx != old) { /* sanity check */
2650         ViceLog(0, ("fe_OldToNew: index %d points to an invalid FileEntry record\n", old));
2651         ret = 1;
2652     } else {
2653         *new = state->fe_map.entries[old].new_idx;
2654     }
2655
2656  done:
2657     return ret;
2658 }
2659
2660 int
2661 cb_OldToNew(struct fs_dump_state * state, afs_uint32 old, afs_uint32 * new)
2662 {
2663     int ret = 0;
2664
2665     /* CBs use a one-based indexing system, so old==0 implies no mapping */
2666     if (!old) {
2667         *new = 0;
2668         goto done;
2669     }
2670
2671     if (old >= state->cb_map.len) {
2672         ViceLog(0, ("cb_OldToNew: index %d is out of range\n", old));
2673         ret = 1;
2674     } else if (state->cb_map.entries[old].old_idx != old) { /* sanity check */
2675         ViceLog(0, ("cb_OldToNew: index %d points to an invalid CallBack record\n", old));
2676         ret = 1;
2677     } else {
2678         *new = state->cb_map.entries[old].new_idx;
2679     }
2680
2681  done:
2682     return ret;
2683 }
2684 #endif /* AFS_DEMAND_ATTACH_FS */
2685
2686 int
2687 DumpCallBackState(void)
2688 {
2689     int fd, oflag;
2690     afs_uint32 magic = MAGICV2, now = (afs_int32) FT_ApproxTime(), freelisthead;
2691
2692     oflag = O_WRONLY | O_CREAT | O_TRUNC;
2693 #ifdef AFS_NT40_ENV
2694     oflag |= O_BINARY;
2695 #endif
2696     fd = open(AFSDIR_SERVER_CBKDUMP_FILEPATH, oflag, 0666);
2697     if (fd < 0) {
2698         ViceLog(0,
2699                 ("Couldn't create callback dump file %s\n",
2700                  AFSDIR_SERVER_CBKDUMP_FILEPATH));
2701         return 0;
2702     }
2703     (void)write(fd, &magic, sizeof(magic));
2704     (void)write(fd, &now, sizeof(now));
2705     (void)write(fd, &cbstuff, sizeof(cbstuff));
2706     (void)write(fd, TimeOuts, sizeof(TimeOuts));
2707     (void)write(fd, timeout, sizeof(timeout));
2708     (void)write(fd, &tfirst, sizeof(tfirst));
2709     freelisthead = cbtoi((struct CallBack *)CBfree);
2710     (void)write(fd, &freelisthead, sizeof(freelisthead));       /* This is a pointer */
2711     freelisthead = fetoi((struct FileEntry *)FEfree);
2712     (void)write(fd, &freelisthead, sizeof(freelisthead));       /* This is a pointer */
2713     (void)write(fd, HashTable, sizeof(HashTable));
2714     (void)write(fd, &CB[1], sizeof(CB[1]) * cbstuff.nblks);     /* CB stuff */
2715     (void)write(fd, &FE[1], sizeof(FE[1]) * cbstuff.nblks);     /* FE stuff */
2716     close(fd);
2717
2718     return 0;
2719 }
2720
2721 #endif /* !INTERPRET_DUMP */
2722
2723 #ifdef INTERPRET_DUMP
2724
2725 /* This is only compiled in for the callback analyzer program */
2726 /* Returns the time of the dump */
2727 time_t
2728 ReadDump(char *file, int timebits)
2729 {
2730     int fd, oflag;
2731     afs_uint32 magic, freelisthead;
2732     afs_uint32 now;
2733 #ifdef AFS_64BIT_ENV
2734     afs_int64 now64;
2735 #endif
2736
2737     oflag = O_RDONLY;
2738 #ifdef AFS_NT40_ENV
2739     oflag |= O_BINARY;
2740 #endif
2741     fd = open(file, oflag);
2742     if (fd < 0) {
2743         fprintf(stderr, "Couldn't read dump file %s\n", file);
2744         exit(1);
2745     }
2746     read(fd, &magic, sizeof(magic));
2747     if (magic == MAGICV2) {
2748         timebits = 32;
2749     } else {
2750         if (magic != MAGIC) {
2751             fprintf(stderr,
2752                     "Magic number of %s is invalid.  You might be trying to\n",
2753                     file);
2754             fprintf(stderr,
2755                     "run this program on a machine type with a different byte ordering.\n");
2756             exit(1);
2757         }
2758     }
2759 #ifdef AFS_64BIT_ENV
2760     if (timebits == 64) {
2761         read(fd, &now64, sizeof(afs_int64));
2762         now = (afs_int32) now64;
2763     } else
2764 #endif
2765         read(fd, &now, sizeof(afs_int32));
2766     read(fd, &cbstuff, sizeof(cbstuff));
2767     read(fd, TimeOuts, sizeof(TimeOuts));
2768     read(fd, timeout, sizeof(timeout));
2769     read(fd, &tfirst, sizeof(tfirst));
2770     read(fd, &freelisthead, sizeof(freelisthead));
2771     CB = ((struct CallBack
2772            *)(calloc(cbstuff.nblks, sizeof(struct CallBack)))) - 1;
2773     FE = ((struct FileEntry
2774            *)(calloc(cbstuff.nblks, sizeof(struct FileEntry)))) - 1;
2775     CBfree = (struct CallBack *)itocb(freelisthead);
2776     read(fd, &freelisthead, sizeof(freelisthead));
2777     FEfree = (struct FileEntry *)itofe(freelisthead);
2778     read(fd, HashTable, sizeof(HashTable));
2779     read(fd, &CB[1], sizeof(CB[1]) * cbstuff.nblks);    /* CB stuff */
2780     read(fd, &FE[1], sizeof(FE[1]) * cbstuff.nblks);    /* FE stuff */
2781     if (close(fd)) {
2782         perror("Error reading dumpfile");
2783         exit(1);
2784     }
2785     return now;
2786 }
2787
2788 #ifdef AFS_NT40_ENV
2789 #include "AFS_component_version_number.h"
2790 #else
2791 #include "AFS_component_version_number.c"
2792 #endif
2793
2794 int
2795 main(int argc, char **argv)
2796 {
2797     int err = 0, cbi = 0, stats = 0, noptions = 0, all = 0, vol = 0, raw = 0;
2798     static AFSFid fid;
2799     register struct FileEntry *fe;
2800     register struct CallBack *cb;
2801     afs_int32 now;
2802     int timebits = 32;
2803     
2804     memset(&fid, 0, sizeof(fid));
2805     argc--;
2806     argv++;
2807     while (argc && **argv == '-') {
2808         noptions++;
2809         argc--;
2810         if (!strcmp(*argv, "-host")) {
2811             if (argc < 1) {
2812                 err++;
2813                 break;
2814             }
2815             argc--;
2816             cbi = atoi(*++argv);
2817         } else if (!strcmp(*argv, "-fid")) {
2818             if (argc < 2) {
2819                 err++;
2820                 break;
2821             }
2822             argc -= 3;
2823             fid.Volume = atoi(*++argv);
2824             fid.Vnode = atoi(*++argv);
2825             fid.Unique = atoi(*++argv);
2826         } else if (!strcmp(*argv, "-time")) {
2827             fprintf(stderr, "-time not supported\n");
2828             exit(1);
2829         } else if (!strcmp(*argv, "-stats")) {
2830             stats = 1;
2831         } else if (!strcmp(*argv, "-all")) {
2832             all = 1;
2833         } else if (!strcmp(*argv, "-raw")) {
2834             raw = 1;
2835         } else if (!strcmp(*argv, "-timebits")) {
2836             if (argc < 1) {
2837                 err++;
2838                 break;
2839             }
2840             argc--;
2841             timebits = atoi(*++argv);
2842             if ((timebits != 32)
2843 #ifdef AFS_64BIT_ENV
2844                 && (timebits != 64)
2845 #endif
2846                 ) 
2847                 err++;
2848         } else if (!strcmp(*argv, "-volume")) {
2849             if (argc < 1) {
2850                 err++;
2851                 break;
2852             }
2853             argc--;
2854             vol = atoi(*++argv);
2855         } else
2856             err++;
2857         argv++;
2858     }
2859     if (err || argc != 1) {
2860         fprintf(stderr,
2861                 "Usage: cbd [-host cbid] [-fid volume vnode] [-stats] [-all] [-timebits 32"
2862 #ifdef AFS_64BIT_ENV
2863                 "|64"
2864 #endif
2865                 "] callbackdumpfile\n");
2866         fprintf(stderr,
2867                 "[cbid is shown for each host in the hosts.dump file]\n");
2868         exit(1);
2869     }
2870     now = ReadDump(*argv, timebits);
2871     if (stats || noptions == 0) {
2872         time_t uxtfirst = UXtime(tfirst), tnow = now;
2873         printf("The time of the dump was %u %s", (unsigned int) now, ctime(&tnow));
2874         printf("The last time cleanup ran was %u %s", (unsigned int) uxtfirst,
2875                ctime(&uxtfirst));
2876         PrintCallBackStats();
2877     }
2878     if (all || vol) {
2879         int hash;
2880         afs_uint32 *feip;
2881         struct CallBack *cb;
2882         struct FileEntry *fe;
2883
2884         for (hash = 0; hash < FEHASH_SIZE; hash++) {
2885             for (feip = &HashTable[hash]; (fe = itofe(*feip));) {
2886                 if (!vol || (fe->volid == vol)) {
2887                     register struct CallBack *cbnext;
2888                     for (cb = itocb(fe->firstcb); cb; cb = cbnext) {
2889                         PrintCB(cb, now);
2890                         cbnext = itocb(cb->cnext);
2891                     }
2892                     *feip = fe->fnext;
2893                 } else {
2894                     feip = &fe->fnext;
2895                 }
2896             }
2897         }
2898     }
2899     if (cbi) {
2900         afs_uint32 cfirst = cbi;
2901         do {
2902             cb = itocb(cbi);
2903             PrintCB(cb, now);
2904             cbi = cb->hnext;
2905         } while (cbi != cfirst);
2906     }
2907     if (fid.Volume) {
2908         fe = FindFE(&fid);
2909         if (!fe) {
2910             printf("No callback entries for %u.%u\n", fid.Volume, fid.Vnode);
2911             exit(1);
2912         }
2913         cb = itocb(fe->firstcb);
2914         while (cb) {
2915             PrintCB(cb, now);
2916             cb = itocb(cb->cnext);
2917         }
2918     }
2919     if (raw) {
2920         afs_int32 *p, i;
2921         for (i = 1; i < cbstuff.nblks; i++) {
2922             p = (afs_int32 *) & FE[i];
2923             printf("%d:%12x%12x%12x%12x\n", i, p[0], p[1], p[2], p[3]);
2924         }
2925     }
2926     exit(0);
2927 }
2928
2929 void
2930 PrintCB(register struct CallBack *cb, afs_uint32 now)
2931 {
2932     struct FileEntry *fe = itofe(cb->fhead);
2933     time_t expires = TIndexToTime(cb->thead);
2934
2935     if (fe == NULL)
2936         return;
2937
2938     printf("vol=%u vn=%u cbs=%d hi=%d st=%d fest=%d, exp in %lu secs at %s",
2939            fe->volid, fe->vnode, fe->ncbs, cb->hhead, cb->status, fe->status,
2940            expires - now, ctime(&expires));
2941 }
2942
2943 #endif
2944
2945 #if     !defined(INTERPRET_DUMP)
2946 /*
2947 ** try breaking calbacks on afidp from host. Use multi_rx.
2948 ** return 0 on success, non-zero on failure
2949 */
2950 int
2951 MultiBreakCallBackAlternateAddress(struct host *host, struct AFSCBFids *afidp)
2952 {
2953     int retVal;
2954     H_LOCK;
2955     retVal = MultiBreakCallBackAlternateAddress_r(host, afidp);
2956     H_UNLOCK;
2957     return retVal;
2958 }
2959
2960 int
2961 MultiBreakCallBackAlternateAddress_r(struct host *host,
2962                                      struct AFSCBFids *afidp)
2963 {
2964     int i, j;
2965     struct rx_connection **conns;
2966     struct rx_connection *connSuccess = 0;
2967     struct AddrPort *interfaces;
2968     static struct rx_securityClass *sc = 0;
2969     static struct AFSCBs tc = { 0, 0 };
2970     char hoststr[16];
2971
2972     /* nothing more can be done */
2973     if (!host->interface)
2974         return 1;               /* failure */
2975
2976     /* the only address is the primary interface */
2977     if (host->interface->numberOfInterfaces <= 1)
2978         return 1;               /* failure */
2979
2980     /* initialise a security object only once */
2981     if (!sc)
2982         sc = rxnull_NewClientSecurityObject();
2983
2984     i = host->interface->numberOfInterfaces;
2985     interfaces = calloc(i, sizeof(struct AddrPort));
2986     conns = calloc(i, sizeof(struct rx_connection *));
2987     if (!interfaces || !conns) {
2988         ViceLog(0,
2989                 ("Failed malloc in MultiBreakCallBackAlternateAddress_r\n"));
2990         assert(0);
2991     }
2992
2993     /* initialize alternate rx connections */
2994     for (i = 0, j = 0; i < host->interface->numberOfInterfaces; i++) {
2995         /* this is the current primary address */
2996         if (host->host == host->interface->interface[i].addr &&
2997             host->port == host->interface->interface[i].port)
2998             continue;
2999
3000         interfaces[j] = host->interface->interface[i];
3001         conns[j] =
3002             rx_NewConnection(interfaces[j].addr, 
3003                              interfaces[j].port, 1, sc, 0);
3004         rx_SetConnDeadTime(conns[j], 2);
3005         rx_SetConnHardDeadTime(conns[j], AFS_HARDDEADTIME);
3006         j++;
3007     }
3008
3009     assert(j);                  /* at least one alternate address */
3010     ViceLog(125,
3011             ("Starting multibreakcall back on all addr for host %p (%s:%d)\n",
3012              host, afs_inet_ntoa_r(host->host, hoststr), ntohs(host->port)));
3013     H_UNLOCK;
3014     multi_Rx(conns, j) {
3015         multi_RXAFSCB_CallBack(afidp, &tc);
3016         if (!multi_error) {
3017             /* first success */
3018             H_LOCK;
3019             if (host->callback_rxcon)
3020                 rx_DestroyConnection(host->callback_rxcon);
3021             host->callback_rxcon = conns[multi_i];
3022             h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
3023             host->host = interfaces[multi_i].addr;
3024             host->port = interfaces[multi_i].port;
3025             h_AddHostToAddrHashTable_r(host->host, host->port, host);
3026             connSuccess = conns[multi_i];
3027             rx_SetConnDeadTime(host->callback_rxcon, 50);
3028             rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
3029             ViceLog(125,
3030                     ("multibreakcall success with addr %s:%d\n",
3031                      afs_inet_ntoa_r(interfaces[multi_i].addr, hoststr),
3032                      ntohs(interfaces[multi_i].port)));
3033             H_UNLOCK;
3034             multi_Abort;
3035         }
3036     }
3037     multi_End_Ignore;
3038     H_LOCK;
3039     /* Destroy all connections except the one on which we succeeded */
3040     for (i = 0; i < j; i++)
3041         if (conns[i] != connSuccess)
3042             rx_DestroyConnection(conns[i]);
3043
3044     free(interfaces);
3045     free(conns);
3046
3047     if (connSuccess)
3048         return 0;               /* success */
3049     else
3050         return 1;               /* failure */
3051 }
3052
3053
3054 /*
3055 ** try multi_RX probes to host. 
3056 ** return 0 on success, non-0 on failure
3057 */
3058 int
3059 MultiProbeAlternateAddress_r(struct host *host)
3060 {
3061     int i, j;
3062     struct rx_connection **conns;
3063     struct rx_connection *connSuccess = 0;
3064     struct AddrPort *interfaces;
3065     static struct rx_securityClass *sc = 0;
3066     char hoststr[16];
3067
3068     /* nothing more can be done */
3069     if (!host->interface)
3070         return 1;               /* failure */
3071
3072     /* the only address is the primary interface */
3073     if (host->interface->numberOfInterfaces <= 1)
3074         return 1;               /* failure */
3075
3076     /* initialise a security object only once */
3077     if (!sc)
3078         sc = rxnull_NewClientSecurityObject();
3079
3080     i = host->interface->numberOfInterfaces;
3081     interfaces = calloc(i, sizeof(struct AddrPort));
3082     conns = calloc(i, sizeof(struct rx_connection *));
3083     if (!interfaces || !conns) {
3084         ViceLog(0, ("Failed malloc in MultiProbeAlternateAddress_r\n"));
3085         assert(0);
3086     }
3087
3088     /* initialize alternate rx connections */
3089     for (i = 0, j = 0; i < host->interface->numberOfInterfaces; i++) {
3090         /* this is the current primary address */
3091         if (host->host == host->interface->interface[i].addr &&
3092             host->port == host->interface->interface[i].port)
3093             continue;
3094
3095         interfaces[j] = host->interface->interface[i];
3096         conns[j] =
3097             rx_NewConnection(interfaces[j].addr, 
3098                              interfaces[j].port, 1, sc, 0);
3099         rx_SetConnDeadTime(conns[j], 2);
3100         rx_SetConnHardDeadTime(conns[j], AFS_HARDDEADTIME);
3101         j++;
3102     }
3103
3104     assert(j);                  /* at least one alternate address */
3105     ViceLog(125,
3106             ("Starting multiprobe on all addr for host %p (%s:%d)\n",
3107              host, afs_inet_ntoa_r(host->host, hoststr),
3108              ntohs(host->port)));
3109     H_UNLOCK;
3110     multi_Rx(conns, j) {
3111         multi_RXAFSCB_ProbeUuid(&host->interface->uuid);
3112         if (!multi_error) {
3113             /* first success */
3114             H_LOCK;
3115             if (host->callback_rxcon)
3116                 rx_DestroyConnection(host->callback_rxcon);
3117             host->callback_rxcon = conns[multi_i];
3118             h_DeleteHostFromAddrHashTable_r(host->host, host->port, host);
3119             host->host = interfaces[multi_i].addr;
3120             host->port = interfaces[multi_i].port;
3121             h_AddHostToAddrHashTable_r(host->host, host->port, host);
3122             connSuccess = conns[multi_i];
3123             rx_SetConnDeadTime(host->callback_rxcon, 50);
3124             rx_SetConnHardDeadTime(host->callback_rxcon, AFS_HARDDEADTIME);
3125             ViceLog(125,
3126                     ("multiprobe success with addr %s:%d\n",
3127                      afs_inet_ntoa_r(interfaces[multi_i].addr, hoststr),
3128                      ntohs(interfaces[multi_i].port)));
3129             H_UNLOCK;
3130             multi_Abort;
3131         } else {
3132             ViceLog(125,
3133                     ("multiprobe failure with addr %s:%d\n",
3134                      afs_inet_ntoa_r(interfaces[multi_i].addr, hoststr),
3135                      ntohs(interfaces[multi_i].port)));
3136             
3137             /* This is less than desirable but its the best we can do.
3138              * The AFS Cache Manager will return either 0 for a Uuid  
3139              * match and a 1 for a non-match.   If the error is 1 we 
3140              * therefore know that our mapping of IP address to Uuid 
3141              * is wrong.   We should attempt to find the correct
3142              * Uuid and fix the host tables.
3143              */
3144             if (multi_error == 1) {
3145                 /* remove the current alternate address from this host */
3146                 H_LOCK;
3147                 removeInterfaceAddr_r(host, interfaces[multi_i].addr, interfaces[multi_i].port);
3148                 H_UNLOCK;
3149             }
3150         }
3151 #ifdef AFS_DEMAND_ATTACH_FS
3152         /* try to bail ASAP if the fileserver is shutting down */
3153         FS_STATE_RDLOCK;
3154         if (fs_state.mode == FS_MODE_SHUTDOWN) {
3155             FS_STATE_UNLOCK;
3156             multi_Abort;
3157         }
3158         FS_STATE_UNLOCK;
3159 #endif
3160     }
3161     multi_End_Ignore;
3162     H_LOCK;
3163     /* Destroy all connections except the one on which we succeeded */
3164     for (i = 0; i < j; i++)
3165         if (conns[i] != connSuccess)
3166             rx_DestroyConnection(conns[i]);
3167
3168     free(interfaces);
3169     free(conns);
3170
3171     if (connSuccess)
3172         return 0;               /* success */
3173     else
3174         return 1;               /* failure */
3175 }
3176
3177 #endif /* !defined(INTERPRET_DUMP) */