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