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