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