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