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