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