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