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