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