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