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