DAFS: avoid shutdown hang during salvage
[openafs.git] / src / vol / volume.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) 2005-2008 Sine Nomine Associates
10  */
11
12 /* 1/1/89: NB:  this stuff is all going to be replaced.  Don't take it too seriously */
13 /*
14
15         System:         VICE-TWO
16         Module:         volume.c
17         Institution:    The Information Technology Center, Carnegie-Mellon University
18
19  */
20
21 #include <afsconfig.h>
22 #include <afs/param.h>
23
24
25 #include <rx/xdr.h>
26 #include <afs/afsint.h>
27 #include <ctype.h>
28 #ifndef AFS_NT40_ENV
29 #include <sys/param.h>
30 #if !defined(AFS_SGI_ENV)
31 #ifdef  AFS_OSF_ENV
32 #include <ufs/fs.h>
33 #else /* AFS_OSF_ENV */
34 #ifdef AFS_VFSINCL_ENV
35 #define VFS
36 #ifdef  AFS_SUN5_ENV
37 #include <sys/fs/ufs_fs.h>
38 #else
39 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
40 #include <ufs/ufs/dinode.h>
41 #include <ufs/ffs/fs.h>
42 #else
43 #include <ufs/fs.h>
44 #endif
45 #endif
46 #else /* AFS_VFSINCL_ENV */
47 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
48 #include <sys/fs.h>
49 #endif
50 #endif /* AFS_VFSINCL_ENV */
51 #endif /* AFS_OSF_ENV */
52 #endif /* AFS_SGI_ENV */
53 #endif /* AFS_NT40_ENV */
54 #include <errno.h>
55 #include <sys/stat.h>
56 #include <stdio.h>
57 #ifdef AFS_NT40_ENV
58 #include <fcntl.h>
59 #else
60 #include <sys/file.h>
61 #endif
62 #include <dirent.h>
63 #ifdef  AFS_AIX_ENV
64 #include <sys/vfs.h>
65 #include <fcntl.h>
66 #else
67 #ifdef  AFS_HPUX_ENV
68 #include <fcntl.h>
69 #include <mntent.h>
70 #else
71 #if     defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
72 #ifdef  AFS_SUN5_ENV
73 #include <sys/mnttab.h>
74 #include <sys/mntent.h>
75 #else
76 #include <mntent.h>
77 #endif
78 #else
79 #ifndef AFS_NT40_ENV
80 #if defined(AFS_SGI_ENV)
81 #include <fcntl.h>
82 #include <mntent.h>
83
84 #else
85 #ifndef AFS_LINUX20_ENV
86 #include <fstab.h>              /* Need to find in libc 5, present in libc 6 */
87 #endif
88 #endif
89 #endif /* AFS_SGI_ENV */
90 #endif
91 #endif /* AFS_HPUX_ENV */
92 #endif
93 #ifndef AFS_NT40_ENV
94 #include <netdb.h>
95 #include <netinet/in.h>
96 #include <sys/wait.h>
97 #include <setjmp.h>
98 #ifndef ITIMER_REAL
99 #include <sys/time.h>
100 #endif /* ITIMER_REAL */
101 #endif /* AFS_NT40_ENV */
102 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
103 #include <string.h>
104 #else
105 #include <strings.h>
106 #endif
107
108 #include "nfs.h"
109 #include <afs/errors.h>
110 #include "lock.h"
111 #include "lwp.h"
112 #include <afs/afssyscalls.h>
113 #include "ihandle.h"
114 #include <afs/afsutil.h>
115 #ifdef AFS_NT40_ENV
116 #include <io.h>
117 #endif
118 #include "daemon_com.h"
119 #include "fssync.h"
120 #include "salvsync.h"
121 #include "vnode.h"
122 #include "volume.h"
123 #include "partition.h"
124 #include "volume_inline.h"
125 #ifdef AFS_PTHREAD_ENV
126 #include <assert.h>
127 #else /* AFS_PTHREAD_ENV */
128 #include "afs/assert.h"
129 #endif /* AFS_PTHREAD_ENV */
130 #include "vutils.h"
131 #ifndef AFS_NT40_ENV
132 #include <dir/dir.h>
133 #include <unistd.h>
134 #endif
135
136 #if !defined(offsetof)
137 #include <stddef.h>
138 #endif
139
140 #ifdef O_LARGEFILE
141 #define afs_stat        stat64
142 #define afs_fstat       fstat64
143 #define afs_open        open64
144 #else /* !O_LARGEFILE */
145 #define afs_stat        stat
146 #define afs_fstat       fstat
147 #define afs_open        open
148 #endif /* !O_LARGEFILE */
149
150 #ifdef AFS_PTHREAD_ENV
151 pthread_mutex_t vol_glock_mutex;
152 pthread_mutex_t vol_trans_mutex;
153 pthread_cond_t vol_put_volume_cond;
154 pthread_cond_t vol_sleep_cond;
155 int vol_attach_threads = 1;
156 #endif /* AFS_PTHREAD_ENV */
157
158 #ifdef AFS_DEMAND_ATTACH_FS
159 pthread_mutex_t vol_salvsync_mutex;
160 #endif /* AFS_DEMAND_ATTACH_FS */
161
162 #ifdef  AFS_OSF_ENV
163 extern void *calloc(), *realloc();
164 #endif
165
166 /*@printflike@*/ extern void Log(const char *format, ...);
167
168 /* Forward declarations */
169 static Volume *attach2(Error * ec, VolId vid, char *path,
170                        register struct VolumeHeader *header,
171                        struct DiskPartition64 *partp, Volume * vp, 
172                        int isbusy, int mode);
173 static void ReallyFreeVolume(Volume * vp);
174 #ifdef AFS_DEMAND_ATTACH_FS
175 static void FreeVolume(Volume * vp);
176 #else /* !AFS_DEMAND_ATTACH_FS */
177 #define FreeVolume(vp) ReallyFreeVolume(vp)
178 static void VScanUpdateList(void);
179 #endif /* !AFS_DEMAND_ATTACH_FS */
180 static void VInitVolumeHeaderCache(afs_uint32 howMany);
181 static int GetVolumeHeader(register Volume * vp);
182 static void ReleaseVolumeHeader(register struct volHeader *hd);
183 static void FreeVolumeHeader(register Volume * vp);
184 static void AddVolumeToHashTable(register Volume * vp, int hashid);
185 static void DeleteVolumeFromHashTable(register Volume * vp);
186 #if 0
187 static int VHold(Volume * vp);
188 #endif
189 static int VHold_r(Volume * vp);
190 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
191 static void VReleaseVolumeHandles_r(Volume * vp);
192 static void VCloseVolumeHandles_r(Volume * vp);
193 static void LoadVolumeHeader(Error * ec, Volume * vp);
194 static int VCheckOffline(register Volume * vp);
195 static int VCheckDetach(register Volume * vp);
196 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
197 #ifdef AFS_DEMAND_ATTACH_FS
198 static int VolumeExternalName_r(VolumeId volumeId, char * name, size_t len);
199 #endif
200
201 int LogLevel;                   /* Vice loglevel--not defined as extern so that it will be
202                                  * defined when not linked with vice, XXXX */
203 ProgramType programType;        /* The type of program using the package */
204
205 /* extended volume package statistics */
206 VolPkgStats VStats;
207
208 #ifdef VOL_LOCK_DEBUG
209 pthread_t vol_glock_holder = 0;
210 #endif
211
212
213 #define VOLUME_BITMAP_GROWSIZE  16      /* bytes, => 128vnodes */
214                                         /* Must be a multiple of 4 (1 word) !! */
215
216 /* this parameter needs to be tunable at runtime.
217  * 128 was really inadequate for largish servers -- at 16384 volumes this
218  * puts average chain length at 128, thus an average 65 deref's to find a volptr.
219  * talk about bad spatial locality...
220  *
221  * an AVL or splay tree might work a lot better, but we'll just increase
222  * the default hash table size for now
223  */
224 #define DEFAULT_VOLUME_HASH_SIZE 256   /* Must be a power of 2!! */
225 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
226 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
227
228 /*
229  * turn volume hash chains into partially ordered lists.
230  * when the threshold is exceeded between two adjacent elements,
231  * perform a chain rebalancing operation.
232  *
233  * keep the threshold high in order to keep cache line invalidates
234  * low "enough" on SMPs
235  */
236 #define VOLUME_HASH_REORDER_THRESHOLD 200
237
238 /*
239  * when possible, don't just reorder single elements, but reorder
240  * entire chains of elements at once.  a chain of elements that
241  * exceed the element previous to the pivot by at least CHAIN_THRESH 
242  * accesses are moved in front of the chain whose elements have at
243  * least CHAIN_THRESH less accesses than the pivot element
244  */
245 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
246
247 #include "rx/rx_queue.h"
248
249
250 VolumeHashTable_t VolumeHashTable = {
251     DEFAULT_VOLUME_HASH_SIZE,
252     DEFAULT_VOLUME_HASH_MASK,
253     NULL
254 };
255
256
257 static void VInitVolumeHash(void);
258
259
260 #ifndef AFS_HAVE_FFS
261 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
262 ffs(x)
263 {
264     afs_int32 ffs_i;
265     afs_int32 ffs_tmp = x;
266     if (ffs_tmp == 0)
267         return (-1);
268     else
269         for (ffs_i = 1;; ffs_i++) {
270             if (ffs_tmp & 1)
271                 return (ffs_i);
272             else
273                 ffs_tmp >>= 1;
274         }
275 }
276 #endif /* !AFS_HAVE_FFS */
277
278 #ifdef AFS_PTHREAD_ENV
279 typedef struct diskpartition_queue_t {
280     struct rx_queue queue;
281     struct DiskPartition64 * diskP;
282 } diskpartition_queue_t;
283 typedef struct vinitvolumepackage_thread_t {
284     struct rx_queue queue;
285     pthread_cond_t thread_done_cv;
286     int n_threads_complete;
287 } vinitvolumepackage_thread_t;
288 static void * VInitVolumePackageThread(void * args);
289 #endif /* AFS_PTHREAD_ENV */
290
291 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP, 
292                                      int * nAttached, int * nUnattached);
293
294
295 #ifdef AFS_DEMAND_ATTACH_FS
296 /* demand attach fileserver extensions */
297
298 /* XXX
299  * in the future we will support serialization of VLRU state into the fs_state
300  * disk dumps
301  *
302  * these structures are the beginning of that effort
303  */
304 struct VLRU_DiskHeader {
305     struct versionStamp stamp;            /* magic and structure version number */
306     afs_uint32 mtime;                     /* time of dump to disk */
307     afs_uint32 num_records;               /* number of VLRU_DiskEntry records */
308 };
309
310 struct VLRU_DiskEntry {
311     afs_uint32 vid;                       /* volume ID */
312     afs_uint32 idx;                       /* generation */
313     afs_uint32 last_get;                  /* timestamp of last get */
314 };
315
316 struct VLRU_StartupQueue {
317     struct VLRU_DiskEntry * entry;
318     int num_entries;
319     int next_idx;
320 };
321
322 typedef struct vshutdown_thread_t {
323     struct rx_queue q;
324     pthread_mutex_t lock;
325     pthread_cond_t cv;
326     pthread_cond_t master_cv;
327     int n_threads;
328     int n_threads_complete;
329     int vol_remaining;
330     int schedule_version;
331     int pass;
332     byte n_parts;
333     byte n_parts_done_pass;
334     byte part_thread_target[VOLMAXPARTS+1];
335     byte part_done_pass[VOLMAXPARTS+1];
336     struct rx_queue * part_pass_head[VOLMAXPARTS+1];
337     int stats[4][VOLMAXPARTS+1];
338 } vshutdown_thread_t;
339 static void * VShutdownThread(void * args);
340
341
342 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
343 static int VCheckFree(Volume * vp);
344
345 /* VByP List */
346 static void AddVolumeToVByPList_r(Volume * vp);
347 static void DeleteVolumeFromVByPList_r(Volume * vp);
348 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
349 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
350 static void VVByPListWait_r(struct DiskPartition64 * dp);
351
352 /* online salvager */
353 static int VCheckSalvage(register Volume * vp);
354 static int VUpdateSalvagePriority_r(Volume * vp);
355 static int VScheduleSalvage_r(Volume * vp);
356
357 /* Volume hash table */
358 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
359 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
360 static void VHashEndExclusive_r(VolumeHashChainHead * head);
361 static void VHashWait_r(VolumeHashChainHead * head);
362
363 /* shutdown */
364 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
365 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
366                                 struct rx_queue ** idx);
367 static void ShutdownController(vshutdown_thread_t * params);
368 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
369
370 /* VLRU */
371 static void VLRU_ComputeConstants(void);
372 static void VInitVLRU(void);
373 static void VLRU_Init_Node_r(volatile Volume * vp);
374 static void VLRU_Add_r(volatile Volume * vp);
375 static void VLRU_Delete_r(volatile Volume * vp);
376 static void VLRU_UpdateAccess_r(volatile Volume * vp);
377 static void * VLRU_ScannerThread(void * args);
378 static void VLRU_Scan_r(int idx);
379 static void VLRU_Promote_r(int idx);
380 static void VLRU_Demote_r(int idx);
381 static void VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append);
382
383 /* soft detach */
384 static int VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh);
385 static int VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh);
386 static int VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh);
387
388
389 pthread_key_t VThread_key;
390 VThreadOptions_t VThread_defaults = {
391     0                           /**< allow salvsync */
392 };
393 #endif /* AFS_DEMAND_ATTACH_FS */
394
395
396 struct Lock vol_listLock;       /* Lock obtained when listing volumes:  
397                                  * prevents a volume from being missed 
398                                  * if the volume is attached during a 
399                                  * list volumes */
400
401
402 static int TimeZoneCorrection;  /* Number of seconds west of GMT */
403
404 /* Common message used when the volume goes off line */
405 char *VSalvageMessage =
406     "Files in this volume are currently unavailable; call operations";
407
408 int VInit;                      /* 0 - uninitialized,
409                                  * 1 - initialized but not all volumes have been attached,
410                                  * 2 - initialized and all volumes have been attached,
411                                  * 3 - initialized, all volumes have been attached, and
412                                  * VConnectFS() has completed. */
413
414
415 bit32 VolumeCacheCheck;         /* Incremented everytime a volume goes on line--
416                                  * used to stamp volume headers and in-core
417                                  * vnodes.  When the volume goes on-line the
418                                  * vnode will be invalidated
419                                  * access only with VOL_LOCK held */
420
421
422
423
424 /***************************************************/
425 /* Startup routines                                */
426 /***************************************************/
427
428 int
429 VInitVolumePackage(ProgramType pt, afs_uint32 nLargeVnodes, afs_uint32 nSmallVnodes,
430                    int connect, afs_uint32 volcache)
431 {
432     int errors = 0;             /* Number of errors while finding vice partitions. */
433     struct timeval tv;
434     struct timezone tz;
435
436     programType = pt;
437
438     memset(&VStats, 0, sizeof(VStats));
439     VStats.hdr_cache_size = 200;
440
441     VInitPartitionPackage();
442     VInitVolumeHash();
443 #ifdef AFS_DEMAND_ATTACH_FS
444     if (programType == fileServer) {
445         VInitVLRU();
446     } else {
447         VLRU_SetOptions(VLRU_SET_ENABLED, 0);
448     }
449     assert(pthread_key_create(&VThread_key, NULL) == 0);
450 #endif
451
452 #ifdef AFS_PTHREAD_ENV
453     assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
454     assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
455     assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
456     assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
457 #else /* AFS_PTHREAD_ENV */
458     IOMGR_Initialize();
459 #endif /* AFS_PTHREAD_ENV */
460     Lock_Init(&vol_listLock);
461
462     srandom(time(0));           /* For VGetVolumeInfo */
463     gettimeofday(&tv, &tz);
464     TimeZoneCorrection = tz.tz_minuteswest * 60;
465
466 #ifdef AFS_DEMAND_ATTACH_FS
467     assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
468 #endif /* AFS_DEMAND_ATTACH_FS */
469
470     /* Ok, we have done enough initialization that fileserver can 
471      * start accepting calls, even though the volumes may not be 
472      * available just yet.
473      */
474     VInit = 1;
475
476 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
477     if (programType == salvageServer) {
478         SALVSYNC_salvInit();
479     }
480 #endif /* AFS_DEMAND_ATTACH_FS */
481 #ifdef FSSYNC_BUILD_SERVER
482     if (programType == fileServer) {
483         FSYNC_fsInit();
484     }
485 #endif
486 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
487     if (programType == fileServer) {
488         /* establish a connection to the salvager at this point */
489         assert(VConnectSALV() != 0);
490     }
491 #endif /* AFS_DEMAND_ATTACH_FS */
492
493     if (volcache > VStats.hdr_cache_size)
494         VStats.hdr_cache_size = volcache;
495     VInitVolumeHeaderCache(VStats.hdr_cache_size);
496
497     VInitVnodes(vLarge, nLargeVnodes);
498     VInitVnodes(vSmall, nSmallVnodes);
499
500
501     errors = VAttachPartitions();
502     if (errors)
503         return -1;
504
505     if (programType == fileServer) {
506         struct DiskPartition64 *diskP;
507 #ifdef AFS_PTHREAD_ENV
508         struct vinitvolumepackage_thread_t params;
509         struct diskpartition_queue_t * dpq;
510         int i, threads, parts;
511         pthread_t tid;
512         pthread_attr_t attrs;
513
514         assert(pthread_cond_init(&params.thread_done_cv,NULL) == 0);
515         queue_Init(&params);
516         params.n_threads_complete = 0;
517
518         /* create partition work queue */
519         for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
520             dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
521             assert(dpq != NULL);
522             dpq->diskP = diskP;
523             queue_Append(&params,dpq);
524         }
525
526         threads = MIN(parts, vol_attach_threads);
527
528         if (threads > 1) {
529             /* spawn off a bunch of initialization threads */
530             assert(pthread_attr_init(&attrs) == 0);
531             assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
532
533             Log("VInitVolumePackage: beginning parallel fileserver startup\n");
534 #ifdef AFS_DEMAND_ATTACH_FS
535             Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
536                 threads, parts);
537 #else /* AFS_DEMAND_ATTACH_FS */
538             Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
539                 threads, parts);
540 #endif /* AFS_DEMAND_ATTACH_FS */
541
542             VOL_LOCK;
543             for (i=0; i < threads; i++) {
544                 assert(pthread_create
545                        (&tid, &attrs, &VInitVolumePackageThread,
546                         &params) == 0);
547             }
548
549             while(params.n_threads_complete < threads) {
550                 VOL_CV_WAIT(&params.thread_done_cv);
551             }
552             VOL_UNLOCK;
553
554             assert(pthread_attr_destroy(&attrs) == 0);
555         } else {
556             /* if we're only going to run one init thread, don't bother creating
557              * another LWP */
558             Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
559 #ifdef AFS_DEMAND_ATTACH_FS
560             Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
561                 parts);
562 #else /* AFS_DEMAND_ATTACH_FS */
563             Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
564                 parts);
565 #endif /* AFS_DEMAND_ATTACH_FS */
566
567             VInitVolumePackageThread(&params);
568         }
569
570         assert(pthread_cond_destroy(&params.thread_done_cv) == 0);
571
572 #else /* AFS_PTHREAD_ENV */
573
574         /* Attach all the volumes in this partition */
575         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
576             int nAttached = 0, nUnattached = 0;
577             assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
578         }
579 #endif /* AFS_PTHREAD_ENV */
580     }
581
582     VInit = 2;                  /* Initialized, and all volumes have been attached */
583 #ifdef FSSYNC_BUILD_CLIENT
584     if (programType == volumeUtility && connect) {
585         if (!VConnectFS()) {
586             Log("Unable to connect to file server; will retry at need\n");
587             /*exit(1);*/
588         }
589     }
590 #ifdef AFS_DEMAND_ATTACH_FS
591     else if (programType == salvageServer) {
592         if (!VConnectFS()) {
593             Log("Unable to connect to file server; aborted\n");
594             exit(1);
595         }
596     }
597 #endif /* AFS_DEMAND_ATTACH_FS */
598 #endif /* FSSYNC_BUILD_CLIENT */
599     return 0;
600 }
601
602 #ifdef AFS_PTHREAD_ENV
603 static void *
604 VInitVolumePackageThread(void * args) {
605
606     struct DiskPartition64 *diskP;
607     struct vinitvolumepackage_thread_t * params;
608     struct diskpartition_queue_t * dpq;
609
610     params = (vinitvolumepackage_thread_t *) args;
611
612
613     VOL_LOCK;
614     /* Attach all the volumes in this partition */
615     while (queue_IsNotEmpty(params)) {
616         int nAttached = 0, nUnattached = 0;
617
618         dpq = queue_First(params,diskpartition_queue_t);
619         queue_Remove(dpq);
620         VOL_UNLOCK;
621         diskP = dpq->diskP;
622         free(dpq);
623
624         assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
625
626         VOL_LOCK;
627     }
628
629     params->n_threads_complete++;
630     pthread_cond_signal(&params->thread_done_cv);
631     VOL_UNLOCK;
632     return NULL;
633 }
634 #endif /* AFS_PTHREAD_ENV */
635
636 /*
637  * attach all volumes on a given disk partition
638  */
639 static int
640 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
641 {
642   DIR * dirp;
643   struct dirent * dp;
644   int ret = 0;
645
646   Log("Partition %s: attaching volumes\n", diskP->name);
647   dirp = opendir(VPartitionPath(diskP));
648   if (!dirp) {
649     Log("opendir on Partition %s failed!\n", diskP->name);
650     return 1;
651   }
652
653   while ((dp = readdir(dirp))) {
654     char *p;
655     p = strrchr(dp->d_name, '.');
656     if (p != NULL && strcmp(p, VHDREXT) == 0) {
657       Error error;
658       Volume *vp;
659 #ifdef AFS_DEMAND_ATTACH_FS
660       vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name);
661 #else /* AFS_DEMAND_ATTACH_FS */
662       vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
663                                V_VOLUPD);
664 #endif /* AFS_DEMAND_ATTACH_FS */
665       (*(vp ? nAttached : nUnattached))++;
666       if (error == VOFFLINE)
667         Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
668       else if (LogLevel >= 5) {
669         Log("Partition %s: attached volume %d (%s)\n",
670             diskP->name, VolumeNumber(dp->d_name),
671             dp->d_name);
672       }
673 #if !defined(AFS_DEMAND_ATTACH_FS)
674       if (vp) {
675         VPutVolume(vp);
676       }
677 #endif /* AFS_DEMAND_ATTACH_FS */
678     }
679   }
680
681   Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
682   closedir(dirp);
683   return ret;
684 }
685
686
687 /***************************************************/
688 /* Shutdown routines                               */
689 /***************************************************/
690
691 /*
692  * demand attach fs
693  * highly multithreaded volume package shutdown
694  *
695  * with the demand attach fileserver extensions,
696  * VShutdown has been modified to be multithreaded.
697  * In order to achieve optimal use of many threads,
698  * the shutdown code involves one control thread and
699  * n shutdown worker threads.  The control thread
700  * periodically examines the number of volumes available
701  * for shutdown on each partition, and produces a worker
702  * thread allocation schedule.  The idea is to eliminate
703  * redundant scheduling computation on the workers by
704  * having a single master scheduler.
705  *
706  * The scheduler's objectives are:
707  * (1) fairness
708  *   each partition with volumes remaining gets allocated
709  *   at least 1 thread (assuming sufficient threads)
710  * (2) performance
711  *   threads are allocated proportional to the number of
712  *   volumes remaining to be offlined.  This ensures that
713  *   the OS I/O scheduler has many requests to elevator
714  *   seek on partitions that will (presumably) take the
715  *   longest amount of time (from now) to finish shutdown
716  * (3) keep threads busy
717  *   when there are extra threads, they are assigned to
718  *   partitions using a simple round-robin algorithm
719  *
720  * In the future, we may wish to add the ability to adapt
721  * to the relative performance patterns of each disk
722  * partition.
723  *
724  *
725  * demand attach fs
726  * multi-step shutdown process
727  *
728  * demand attach shutdown is a four-step process. Each
729  * shutdown "pass" shuts down increasingly more difficult
730  * volumes.  The main purpose is to achieve better cache
731  * utilization during shutdown.
732  *
733  * pass 0
734  *   shutdown volumes in the unattached, pre-attached
735  *   and error states
736  * pass 1
737  *   shutdown attached volumes with cached volume headers
738  * pass 2
739  *   shutdown all volumes in non-exclusive states
740  * pass 3
741  *   shutdown all remaining volumes
742  */
743
744 void
745 VShutdown_r(void)
746 {
747     int i;
748     register Volume *vp, *np;
749     register afs_int32 code;
750 #ifdef AFS_DEMAND_ATTACH_FS
751     struct DiskPartition64 * diskP;
752     struct diskpartition_queue_t * dpq;
753     vshutdown_thread_t params;
754     pthread_t tid;
755     pthread_attr_t attrs;
756
757     memset(&params, 0, sizeof(vshutdown_thread_t));
758
759     for (params.n_parts=0, diskP = DiskPartitionList;
760          diskP; diskP = diskP->next, params.n_parts++);
761
762     Log("VShutdown:  shutting down on-line volumes on %d partition%s...\n", 
763         params.n_parts, params.n_parts > 1 ? "s" : "");
764
765     if (vol_attach_threads > 1) {
766         /* prepare for parallel shutdown */
767         params.n_threads = vol_attach_threads;
768         assert(pthread_mutex_init(&params.lock, NULL) == 0);
769         assert(pthread_cond_init(&params.cv, NULL) == 0);
770         assert(pthread_cond_init(&params.master_cv, NULL) == 0);
771         assert(pthread_attr_init(&attrs) == 0);
772         assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
773         queue_Init(&params);
774
775         /* setup the basic partition information structures for
776          * parallel shutdown */
777         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
778             /* XXX debug */
779             struct rx_queue * qp, * nqp;
780             Volume * vp;
781             int count = 0;
782
783             VVByPListWait_r(diskP);
784             VVByPListBeginExclusive_r(diskP);
785
786             /* XXX debug */
787             for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
788                 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
789                 if (vp->header)
790                     count++;
791             }
792             Log("VShutdown: partition %s has %d volumes with attached headers\n",
793                 VPartitionPath(diskP), count);
794                 
795
796             /* build up the pass 0 shutdown work queue */
797             dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
798             assert(dpq != NULL);
799             dpq->diskP = diskP;
800             queue_Prepend(&params, dpq);
801
802             params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
803         }
804
805         Log("VShutdown:  beginning parallel fileserver shutdown\n");
806         Log("VShutdown:  using %d threads to offline volumes on %d partition%s\n",
807             vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
808
809         /* do pass 0 shutdown */
810         assert(pthread_mutex_lock(&params.lock) == 0);
811         for (i=0; i < params.n_threads; i++) {
812             assert(pthread_create
813                    (&tid, &attrs, &VShutdownThread,
814                     &params) == 0);
815         }
816         
817         /* wait for all the pass 0 shutdowns to complete */
818         while (params.n_threads_complete < params.n_threads) {
819             assert(pthread_cond_wait(&params.master_cv, &params.lock) == 0);
820         }
821         params.n_threads_complete = 0;
822         params.pass = 1;
823         assert(pthread_cond_broadcast(&params.cv) == 0);
824         assert(pthread_mutex_unlock(&params.lock) == 0);
825
826         Log("VShutdown:  pass 0 completed using the 1 thread per partition algorithm\n");
827         Log("VShutdown:  starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
828
829         /* run the parallel shutdown scheduler. it will drop the glock internally */
830         ShutdownController(&params);
831         
832         /* wait for all the workers to finish pass 3 and terminate */
833         while (params.pass < 4) {
834             VOL_CV_WAIT(&params.cv);
835         }
836         
837         assert(pthread_attr_destroy(&attrs) == 0);
838         assert(pthread_cond_destroy(&params.cv) == 0);
839         assert(pthread_cond_destroy(&params.master_cv) == 0);
840         assert(pthread_mutex_destroy(&params.lock) == 0);
841
842         /* drop the VByPList exclusive reservations */
843         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
844             VVByPListEndExclusive_r(diskP);
845             Log("VShutdown:  %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
846                 VPartitionPath(diskP),
847                 params.stats[0][diskP->index],
848                 params.stats[1][diskP->index],
849                 params.stats[2][diskP->index],
850                 params.stats[3][diskP->index]);
851         }
852
853         Log("VShutdown:  shutdown finished using %d threads\n", params.n_threads);
854     } else {
855         /* if we're only going to run one shutdown thread, don't bother creating
856          * another LWP */
857         Log("VShutdown:  beginning single-threaded fileserver shutdown\n");
858
859         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
860             VShutdownByPartition_r(diskP);
861         }
862     }
863
864     Log("VShutdown:  complete.\n");
865 #else /* AFS_DEMAND_ATTACH_FS */
866     Log("VShutdown:  shutting down on-line volumes...\n");
867     for (i = 0; i < VolumeHashTable.Size; i++) {
868         /* try to hold first volume in the hash table */
869         for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
870             code = VHold_r(vp);
871             if (code == 0) {
872                 if (LogLevel >= 5)
873                     Log("VShutdown:  Attempting to take volume %u offline.\n",
874                         vp->hashid);
875                 
876                 /* next, take the volume offline (drops reference count) */
877                 VOffline_r(vp, "File server was shut down");
878             }
879         }
880     }
881     Log("VShutdown:  complete.\n");
882 #endif /* AFS_DEMAND_ATTACH_FS */
883 }
884
885 void
886 VShutdown(void)
887 {
888     VOL_LOCK;
889     VShutdown_r();
890     VOL_UNLOCK;
891 }
892
893 #ifdef AFS_DEMAND_ATTACH_FS
894 /*
895  * demand attach fs
896  * shutdown control thread
897  */
898 static void
899 ShutdownController(vshutdown_thread_t * params)
900 {
901     /* XXX debug */
902     struct DiskPartition64 * diskP;
903     Device id;
904     vshutdown_thread_t shadow;
905
906     ShutdownCreateSchedule(params);
907
908     while ((params->pass < 4) &&
909            (params->n_threads_complete < params->n_threads)) {
910         /* recompute schedule once per second */
911
912         memcpy(&shadow, params, sizeof(vshutdown_thread_t));
913
914         VOL_UNLOCK;
915         /* XXX debug */
916         Log("ShutdownController:  schedule version=%d, vol_remaining=%d, pass=%d\n",
917             shadow.schedule_version, shadow.vol_remaining, shadow.pass);
918         Log("ShutdownController:  n_threads_complete=%d, n_parts_done_pass=%d\n",
919             shadow.n_threads_complete, shadow.n_parts_done_pass);
920         for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
921             id = diskP->index;
922             Log("ShutdownController:  part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
923                 id, 
924                 diskP->vol_list.len,
925                 shadow.part_thread_target[id], 
926                 shadow.part_done_pass[id], 
927                 shadow.part_pass_head[id]);
928         }
929
930         sleep(1);
931         VOL_LOCK;
932
933         ShutdownCreateSchedule(params);
934     }
935 }
936
937 /* create the shutdown thread work schedule.
938  * this scheduler tries to implement fairness
939  * by allocating at least 1 thread to each 
940  * partition with volumes to be shutdown,
941  * and then it attempts to allocate remaining
942  * threads based upon the amount of work left
943  */
944 static void
945 ShutdownCreateSchedule(vshutdown_thread_t * params)
946 {
947     struct DiskPartition64 * diskP;
948     int sum, thr_workload, thr_left;
949     int part_residue[VOLMAXPARTS+1];
950     Device id;
951
952     /* compute the total number of outstanding volumes */
953     sum = 0;
954     for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
955         sum += diskP->vol_list.len;
956     }
957     
958     params->schedule_version++;
959     params->vol_remaining = sum;
960
961     if (!sum)
962         return;
963
964     /* compute average per-thread workload */
965     thr_workload = sum / params->n_threads;
966     if (sum % params->n_threads)
967         thr_workload++;
968
969     thr_left = params->n_threads;
970     memset(&part_residue, 0, sizeof(part_residue));
971
972     /* for fairness, give every partition with volumes remaining
973      * at least one thread */
974     for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
975         id = diskP->index;
976         if (diskP->vol_list.len) {
977             params->part_thread_target[id] = 1;
978             thr_left--;
979         } else {
980             params->part_thread_target[id] = 0;
981         }
982     }
983
984     if (thr_left && thr_workload) {
985         /* compute length-weighted workloads */
986         int delta;
987
988         for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
989             id = diskP->index;
990             delta = (diskP->vol_list.len / thr_workload) -
991                 params->part_thread_target[id];
992             if (delta < 0) {
993                 continue;
994             }
995             if (delta < thr_left) {
996                 params->part_thread_target[id] += delta;
997                 thr_left -= delta;
998             } else {
999                 params->part_thread_target[id] += thr_left;
1000                 thr_left = 0;
1001                 break;
1002             }
1003         }
1004     }
1005
1006     if (thr_left) {
1007         /* try to assign any leftover threads to partitions that
1008          * had volume lengths closer to needing thread_target+1 */
1009         int max_residue, max_id;
1010
1011         /* compute the residues */
1012         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1013             id = diskP->index;
1014             part_residue[id] = diskP->vol_list.len - 
1015                 (params->part_thread_target[id] * thr_workload);
1016         }
1017
1018         /* now try to allocate remaining threads to partitions with the
1019          * highest residues */
1020         while (thr_left) {
1021             max_residue = 0;
1022             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1023                 id = diskP->index;
1024                 if (part_residue[id] > max_residue) {
1025                     max_residue = part_residue[id];
1026                     max_id = id;
1027                 }
1028             }
1029
1030             if (!max_residue) {
1031                 break;
1032             }
1033
1034             params->part_thread_target[max_id]++;
1035             thr_left--;
1036             part_residue[max_id] = 0;
1037         }
1038     }
1039
1040     if (thr_left) {
1041         /* punt and give any remaining threads equally to each partition */
1042         int alloc;
1043         if (thr_left >= params->n_parts) {
1044             alloc = thr_left / params->n_parts;
1045             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1046                 id = diskP->index;
1047                 params->part_thread_target[id] += alloc;
1048                 thr_left -= alloc;
1049             }
1050         }
1051
1052         /* finish off the last of the threads */
1053         for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1054             id = diskP->index;
1055             params->part_thread_target[id]++;
1056             thr_left--;
1057         }
1058     }
1059 }
1060
1061 /* worker thread for parallel shutdown */
1062 static void *
1063 VShutdownThread(void * args)
1064 {
1065     struct rx_queue *qp;
1066     Volume * vp;
1067     vshutdown_thread_t * params;
1068     int part, code, found, pass, schedule_version_save, count;
1069     struct DiskPartition64 *diskP;
1070     struct diskpartition_queue_t * dpq;
1071     Device id;
1072
1073     params = (vshutdown_thread_t *) args;
1074
1075     /* acquire the shutdown pass 0 lock */
1076     assert(pthread_mutex_lock(&params->lock) == 0);
1077
1078     /* if there's still pass 0 work to be done,
1079      * get a work entry, and do a pass 0 shutdown */
1080     if (queue_IsNotEmpty(params)) {
1081         dpq = queue_First(params, diskpartition_queue_t);
1082         queue_Remove(dpq);
1083         assert(pthread_mutex_unlock(&params->lock) == 0);
1084         diskP = dpq->diskP;
1085         free(dpq);
1086         id = diskP->index;
1087
1088         count = 0;
1089         while (ShutdownVolumeWalk_r(diskP, 0, &params->part_pass_head[id]))
1090             count++;
1091         params->stats[0][diskP->index] = count;
1092         assert(pthread_mutex_lock(&params->lock) == 0);
1093     }
1094
1095     params->n_threads_complete++;
1096     if (params->n_threads_complete == params->n_threads) {
1097       /* notify control thread that all workers have completed pass 0 */
1098       assert(pthread_cond_signal(&params->master_cv) == 0);
1099     }
1100     while (params->pass == 0) {
1101       assert(pthread_cond_wait(&params->cv, &params->lock) == 0);
1102     }
1103
1104     /* switch locks */
1105     assert(pthread_mutex_unlock(&params->lock) == 0);
1106     VOL_LOCK;
1107
1108     pass = params->pass;
1109     assert(pass > 0);
1110
1111     /* now escalate through the more complicated shutdowns */
1112     while (pass <= 3) {
1113         schedule_version_save = params->schedule_version;
1114         found = 0;
1115         /* find a disk partition to work on */
1116         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1117             id = diskP->index;
1118             if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1119                 params->part_thread_target[id]--;
1120                 found = 1;
1121                 break;
1122             }
1123         }
1124         
1125         if (!found) {
1126             /* hmm. for some reason the controller thread couldn't find anything for 
1127              * us to do. let's see if there's anything we can do */
1128             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1129                 id = diskP->index;
1130                 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1131                     found = 1;
1132                     break;
1133                 } else if (!params->part_done_pass[id]) {
1134                     params->part_done_pass[id] = 1;
1135                     params->n_parts_done_pass++;
1136                     if (pass == 3) {
1137                         Log("VShutdown:  done shutting down volumes on partition %s.\n",
1138                             VPartitionPath(diskP));
1139                     }
1140                 }
1141             }
1142         }
1143         
1144         /* do work on this partition until either the controller
1145          * creates a new schedule, or we run out of things to do
1146          * on this partition */
1147         if (found) {
1148             count = 0;
1149             while (!params->part_done_pass[id] &&
1150                    (schedule_version_save == params->schedule_version)) {
1151                 /* ShutdownVolumeWalk_r will drop the glock internally */
1152                 if (!ShutdownVolumeWalk_r(diskP, pass, &params->part_pass_head[id])) {
1153                     if (!params->part_done_pass[id]) {
1154                         params->part_done_pass[id] = 1;
1155                         params->n_parts_done_pass++;
1156                         if (pass == 3) {
1157                             Log("VShutdown:  done shutting down volumes on partition %s.\n",
1158                                 VPartitionPath(diskP));
1159                         }
1160                     }
1161                     break;
1162                 }
1163                 count++;
1164             }
1165
1166             params->stats[pass][id] += count;
1167         } else {
1168             /* ok, everyone is done this pass, proceed */
1169
1170             /* barrier lock */
1171             params->n_threads_complete++;
1172             while (params->pass == pass) {
1173                 if (params->n_threads_complete == params->n_threads) {
1174                     /* we are the last thread to complete, so we will
1175                      * reinitialize worker pool state for the next pass */
1176                     params->n_threads_complete = 0;
1177                     params->n_parts_done_pass = 0;
1178                     params->pass++;
1179                     for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1180                         id = diskP->index;
1181                         params->part_done_pass[id] = 0;
1182                         params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1183                     }
1184
1185                     /* compute a new thread schedule before releasing all the workers */
1186                     ShutdownCreateSchedule(params);
1187
1188                     /* wake up all the workers */
1189                     assert(pthread_cond_broadcast(&params->cv) == 0);
1190
1191                     VOL_UNLOCK;
1192                     Log("VShutdown:  pass %d completed using %d threads on %d partitions\n",
1193                         pass, params->n_threads, params->n_parts);
1194                     VOL_LOCK;
1195                 } else {
1196                     VOL_CV_WAIT(&params->cv);
1197                 }
1198             }
1199             pass = params->pass;
1200         }
1201         
1202         /* for fairness */
1203         VOL_UNLOCK;
1204         pthread_yield();
1205         VOL_LOCK;
1206     }
1207
1208     VOL_UNLOCK;
1209
1210     return NULL;
1211 }
1212
1213 /* shut down all volumes on a given disk partition 
1214  *
1215  * note that this function will not allow mp-fast
1216  * shutdown of a partition */
1217 int
1218 VShutdownByPartition_r(struct DiskPartition64 * dp)
1219 {
1220     int pass, retVal;
1221     int pass_stats[4];
1222     int total;
1223
1224     /* wait for other exclusive ops to finish */
1225     VVByPListWait_r(dp);
1226
1227     /* begin exclusive access */
1228     VVByPListBeginExclusive_r(dp);
1229
1230     /* pick the low-hanging fruit first,
1231      * then do the complicated ones last 
1232      * (has the advantage of keeping
1233      *  in-use volumes up until the bitter end) */
1234     for (pass = 0, total=0; pass < 4; pass++) {
1235         pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1236         total += pass_stats[pass];
1237     }
1238
1239     /* end exclusive access */
1240     VVByPListEndExclusive_r(dp);
1241
1242     Log("VShutdownByPartition:  shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1243         total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1244
1245     return retVal;
1246 }
1247
1248 /* internal shutdown functionality
1249  *
1250  * for multi-pass shutdown:
1251  * 0 to only "shutdown" {pre,un}attached and error state volumes
1252  * 1 to also shutdown attached volumes w/ volume header loaded
1253  * 2 to also shutdown attached volumes w/o volume header loaded
1254  * 3 to also shutdown exclusive state volumes 
1255  *
1256  * caller MUST hold exclusive access on the hash chain
1257  * because we drop vol_glock_mutex internally
1258  * 
1259  * this function is reentrant for passes 1--3 
1260  * (e.g. multiple threads can cooperate to 
1261  *  shutdown a partition mp-fast)
1262  *
1263  * pass 0 is not scaleable because the volume state data is
1264  * synchronized by vol_glock mutex, and the locking overhead
1265  * is too high to drop the lock long enough to do linked list
1266  * traversal
1267  */
1268 static int
1269 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1270 {
1271     struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1272     register int i = 0;
1273
1274     while (ShutdownVolumeWalk_r(dp, pass, &q))
1275         i++;
1276
1277     return i;
1278 }
1279
1280 /* conditionally shutdown one volume on partition dp
1281  * returns 1 if a volume was shutdown in this pass,
1282  * 0 otherwise */
1283 static int
1284 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1285                      struct rx_queue ** idx)
1286 {
1287     struct rx_queue *qp, *nqp;
1288     Volume * vp;
1289
1290     qp = *idx;
1291
1292     for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1293         vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1294         
1295         switch (pass) {
1296         case 0:
1297             if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1298                 (V_attachState(vp) != VOL_STATE_ERROR) &&
1299                 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1300                 break;
1301             }
1302         case 1:
1303             if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1304                 (vp->header == NULL)) {
1305                 break;
1306             }
1307         case 2:
1308             if (VIsExclusiveState(V_attachState(vp))) {
1309                 break;
1310             }
1311         case 3:
1312             *idx = nqp;
1313             DeleteVolumeFromVByPList_r(vp);
1314             VShutdownVolume_r(vp);
1315             vp = NULL;
1316             return 1;
1317         }
1318     }
1319
1320     return 0;
1321 }
1322
1323 /*
1324  * shutdown a specific volume
1325  */
1326 /* caller MUST NOT hold a heavyweight ref on vp */
1327 int
1328 VShutdownVolume_r(Volume * vp)
1329 {
1330     int code;
1331
1332     VCreateReservation_r(vp);
1333
1334     if (LogLevel >= 5) {
1335         Log("VShutdownVolume_r:  vid=%u, device=%d, state=%hu\n",
1336             vp->hashid, vp->partition->device, V_attachState(vp));
1337     }
1338
1339     /* wait for other blocking ops to finish */
1340     VWaitExclusiveState_r(vp);
1341
1342     assert(VIsValidState(V_attachState(vp)));
1343     
1344     switch(V_attachState(vp)) {
1345     case VOL_STATE_SALVAGING:
1346         /* Leave salvaging volumes alone. Any in-progress salvages will
1347          * continue working after viced shuts down. This is intentional.
1348          */
1349
1350     case VOL_STATE_PREATTACHED:
1351     case VOL_STATE_ERROR:
1352         VChangeState_r(vp, VOL_STATE_UNATTACHED);
1353     case VOL_STATE_UNATTACHED:
1354         break;
1355     case VOL_STATE_GOING_OFFLINE:
1356     case VOL_STATE_SHUTTING_DOWN:
1357     case VOL_STATE_ATTACHED:
1358         code = VHold_r(vp);
1359         if (!code) {
1360             if (LogLevel >= 5)
1361                 Log("VShutdown:  Attempting to take volume %u offline.\n",
1362                     vp->hashid);
1363
1364             /* take the volume offline (drops reference count) */
1365             VOffline_r(vp, "File server was shut down");
1366         }
1367         break;
1368     }
1369     
1370     VCancelReservation_r(vp);
1371     vp = NULL;
1372     return 0;
1373 }
1374 #endif /* AFS_DEMAND_ATTACH_FS */
1375
1376
1377 /***************************************************/
1378 /* Header I/O routines                             */
1379 /***************************************************/
1380
1381 /* open a descriptor for the inode (h),
1382  * read in an on-disk structure into buffer (to) of size (size),
1383  * verify versionstamp in structure has magic (magic) and
1384  * optionally verify version (version) if (version) is nonzero
1385  */
1386 static void
1387 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1388            bit32 version)
1389 {
1390     struct versionStamp *vsn;
1391     FdHandle_t *fdP;
1392
1393     *ec = 0;
1394     if (h == NULL) {
1395         *ec = VSALVAGE;
1396         return;
1397     }
1398
1399     fdP = IH_OPEN(h);
1400     if (fdP == NULL) {
1401         *ec = VSALVAGE;
1402         return;
1403     }
1404
1405     if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1406         *ec = VSALVAGE;
1407         FDH_REALLYCLOSE(fdP);
1408         return;
1409     }
1410     vsn = (struct versionStamp *)to;
1411     if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1412         *ec = VSALVAGE;
1413         FDH_REALLYCLOSE(fdP);
1414         return;
1415     }
1416     FDH_CLOSE(fdP);
1417
1418     /* Check is conditional, in case caller wants to inspect version himself */
1419     if (version && vsn->version != version) {
1420         *ec = VSALVAGE;
1421     }
1422 }
1423
1424 void
1425 WriteVolumeHeader_r(Error * ec, Volume * vp)
1426 {
1427     IHandle_t *h = V_diskDataHandle(vp);
1428     FdHandle_t *fdP;
1429
1430     *ec = 0;
1431
1432     fdP = IH_OPEN(h);
1433     if (fdP == NULL) {
1434         *ec = VSALVAGE;
1435         return;
1436     }
1437     if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1438         *ec = VSALVAGE;
1439         FDH_REALLYCLOSE(fdP);
1440         return;
1441     }
1442     if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1443         != sizeof(V_disk(vp))) {
1444         *ec = VSALVAGE;
1445         FDH_REALLYCLOSE(fdP);
1446         return;
1447     }
1448     FDH_CLOSE(fdP);
1449 }
1450
1451 /* VolumeHeaderToDisk
1452  * Allows for storing 64 bit inode numbers in on-disk volume header
1453  * file.
1454  */
1455 /* convert in-memory representation of a volume header to the
1456  * on-disk representation of a volume header */
1457 void
1458 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1459 {
1460
1461     memset((char *)dh, 0, sizeof(VolumeDiskHeader_t));
1462     dh->stamp = h->stamp;
1463     dh->id = h->id;
1464     dh->parent = h->parent;
1465
1466 #ifdef AFS_64BIT_IOPS_ENV
1467     dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1468     dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1469     dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1470     dh->smallVnodeIndex_hi =
1471         (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1472     dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1473     dh->largeVnodeIndex_hi =
1474         (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1475     dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1476     dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1477 #else
1478     dh->volumeInfo_lo = h->volumeInfo;
1479     dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1480     dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1481     dh->linkTable_lo = h->linkTable;
1482 #endif
1483 }
1484
1485 /* DiskToVolumeHeader
1486  * Converts an on-disk representation of a volume header to
1487  * the in-memory representation of a volume header.
1488  *
1489  * Makes the assumption that AFS has *always* 
1490  * zero'd the volume header file so that high parts of inode
1491  * numbers are 0 in older (SGI EFS) volume header files.
1492  */
1493 void
1494 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1495 {
1496     memset((char *)h, 0, sizeof(VolumeHeader_t));
1497     h->stamp = dh->stamp;
1498     h->id = dh->id;
1499     h->parent = dh->parent;
1500
1501 #ifdef AFS_64BIT_IOPS_ENV
1502     h->volumeInfo =
1503         (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1504
1505     h->smallVnodeIndex =
1506         (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1507                                           smallVnodeIndex_hi << 32);
1508
1509     h->largeVnodeIndex =
1510         (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1511                                           largeVnodeIndex_hi << 32);
1512     h->linkTable =
1513         (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1514 #else
1515     h->volumeInfo = dh->volumeInfo_lo;
1516     h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1517     h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1518     h->linkTable = dh->linkTable_lo;
1519 #endif
1520 }
1521
1522
1523 /***************************************************/
1524 /* Volume Attachment routines                      */
1525 /***************************************************/
1526
1527 #ifdef AFS_DEMAND_ATTACH_FS
1528 /**
1529  * pre-attach a volume given its path.
1530  *
1531  * @param[out] ec         outbound error code
1532  * @param[in]  partition  partition path string
1533  * @param[in]  name       volume id string
1534  *
1535  * @return volume object pointer
1536  *
1537  * @note A pre-attached volume will only have its partition
1538  *       and hashid fields initialized.  At first call to 
1539  *       VGetVolume, the volume will be fully attached.
1540  *
1541  */
1542 Volume *
1543 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
1544 {
1545     Volume * vp;
1546     VOL_LOCK;
1547     vp = VPreAttachVolumeByName_r(ec, partition, name);
1548     VOL_UNLOCK;
1549     return vp;
1550 }
1551
1552 /**
1553  * pre-attach a volume given its path.
1554  *
1555  * @param[out] ec         outbound error code
1556  * @param[in]  partition  path to vice partition
1557  * @param[in]  name       volume id string
1558  *
1559  * @return volume object pointer
1560  *
1561  * @pre VOL_LOCK held
1562  *
1563  * @internal volume package internal use only.
1564  */
1565 Volume *
1566 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
1567 {
1568     return VPreAttachVolumeById_r(ec, 
1569                                   partition,
1570                                   VolumeNumber(name));
1571 }
1572
1573 /**
1574  * pre-attach a volume given its path and numeric volume id.
1575  *
1576  * @param[out] ec          error code return
1577  * @param[in]  partition   path to vice partition
1578  * @param[in]  volumeId    numeric volume id
1579  *
1580  * @return volume object pointer
1581  *
1582  * @pre VOL_LOCK held
1583  *
1584  * @internal volume package internal use only.
1585  */
1586 Volume *
1587 VPreAttachVolumeById_r(Error * ec, 
1588                        char * partition,
1589                        VolId volumeId)
1590 {
1591     Volume *vp;
1592     struct DiskPartition64 *partp;
1593
1594     *ec = 0;
1595
1596     assert(programType == fileServer);
1597
1598     if (!(partp = VGetPartition_r(partition, 0))) {
1599         *ec = VNOVOL;
1600         Log("VPreAttachVolumeById_r:  Error getting partition (%s)\n", partition);
1601         return NULL;
1602     }
1603
1604     vp = VLookupVolume_r(ec, volumeId, NULL);
1605     if (*ec) {
1606         return NULL;
1607     }
1608
1609     return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1610 }
1611
1612 /**
1613  * preattach a volume.
1614  *
1615  * @param[out] ec     outbound error code
1616  * @param[in]  partp  pointer to partition object
1617  * @param[in]  vp     pointer to volume object
1618  * @param[in]  vid    volume id
1619  *
1620  * @return volume object pointer
1621  *
1622  * @pre VOL_LOCK is held.
1623  *
1624  * @warning Returned volume object pointer does not have to
1625  *          equal the pointer passed in as argument vp.  There
1626  *          are potential race conditions which can result in
1627  *          the pointers having different values.  It is up to
1628  *          the caller to make sure that references are handled
1629  *          properly in this case.
1630  *
1631  * @note If there is already a volume object registered with
1632  *       the same volume id, its pointer MUST be passed as 
1633  *       argument vp.  Failure to do so will result in a silent
1634  *       failure to preattach.
1635  *
1636  * @internal volume package internal use only.
1637  */
1638 Volume * 
1639 VPreAttachVolumeByVp_r(Error * ec, 
1640                        struct DiskPartition64 * partp, 
1641                        Volume * vp,
1642                        VolId vid)
1643 {
1644     Volume *nvp = NULL;
1645
1646     *ec = 0;
1647
1648     /* check to see if pre-attach already happened */
1649     if (vp && 
1650         (V_attachState(vp) != VOL_STATE_UNATTACHED) && 
1651         (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
1652         !VIsErrorState(V_attachState(vp))) {
1653         /*
1654          * pre-attach is a no-op in all but the following cases:
1655          *
1656          *   - volume is unattached
1657          *   - volume is in an error state
1658          *   - volume is pre-attached
1659          */
1660         Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
1661         goto done;
1662     } else if (vp) {
1663         /* we're re-attaching a volume; clear out some old state */
1664         memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1665
1666         if (V_partition(vp) != partp) {
1667             /* XXX potential race */
1668             DeleteVolumeFromVByPList_r(vp);
1669         }
1670     } else {
1671         /* if we need to allocate a new Volume struct,
1672          * go ahead and drop the vol glock, otherwise
1673          * do the basic setup synchronised, as it's
1674          * probably not worth dropping the lock */
1675         VOL_UNLOCK;
1676
1677         /* allocate the volume structure */
1678         vp = nvp = (Volume *) malloc(sizeof(Volume));
1679         assert(vp != NULL);
1680         memset(vp, 0, sizeof(Volume));
1681         queue_Init(&vp->vnode_list);
1682         assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1683     }
1684
1685     /* link the volume with its associated vice partition */
1686     vp->device = partp->device;
1687     vp->partition = partp;
1688
1689     vp->hashid = vid;
1690     vp->specialStatus = 0;
1691
1692     /* if we dropped the lock, reacquire the lock,
1693      * check for pre-attach races, and then add
1694      * the volume to the hash table */
1695     if (nvp) {
1696         VOL_LOCK;
1697         nvp = VLookupVolume_r(ec, vid, NULL);
1698         if (*ec) {
1699             free(vp);
1700             vp = NULL;
1701             goto done;
1702         } else if (nvp) { /* race detected */
1703             free(vp);
1704             vp = nvp;
1705             goto done;
1706         } else {
1707           /* hack to make up for VChangeState_r() decrementing 
1708            * the old state counter */
1709           VStats.state_levels[0]++;
1710         }
1711     }
1712
1713     /* put pre-attached volume onto the hash table
1714      * and bring it up to the pre-attached state */
1715     AddVolumeToHashTable(vp, vp->hashid);
1716     AddVolumeToVByPList_r(vp);
1717     VLRU_Init_Node_r(vp);
1718     VChangeState_r(vp, VOL_STATE_PREATTACHED);
1719
1720     if (LogLevel >= 5)
1721         Log("VPreAttachVolumeByVp_r:  volume %u pre-attached\n", vp->hashid);
1722
1723   done:
1724     if (*ec)
1725         return NULL;
1726     else
1727         return vp;
1728 }
1729 #endif /* AFS_DEMAND_ATTACH_FS */
1730
1731 /* Attach an existing volume, given its pathname, and return a
1732    pointer to the volume header information.  The volume also
1733    normally goes online at this time.  An offline volume
1734    must be reattached to make it go online */
1735 Volume *
1736 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1737 {
1738     Volume *retVal;
1739     VOL_LOCK;
1740     retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1741     VOL_UNLOCK;
1742     return retVal;
1743 }
1744
1745 Volume *
1746 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1747 {
1748     register Volume *vp = NULL;
1749     int fd, n;
1750     struct afs_stat status;
1751     struct VolumeDiskHeader diskHeader;
1752     struct VolumeHeader iheader;
1753     struct DiskPartition64 *partp;
1754     char path[64];
1755     int isbusy = 0;
1756     VolId volumeId;
1757 #ifdef AFS_DEMAND_ATTACH_FS
1758     VolumeStats stats_save;
1759     Volume *svp = NULL;
1760 #endif /* AFS_DEMAND_ATTACH_FS */
1761
1762     *ec = 0;
1763    
1764     volumeId = VolumeNumber(name);
1765
1766     if (!(partp = VGetPartition_r(partition, 0))) {
1767         *ec = VNOVOL;
1768         Log("VAttachVolume: Error getting partition (%s)\n", partition);
1769         goto done;
1770     }
1771
1772     if (programType == volumeUtility) {
1773         assert(VInit == 3);
1774         VLockPartition_r(partition);
1775     } else if (programType == fileServer) {
1776 #ifdef AFS_DEMAND_ATTACH_FS
1777         /* lookup the volume in the hash table */
1778         vp = VLookupVolume_r(ec, volumeId, NULL);
1779         if (*ec) {
1780             return NULL;
1781         }
1782
1783         if (vp) {
1784             /* save any counters that are supposed to
1785              * be monotonically increasing over the
1786              * lifetime of the fileserver */
1787             memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1788         } else {
1789             memset(&stats_save, 0, sizeof(VolumeStats));
1790         }
1791
1792         /* if there's something in the hash table, and it's not
1793          * in the pre-attach state, then we may need to detach
1794          * it before proceeding */
1795         if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1796             VCreateReservation_r(vp);
1797             VWaitExclusiveState_r(vp);
1798
1799             /* at this point state must be one of:
1800              *   - UNATTACHED
1801              *   - ATTACHED
1802              *   - SHUTTING_DOWN
1803              *   - GOING_OFFLINE
1804              *   - SALVAGING
1805              *   - ERROR
1806              */
1807
1808             if (vp->specialStatus == VBUSY)
1809                 isbusy = 1;
1810             
1811             /* if it's already attached, see if we can return it */
1812             if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1813                 VGetVolumeByVp_r(ec, vp);
1814                 if (V_inUse(vp) == fileServer) {
1815                     VCancelReservation_r(vp);
1816                     return vp;
1817                 }
1818
1819                 /* otherwise, we need to detach, and attempt to re-attach */
1820                 VDetachVolume_r(ec, vp);
1821                 if (*ec) {
1822                     Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1823                 }
1824             } else {
1825                 /* if it isn't fully attached, delete from the hash tables,
1826                    and let the refcounter handle the rest */
1827                 DeleteVolumeFromHashTable(vp);
1828                 DeleteVolumeFromVByPList_r(vp);
1829             }
1830
1831             VCancelReservation_r(vp);
1832             vp = NULL;
1833         }
1834
1835         /* pre-attach volume if it hasn't been done yet */
1836         if (!vp || 
1837             (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1838             (V_attachState(vp) == VOL_STATE_ERROR)) {
1839             svp = vp;
1840             vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1841             if (*ec) {
1842                 return NULL;
1843             }
1844         }
1845
1846         assert(vp != NULL);
1847
1848         /* handle pre-attach races 
1849          *
1850          * multiple threads can race to pre-attach a volume,
1851          * but we can't let them race beyond that
1852          * 
1853          * our solution is to let the first thread to bring
1854          * the volume into an exclusive state win; the other
1855          * threads just wait until it finishes bringing the
1856          * volume online, and then they do a vgetvolumebyvp
1857          */
1858         if (svp && (svp != vp)) {
1859             /* wait for other exclusive ops to finish */
1860             VCreateReservation_r(vp);
1861             VWaitExclusiveState_r(vp);
1862
1863             /* get a heavyweight ref, kill the lightweight ref, and return */
1864             VGetVolumeByVp_r(ec, vp);
1865             VCancelReservation_r(vp);
1866             return vp;
1867         }
1868
1869         /* at this point, we are chosen as the thread to do
1870          * demand attachment for this volume. all other threads
1871          * doing a getvolume on vp->hashid will block until we finish */
1872
1873         /* make sure any old header cache entries are invalidated
1874          * before proceeding */
1875         FreeVolumeHeader(vp);
1876
1877         VChangeState_r(vp, VOL_STATE_ATTACHING);
1878
1879         /* restore any saved counters */
1880         memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
1881 #else /* AFS_DEMAND_ATTACH_FS */
1882         vp = VGetVolume_r(ec, volumeId);
1883         if (vp) {
1884             if (V_inUse(vp) == fileServer)
1885                 return vp;
1886             if (vp->specialStatus == VBUSY)
1887                 isbusy = 1;
1888             VDetachVolume_r(ec, vp);
1889             if (*ec) {
1890                 Log("VAttachVolume: Error detaching volume (%s)\n", name);
1891             }
1892             vp = NULL;
1893         }
1894 #endif /* AFS_DEMAND_ATTACH_FS */
1895     }
1896
1897     *ec = 0;
1898     strcpy(path, VPartitionPath(partp));
1899
1900     VOL_UNLOCK;
1901
1902     strcat(path, "/");
1903     strcat(path, name);
1904     if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
1905         Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
1906         if (fd > -1)
1907             close(fd);
1908         *ec = VNOVOL;
1909         VOL_LOCK;
1910         goto done;
1911     }
1912     n = read(fd, &diskHeader, sizeof(diskHeader));
1913     close(fd);
1914     if (n != sizeof(diskHeader)
1915         || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1916         Log("VAttachVolume: Error reading volume header %s\n", path);
1917         *ec = VSALVAGE;
1918         VOL_LOCK;
1919         goto done;
1920     }
1921     if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1922         Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
1923         *ec = VSALVAGE;
1924         VOL_LOCK;
1925         goto done;
1926     }
1927
1928     DiskToVolumeHeader(&iheader, &diskHeader);
1929 #ifdef FSSYNC_BUILD_CLIENT
1930     if (programType == volumeUtility && mode != V_SECRETLY && mode != V_PEEK) {
1931         VOL_LOCK;
1932         if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, NULL)
1933             != SYNC_OK) {
1934             Log("VAttachVolume: attach of volume %u apparently denied by file server\n", iheader.id);
1935             *ec = VNOVOL;       /* XXXX */
1936             goto done;
1937         }
1938         VOL_UNLOCK;
1939     }
1940 #endif
1941
1942     if (!vp) {
1943       vp = (Volume *) calloc(1, sizeof(Volume));
1944       assert(vp != NULL);
1945       vp->device = partp->device;
1946       vp->partition = partp;
1947       queue_Init(&vp->vnode_list);
1948 #ifdef AFS_DEMAND_ATTACH_FS
1949       assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1950 #endif /* AFS_DEMAND_ATTACH_FS */
1951     }
1952
1953     /* attach2 is entered without any locks, and returns
1954      * with vol_glock_mutex held */
1955     vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
1956
1957     if (programType == volumeUtility && vp) {
1958         if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
1959             /* mark volume header as in use so that volser crashes lead to a
1960              * salvage attempt */
1961             VUpdateVolume_r(ec, vp, 0);
1962         }
1963 #ifdef AFS_DEMAND_ATTACH_FS
1964         /* for dafs, we should tell the fileserver, except for V_PEEK
1965          * where we know it is not necessary */
1966         if (mode == V_PEEK) {
1967             vp->needsPutBack = 0;
1968         } else {
1969             vp->needsPutBack = 1;
1970         }
1971 #else /* !AFS_DEMAND_ATTACH_FS */
1972         /* duplicate computation in fssync.c about whether the server
1973          * takes the volume offline or not.  If the volume isn't
1974          * offline, we must not return it when we detach the volume,
1975          * or the server will abort */
1976         if (mode == V_READONLY || mode == V_PEEK
1977             || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
1978             vp->needsPutBack = 0;
1979         else
1980             vp->needsPutBack = 1;
1981 #endif /* !AFS_DEMAND_ATTACH_FS */
1982     }
1983     /* OK, there's a problem here, but one that I don't know how to
1984      * fix right now, and that I don't think should arise often.
1985      * Basically, we should only put back this volume to the server if
1986      * it was given to us by the server, but since we don't have a vp,
1987      * we can't run the VolumeWriteable function to find out as we do
1988      * above when computing vp->needsPutBack.  So we send it back, but
1989      * there's a path in VAttachVolume on the server which may abort
1990      * if this volume doesn't have a header.  Should be pretty rare
1991      * for all of that to happen, but if it does, probably the right
1992      * fix is for the server to allow the return of readonly volumes
1993      * that it doesn't think are really checked out. */
1994 #ifdef FSSYNC_BUILD_CLIENT
1995     if (programType == volumeUtility && vp == NULL &&
1996         mode != V_SECRETLY && mode != V_PEEK) {
1997         FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
1998     } else 
1999 #endif
2000     if (programType == fileServer && vp) {
2001 #ifdef AFS_DEMAND_ATTACH_FS
2002         /* 
2003          * we can get here in cases where we don't "own"
2004          * the volume (e.g. volume owned by a utility).
2005          * short circuit around potential disk header races.
2006          */
2007         if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2008             goto done;
2009         }
2010 #endif
2011         V_needsCallback(vp) = 0;
2012 #ifdef  notdef
2013         if (VInit >= 2 && V_BreakVolumeCallbacks) {
2014             Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
2015             (*V_BreakVolumeCallbacks) (V_id(vp));
2016         }
2017 #endif
2018         VUpdateVolume_r(ec, vp, 0);
2019         if (*ec) {
2020             Log("VAttachVolume: Error updating volume\n");
2021             if (vp)
2022                 VPutVolume_r(vp);
2023             goto done;
2024         }
2025         if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2026 #ifndef AFS_DEMAND_ATTACH_FS
2027             /* This is a hack: by temporarily setting the incore
2028              * dontSalvage flag ON, the volume will be put back on the
2029              * Update list (with dontSalvage OFF again).  It will then
2030              * come back in N minutes with DONT_SALVAGE eventually
2031              * set.  This is the way that volumes that have never had
2032              * it set get it set; or that volumes that have been
2033              * offline without DONT SALVAGE having been set also
2034              * eventually get it set */
2035             V_dontSalvage(vp) = DONT_SALVAGE;
2036 #endif /* !AFS_DEMAND_ATTACH_FS */
2037             VAddToVolumeUpdateList_r(ec, vp);
2038             if (*ec) {
2039                 Log("VAttachVolume: Error adding volume to update list\n");
2040                 if (vp)
2041                     VPutVolume_r(vp);
2042                 goto done;
2043             }
2044         }
2045         if (LogLevel)
2046             Log("VOnline:  volume %u (%s) attached and online\n", V_id(vp),
2047                 V_name(vp));
2048     }
2049
2050   done:
2051     if (programType == volumeUtility) {
2052         VUnlockPartition_r(partition);
2053     }
2054     if (*ec) {
2055 #ifdef AFS_DEMAND_ATTACH_FS
2056         /* attach failed; make sure we're in error state */
2057         if (vp && !VIsErrorState(V_attachState(vp))) {
2058             VChangeState_r(vp, VOL_STATE_ERROR);
2059         }
2060 #endif /* AFS_DEMAND_ATTACH_FS */
2061         return NULL;
2062     } else {
2063         return vp;
2064     }
2065 }
2066
2067 #ifdef AFS_DEMAND_ATTACH_FS
2068 /* VAttachVolumeByVp_r
2069  *
2070  * finish attaching a volume that is
2071  * in a less than fully attached state
2072  */
2073 /* caller MUST hold a ref count on vp */
2074 static Volume *
2075 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2076 {
2077     char name[VMAXPATHLEN];
2078     int fd, n, reserve = 0;
2079     struct afs_stat status;
2080     struct VolumeDiskHeader diskHeader;
2081     struct VolumeHeader iheader;
2082     struct DiskPartition64 *partp;
2083     char path[64];
2084     int isbusy = 0;
2085     VolId volumeId;
2086     Volume * nvp;
2087     VolumeStats stats_save;
2088     *ec = 0;
2089
2090     /* volume utility should never call AttachByVp */
2091     assert(programType == fileServer);
2092    
2093     volumeId = vp->hashid;
2094     partp = vp->partition;
2095     VolumeExternalName_r(volumeId, name, sizeof(name));
2096
2097
2098     /* if another thread is performing a blocking op, wait */
2099     VWaitExclusiveState_r(vp);
2100
2101     memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2102
2103     /* if it's already attached, see if we can return it */
2104     if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2105         VGetVolumeByVp_r(ec, vp);
2106         if (V_inUse(vp) == fileServer) {
2107             return vp;
2108         } else {
2109             if (vp->specialStatus == VBUSY)
2110                 isbusy = 1;
2111             VDetachVolume_r(ec, vp);
2112             if (*ec) {
2113                 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2114             }
2115             vp = NULL;
2116         }
2117     }
2118
2119     /* pre-attach volume if it hasn't been done yet */
2120     if (!vp || 
2121         (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2122         (V_attachState(vp) == VOL_STATE_ERROR)) {
2123         nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2124         if (*ec) {
2125             return NULL;
2126         }
2127         if (nvp != vp) {
2128             reserve = 1;
2129             VCreateReservation_r(nvp);
2130             vp = nvp;
2131         }
2132     }
2133     
2134     assert(vp != NULL);
2135     VChangeState_r(vp, VOL_STATE_ATTACHING);
2136
2137     /* restore monotonically increasing stats */
2138     memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2139
2140     *ec = 0;
2141
2142
2143     /* compute path to disk header, 
2144      * read in header, 
2145      * and verify magic and version stamps */
2146     strcpy(path, VPartitionPath(partp));
2147
2148     VOL_UNLOCK;
2149
2150     strcat(path, "/");
2151     strcat(path, name);
2152     if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2153         Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2154         if (fd > -1)
2155             close(fd);
2156         *ec = VNOVOL;
2157         VOL_LOCK;
2158         goto done;
2159     }
2160     n = read(fd, &diskHeader, sizeof(diskHeader));
2161     close(fd);
2162     if (n != sizeof(diskHeader)
2163         || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2164         Log("VAttachVolume: Error reading volume header %s\n", path);
2165         *ec = VSALVAGE;
2166         VOL_LOCK;
2167         goto done;
2168     }
2169     if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2170         Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2171         *ec = VSALVAGE;
2172         VOL_LOCK;
2173         goto done;
2174     }
2175
2176     /* convert on-disk header format to in-memory header format */
2177     DiskToVolumeHeader(&iheader, &diskHeader);
2178
2179     /* do volume attach
2180      *
2181      * NOTE: attach2 is entered without any locks, and returns
2182      * with vol_glock_mutex held */
2183     vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2184
2185     /*
2186      * the event that an error was encountered, or
2187      * the volume was not brought to an attached state
2188      * for any reason, skip to the end.  We cannot
2189      * safely call VUpdateVolume unless we "own" it.
2190      */
2191     if (*ec || 
2192         (vp == NULL) ||
2193         (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2194         goto done;
2195     }
2196
2197     V_needsCallback(vp) = 0;
2198     VUpdateVolume_r(ec, vp, 0);
2199     if (*ec) {
2200         Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2201         VPutVolume_r(vp);
2202         goto done;
2203     }
2204     if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2205 #ifndef AFS_DEMAND_ATTACH_FS
2206         /* This is a hack: by temporarily setting the incore
2207          * dontSalvage flag ON, the volume will be put back on the
2208          * Update list (with dontSalvage OFF again).  It will then
2209          * come back in N minutes with DONT_SALVAGE eventually
2210          * set.  This is the way that volumes that have never had
2211          * it set get it set; or that volumes that have been
2212          * offline without DONT SALVAGE having been set also
2213          * eventually get it set */
2214         V_dontSalvage(vp) = DONT_SALVAGE;
2215 #endif /* !AFS_DEMAND_ATTACH_FS */
2216         VAddToVolumeUpdateList_r(ec, vp);
2217         if (*ec) {
2218             Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2219             if (vp)
2220                 VPutVolume_r(vp);
2221             goto done;
2222         }
2223     }
2224     if (LogLevel)
2225         Log("VOnline:  volume %u (%s) attached and online\n", V_id(vp),
2226             V_name(vp));
2227   done:
2228     if (reserve) {
2229         VCancelReservation_r(nvp);
2230         reserve = 0;
2231     }
2232     if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2233         if (vp && !VIsErrorState(V_attachState(vp))) {
2234             VChangeState_r(vp, VOL_STATE_ERROR);
2235         }
2236         return NULL;
2237     } else {
2238         return vp;
2239     }
2240 }
2241 #endif /* AFS_DEMAND_ATTACH_FS */
2242
2243 /*
2244  * called without any locks held
2245  * returns with vol_glock_mutex held
2246  */
2247 private Volume * 
2248 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2249         struct DiskPartition64 * partp, register Volume * vp, int isbusy, int mode)
2250 {
2251     vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2252     IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2253             header->largeVnodeIndex);
2254     IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2255             header->smallVnodeIndex);
2256     IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2257             header->volumeInfo);
2258     IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2259     vp->shuttingDown = 0;
2260     vp->goingOffline = 0;
2261     vp->nUsers = 1;
2262 #ifdef AFS_DEMAND_ATTACH_FS
2263     vp->stats.last_attach = FT_ApproxTime();
2264     vp->stats.attaches++;
2265 #endif
2266
2267     VOL_LOCK;
2268     IncUInt64(&VStats.attaches);
2269     vp->cacheCheck = ++VolumeCacheCheck;
2270     /* just in case this ever rolls over */
2271     if (!vp->cacheCheck)
2272         vp->cacheCheck = ++VolumeCacheCheck;
2273     GetVolumeHeader(vp);
2274     VOL_UNLOCK;
2275
2276 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2277     /* demand attach changes the V_PEEK mechanism
2278      *
2279      * we can now suck the current disk data structure over
2280      * the fssync interface without going to disk
2281      *
2282      * (technically, we don't need to restrict this feature
2283      *  to demand attach fileservers.  However, I'm trying
2284      *  to limit the number of common code changes)
2285      */
2286     if (programType != fileServer && mode == V_PEEK) {
2287         SYNC_response res;
2288         res.payload.len = sizeof(VolumeDiskData);
2289         res.payload.buf = &vp->header->diskstuff;
2290
2291         if (FSYNC_VolOp(volumeId,
2292                         partp->name,
2293                         FSYNC_VOL_QUERY_HDR,
2294                         FSYNC_WHATEVER,
2295                         &res) == SYNC_OK) {
2296             goto disk_header_loaded;
2297         }
2298     }
2299 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2300     (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2301                      sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2302
2303 #ifdef AFS_DEMAND_ATTACH_FS
2304     /* update stats */
2305     VOL_LOCK;
2306     IncUInt64(&VStats.hdr_loads);
2307     IncUInt64(&vp->stats.hdr_loads);
2308     VOL_UNLOCK;
2309 #endif /* AFS_DEMAND_ATTACH_FS */
2310     
2311     if (*ec) {
2312         Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2313     }
2314
2315 #ifdef AFS_DEMAND_ATTACH_FS
2316  disk_header_loaded:
2317     if (!*ec) {
2318
2319         /* check for pending volume operations */
2320         if (vp->pending_vol_op) {
2321             /* see if the pending volume op requires exclusive access */
2322             switch (vp->pending_vol_op->vol_op_state) {
2323             case FSSYNC_VolOpPending:
2324                 /* this should never happen */
2325                 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2326                 break;
2327
2328             case FSSYNC_VolOpRunningUnknown:
2329                 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2330                     vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2331                     break;
2332                 } else {
2333                     vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2334                     /* fall through to take volume offline */
2335                 }
2336
2337             case FSSYNC_VolOpRunningOffline:
2338                 /* mark the volume down */
2339                 *ec = VOFFLINE;
2340                 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2341                 if (V_offlineMessage(vp)[0] == '\0')
2342                     strlcpy(V_offlineMessage(vp),
2343                             "A volume utility is running.", 
2344                             sizeof(V_offlineMessage(vp)));
2345                 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2346
2347                 /* check to see if we should set the specialStatus flag */
2348                 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2349                     vp->specialStatus = VBUSY;
2350                 }
2351             }
2352         }
2353
2354         V_attachFlags(vp) |= VOL_HDR_LOADED;
2355         vp->stats.last_hdr_load = vp->stats.last_attach;
2356     }
2357 #endif /* AFS_DEMAND_ATTACH_FS */
2358
2359     if (!*ec) {
2360         struct IndexFileHeader iHead;
2361
2362 #if OPENAFS_VOL_STATS
2363         /*
2364          * We just read in the diskstuff part of the header.  If the detailed
2365          * volume stats area has not yet been initialized, we should bzero the
2366          * area and mark it as initialized.
2367          */
2368         if (!(V_stat_initialized(vp))) {
2369             memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
2370             V_stat_initialized(vp) = 1;
2371         }
2372 #endif /* OPENAFS_VOL_STATS */
2373
2374         (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2375                          (char *)&iHead, sizeof(iHead),
2376                          SMALLINDEXMAGIC, SMALLINDEXVERSION);
2377
2378         if (*ec) {
2379             Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2380         }
2381     }
2382
2383     if (!*ec) {
2384         struct IndexFileHeader iHead;
2385
2386         (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2387                          (char *)&iHead, sizeof(iHead),
2388                          LARGEINDEXMAGIC, LARGEINDEXVERSION);
2389
2390         if (*ec) {
2391             Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2392         }
2393     }
2394
2395 #ifdef AFS_NAMEI_ENV
2396     if (!*ec) {
2397         struct versionStamp stamp;
2398
2399         (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2400                          sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2401
2402         if (*ec) {
2403             Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2404         }
2405     }
2406 #endif /* AFS_NAMEI_ENV */
2407
2408 #if defined(AFS_DEMAND_ATTACH_FS)
2409     if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2410         VOL_LOCK;
2411         if (programType == fileServer) {
2412             VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2413             vp->nUsers = 0;
2414         } else {
2415             Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2416             FreeVolume(vp);
2417             *ec = VSALVAGE;
2418         }
2419         return NULL;
2420     } else if (*ec) {
2421         /* volume operation in progress */
2422         VOL_LOCK;
2423         return NULL;
2424     }
2425 #else /* AFS_DEMAND_ATTACH_FS */
2426     if (*ec) {
2427         Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2428         VOL_LOCK;
2429         FreeVolume(vp);
2430         return NULL;
2431     }
2432 #endif /* AFS_DEMAND_ATTACH_FS */
2433
2434     if (V_needsSalvaged(vp)) {
2435         if (vp->specialStatus)
2436             vp->specialStatus = 0;
2437         VOL_LOCK;
2438 #if defined(AFS_DEMAND_ATTACH_FS)
2439         if (programType == fileServer) {
2440             VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2441             vp->nUsers = 0;
2442         } else {
2443             Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2444             FreeVolume(vp);
2445             *ec = VSALVAGE;
2446         }
2447 #else /* AFS_DEMAND_ATTACH_FS */
2448         FreeVolume(vp);
2449         *ec = VSALVAGE;
2450 #endif /* AFS_DEMAND_ATTACH_FS */
2451         return NULL;
2452     }
2453
2454     VOL_LOCK;
2455     if (programType == fileServer) {
2456 #ifndef FAST_RESTART
2457         if (V_inUse(vp) && VolumeWriteable(vp)) {
2458             if (!V_needsSalvaged(vp)) {
2459                 V_needsSalvaged(vp) = 1;
2460                 VUpdateVolume_r(ec, vp, 0);
2461             }
2462 #if defined(AFS_DEMAND_ATTACH_FS)
2463             VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2464             vp->nUsers = 0;
2465 #else /* AFS_DEMAND_ATTACH_FS */
2466             Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2467             FreeVolume(vp);
2468             *ec = VSALVAGE;
2469 #endif /* AFS_DEMAND_ATTACH_FS */
2470             return NULL;
2471         }
2472 #endif /* FAST_RESTART */
2473
2474         if (V_destroyMe(vp) == DESTROY_ME) {
2475 #if defined(AFS_DEMAND_ATTACH_FS)
2476             /* schedule a salvage so the volume goes away on disk */
2477             VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2478             VChangeState_r(vp, VOL_STATE_ERROR);
2479             vp->nUsers = 0;
2480 #endif /* AFS_DEMAND_ATTACH_FS */
2481             FreeVolume(vp);
2482             Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2483             *ec = VNOVOL;
2484             return NULL;
2485         }
2486     }
2487
2488     vp->nextVnodeUnique = V_uniquifier(vp);
2489     vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2490 #ifndef BITMAP_LATER
2491     if (programType == fileServer && VolumeWriteable(vp)) {
2492         int i;
2493         for (i = 0; i < nVNODECLASSES; i++) {
2494             VGetBitmap_r(ec, vp, i);
2495             if (*ec) {
2496 #ifdef AFS_DEMAND_ATTACH_FS
2497                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2498                 vp->nUsers = 0;
2499 #else /* AFS_DEMAND_ATTACH_FS */
2500                 FreeVolume(vp);
2501 #endif /* AFS_DEMAND_ATTACH_FS */
2502                 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2503                     path);
2504                 return NULL;
2505             }
2506         }
2507     }
2508 #endif /* BITMAP_LATER */
2509
2510     if (programType == fileServer) {
2511         if (vp->specialStatus)
2512             vp->specialStatus = 0;
2513         if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2514             V_inUse(vp) = fileServer;
2515             V_offlineMessage(vp)[0] = '\0';
2516         }
2517     } else {
2518         if ((mode != V_PEEK) && (mode != V_SECRETLY))
2519             V_inUse(vp) = programType;
2520         V_checkoutMode(vp) = mode;
2521     }
2522
2523     AddVolumeToHashTable(vp, V_id(vp));
2524 #ifdef AFS_DEMAND_ATTACH_FS
2525     if ((programType != fileServer) ||
2526         (V_inUse(vp) == fileServer)) {
2527         AddVolumeToVByPList_r(vp);
2528         VLRU_Add_r(vp);
2529         VChangeState_r(vp, VOL_STATE_ATTACHED);
2530     } else {
2531         VChangeState_r(vp, VOL_STATE_UNATTACHED);
2532     }
2533 #endif
2534     return vp;
2535 }
2536
2537 /* Attach an existing volume.
2538    The volume also normally goes online at this time.
2539    An offline volume must be reattached to make it go online.
2540  */
2541
2542 Volume *
2543 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2544 {
2545     Volume *retVal;
2546     VOL_LOCK;
2547     retVal = VAttachVolume_r(ec, volumeId, mode);
2548     VOL_UNLOCK;
2549     return retVal;
2550 }
2551
2552 Volume *
2553 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2554 {
2555     char *part, *name;
2556     VGetVolumePath(ec, volumeId, &part, &name);
2557     if (*ec) {
2558         register Volume *vp;
2559         Error error;
2560         vp = VGetVolume_r(&error, volumeId);
2561         if (vp) {
2562             assert(V_inUse(vp) == 0);
2563             VDetachVolume_r(ec, vp);
2564         }
2565         return NULL;
2566     }
2567     return VAttachVolumeByName_r(ec, part, name, mode);
2568 }
2569
2570 /* Increment a reference count to a volume, sans context swaps.  Requires
2571  * possibly reading the volume header in from the disk, since there's
2572  * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2573  *
2574  * N.B. This call can fail if we can't read in the header!!  In this case
2575  * we still guarantee we won't context swap, but the ref count won't be
2576  * incremented (otherwise we'd violate the invariant).
2577  */
2578 /* NOTE: with the demand attach fileserver extensions, the global lock
2579  * is dropped within VHold */
2580 #ifdef AFS_DEMAND_ATTACH_FS
2581 static int
2582 VHold_r(register Volume * vp)
2583 {
2584     Error error;
2585
2586     VCreateReservation_r(vp);
2587     VWaitExclusiveState_r(vp);
2588
2589     LoadVolumeHeader(&error, vp);
2590     if (error) {
2591         VCancelReservation_r(vp);
2592         return error;
2593     }
2594     vp->nUsers++;
2595     VCancelReservation_r(vp);
2596     return 0;
2597 }
2598 #else /* AFS_DEMAND_ATTACH_FS */
2599 static int
2600 VHold_r(register Volume * vp)
2601 {
2602     Error error;
2603
2604     LoadVolumeHeader(&error, vp);
2605     if (error)
2606         return error;
2607     vp->nUsers++;
2608     return 0;
2609 }
2610 #endif /* AFS_DEMAND_ATTACH_FS */
2611
2612 #if 0
2613 static int
2614 VHold(register Volume * vp)
2615 {
2616     int retVal;
2617     VOL_LOCK;
2618     retVal = VHold_r(vp);
2619     VOL_UNLOCK;
2620     return retVal;
2621 }
2622 #endif
2623
2624
2625 /***************************************************/
2626 /* get and put volume routines                     */
2627 /***************************************************/
2628
2629 /**
2630  * put back a heavyweight reference to a volume object.
2631  *
2632  * @param[in] vp  volume object pointer
2633  *
2634  * @pre VOL_LOCK held
2635  *
2636  * @post heavyweight volume reference put back.
2637  *       depending on state, volume may have been taken offline,
2638  *       detached, salvaged, freed, etc.
2639  *
2640  * @internal volume package internal use only
2641  */
2642 void
2643 VPutVolume_r(register Volume * vp)
2644 {
2645     assert(--vp->nUsers >= 0);
2646     if (vp->nUsers == 0) {
2647         VCheckOffline(vp);
2648         ReleaseVolumeHeader(vp->header);
2649 #ifdef AFS_DEMAND_ATTACH_FS
2650         if (!VCheckDetach(vp)) {
2651             VCheckSalvage(vp);
2652             VCheckFree(vp);
2653         }
2654 #else /* AFS_DEMAND_ATTACH_FS */
2655         VCheckDetach(vp);
2656 #endif /* AFS_DEMAND_ATTACH_FS */
2657     }
2658 }
2659
2660 void
2661 VPutVolume(register Volume * vp)
2662 {
2663     VOL_LOCK;
2664     VPutVolume_r(vp);
2665     VOL_UNLOCK;
2666 }
2667
2668
2669 /* Get a pointer to an attached volume.  The pointer is returned regardless
2670    of whether or not the volume is in service or on/off line.  An error
2671    code, however, is returned with an indication of the volume's status */
2672 Volume *
2673 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2674 {
2675     Volume *retVal;
2676     VOL_LOCK;
2677     retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2678     VOL_UNLOCK;
2679     return retVal;
2680 }
2681
2682 Volume *
2683 VGetVolume_r(Error * ec, VolId volumeId)
2684 {
2685     return GetVolume(ec, NULL, volumeId, NULL, 0);
2686 }
2687
2688 /* try to get a volume we've previously looked up */
2689 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2690 Volume * 
2691 VGetVolumeByVp_r(Error * ec, Volume * vp)
2692 {
2693     return GetVolume(ec, NULL, vp->hashid, vp, 0);
2694 }
2695
2696 /* private interface for getting a volume handle
2697  * volumeId must be provided.
2698  * hint is an optional parameter to speed up hash lookups
2699  * flags is not used at this time
2700  */
2701 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2702 static Volume *
2703 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2704 {
2705     Volume *vp = hint;
2706     /* pull this profiling/debugging code out of regular builds */
2707 #ifdef notdef
2708 #define VGET_CTR_INC(x) x++
2709     unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2710         0, V7 = 0, V8 = 0, V9 = 0;
2711     unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2712 #else
2713 #define VGET_CTR_INC(x)
2714 #endif
2715 #ifdef AFS_DEMAND_ATTACH_FS
2716     Volume *avp, * rvp = hint;
2717 #endif
2718
2719     /* 
2720      * if VInit is zero, the volume package dynamic
2721      * data structures have not been initialized yet,
2722      * and we must immediately return an error
2723      */
2724     if (VInit == 0) {
2725         vp = NULL;
2726         *ec = VOFFLINE;
2727         if (client_ec) {
2728             *client_ec = VOFFLINE;
2729         }
2730         goto not_inited;
2731     }
2732
2733 #ifdef AFS_DEMAND_ATTACH_FS
2734     if (rvp) {
2735         VCreateReservation_r(rvp);
2736     }
2737 #endif /* AFS_DEMAND_ATTACH_FS */
2738
2739     for (;;) {
2740         *ec = 0;
2741         if (client_ec)
2742             *client_ec = 0;
2743         VGET_CTR_INC(V0);
2744
2745         vp = VLookupVolume_r(ec, volumeId, vp);
2746         if (*ec) {
2747             vp = NULL;
2748             break;
2749         }
2750
2751 #ifdef AFS_DEMAND_ATTACH_FS
2752         if (rvp && (rvp != vp)) {
2753             /* break reservation on old vp */
2754             VCancelReservation_r(rvp);
2755             rvp = NULL;
2756         }
2757 #endif /* AFS_DEMAND_ATTACH_FS */
2758
2759         if (!vp) {
2760             VGET_CTR_INC(V1);
2761             if (VInit < 2) {
2762                 VGET_CTR_INC(V2);
2763                 /* Until we have reached an initialization level of 2
2764                  * we don't know whether this volume exists or not.
2765                  * We can't sleep and retry later because before a volume
2766                  * is attached, the caller tries to get it first.  Just
2767                  * return VOFFLINE and the caller can choose whether to
2768                  * retry the command or not. */
2769                 *ec = VOFFLINE;
2770                 break;
2771             }
2772
2773             *ec = VNOVOL;
2774             break;
2775         }
2776
2777         VGET_CTR_INC(V3);
2778         IncUInt64(&VStats.hdr_gets);
2779         
2780 #ifdef AFS_DEMAND_ATTACH_FS
2781         /* block if someone else is performing an exclusive op on this volume */
2782         if (rvp != vp) {
2783             rvp = vp;
2784             VCreateReservation_r(rvp);
2785         }
2786         VWaitExclusiveState_r(vp);
2787
2788         /* short circuit with VNOVOL in the following circumstances:
2789          *
2790          *   - VOL_STATE_ERROR
2791          *   - VOL_STATE_SHUTTING_DOWN
2792          */
2793         if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2794             (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
2795             (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
2796             *ec = VNOVOL;
2797             vp = NULL;
2798             break;
2799         }
2800
2801         /*
2802          * short circuit with VOFFLINE in the following circumstances:
2803          *
2804          *   - VOL_STATE_UNATTACHED
2805          */
2806        if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2807            if (vp->specialStatus) {
2808                *ec = vp->specialStatus;
2809            } else {
2810                *ec = VOFFLINE;
2811            }
2812            vp = NULL;
2813            break;
2814        }
2815
2816         /* allowable states:
2817          *   - PREATTACHED
2818          *   - ATTACHED
2819          *   - SALVAGING
2820          */
2821
2822         if (vp->salvage.requested) {
2823             VUpdateSalvagePriority_r(vp);
2824         }
2825
2826         if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2827             avp = VAttachVolumeByVp_r(ec, vp, 0);
2828             if (avp) {
2829                 if (vp != avp) {
2830                     /* VAttachVolumeByVp_r can return a pointer
2831                      * != the vp passed to it under certain
2832                      * conditions; make sure we don't leak
2833                      * reservations if that happens */
2834                     vp = avp;
2835                     VCancelReservation_r(rvp);
2836                     rvp = avp;
2837                     VCreateReservation_r(rvp);
2838                 }
2839                 VPutVolume_r(avp);
2840             }
2841             if (*ec) {
2842                 int endloop = 0;
2843                 switch (*ec) {
2844                 case VSALVAGING:
2845                     break;
2846                 case VOFFLINE:
2847                     if (!vp->pending_vol_op) {
2848                         endloop = 1;
2849                     }
2850                     break;
2851                 default:
2852                     *ec = VNOVOL;
2853                     endloop = 1;
2854                 }
2855                 if (endloop) {
2856                     vp = NULL;
2857                     break;
2858                 }
2859             }
2860         }
2861
2862         if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2863             (*ec == VSALVAGING)) {
2864             if (client_ec) {
2865                 /* see CheckVnode() in afsfileprocs.c for an explanation
2866                  * of this error code logic */
2867                 afs_uint32 now = FT_ApproxTime();
2868                 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2869                     *client_ec = VBUSY;
2870                 } else {
2871                     *client_ec = VRESTARTING;
2872                 }
2873             }
2874             *ec = VSALVAGING;
2875             vp = NULL;
2876             break;
2877         }
2878 #endif
2879
2880         LoadVolumeHeader(ec, vp);
2881         if (*ec) {
2882             VGET_CTR_INC(V6);
2883             /* Only log the error if it was a totally unexpected error.  Simply
2884              * a missing inode is likely to be caused by the volume being deleted */
2885             if (errno != ENXIO || LogLevel)
2886                 Log("Volume %u: couldn't reread volume header\n",
2887                     vp->hashid);
2888 #ifdef AFS_DEMAND_ATTACH_FS
2889             if (programType == fileServer) {
2890                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2891             } else {
2892                 FreeVolume(vp);
2893                 vp = NULL;
2894             }
2895 #else /* AFS_DEMAND_ATTACH_FS */
2896             FreeVolume(vp);
2897             vp = NULL;
2898 #endif /* AFS_DEMAND_ATTACH_FS */
2899             break;
2900         }
2901
2902 #ifdef AFS_DEMAND_ATTACH_FS
2903         /*
2904          * this test MUST happen after the volume header is loaded
2905          */
2906         
2907          /* only valid before/during demand attachment */
2908          assert(!vp->pending_vol_op || vp->pending_vol_op != FSSYNC_VolOpRunningUnknown);
2909         
2910          /* deny getvolume due to running mutually exclusive vol op */
2911          if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
2912            /* 
2913             * volume cannot remain online during this volume operation.
2914             * notify client. 
2915             */
2916            if (vp->specialStatus) {
2917                /*
2918                 * special status codes outrank normal VOFFLINE code
2919                 */
2920                *ec = vp->specialStatus;
2921                if (client_ec) {
2922                    *client_ec = vp->specialStatus;
2923                }
2924            } else {
2925                if (client_ec) {
2926                    /* see CheckVnode() in afsfileprocs.c for an explanation
2927                     * of this error code logic */
2928                    afs_uint32 now = FT_ApproxTime();
2929                    if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
2930                        *client_ec = VBUSY;
2931                    } else {
2932                        *client_ec = VRESTARTING;
2933                    }
2934                }
2935                *ec = VOFFLINE;
2936            }
2937            VChangeState_r(vp, VOL_STATE_UNATTACHED);
2938            FreeVolumeHeader(vp);
2939            vp = NULL;
2940            break;
2941         }
2942 #endif /* AFS_DEMAND_ATTACH_FS */
2943         
2944         VGET_CTR_INC(V7);
2945         if (vp->shuttingDown) {
2946             VGET_CTR_INC(V8);
2947             *ec = VNOVOL;
2948             vp = NULL;
2949             break;
2950         }
2951
2952         if (programType == fileServer) {
2953             VGET_CTR_INC(V9);
2954             if (vp->goingOffline) {
2955                 VGET_CTR_INC(V10);
2956 #ifdef AFS_DEMAND_ATTACH_FS
2957                 /* wait for the volume to go offline */
2958                 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2959                     VWaitStateChange_r(vp);
2960                 }
2961 #elif defined(AFS_PTHREAD_ENV)
2962                 VOL_CV_WAIT(&vol_put_volume_cond);
2963 #else /* AFS_PTHREAD_ENV */
2964                 LWP_WaitProcess(VPutVolume);
2965 #endif /* AFS_PTHREAD_ENV */
2966                 continue;
2967             }
2968             if (vp->specialStatus) {
2969                 VGET_CTR_INC(V11);
2970                 *ec = vp->specialStatus;
2971             } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
2972                 VGET_CTR_INC(V12);
2973                 *ec = VNOVOL;
2974             } else if (V_inUse(vp) == 0) {
2975                 VGET_CTR_INC(V13);
2976                 *ec = VOFFLINE;
2977             } else {
2978                 VGET_CTR_INC(V14);
2979             }
2980         }
2981         break;
2982     }
2983     VGET_CTR_INC(V15);
2984
2985 #ifdef AFS_DEMAND_ATTACH_FS
2986     /* if no error, bump nUsers */
2987     if (vp) {
2988         vp->nUsers++;
2989         VLRU_UpdateAccess_r(vp);
2990     }
2991     if (rvp) {
2992         VCancelReservation_r(rvp);
2993         rvp = NULL;
2994     }
2995     if (client_ec && !*client_ec) {
2996         *client_ec = *ec;
2997     }
2998 #else /* AFS_DEMAND_ATTACH_FS */
2999     /* if no error, bump nUsers */
3000     if (vp) {
3001         vp->nUsers++;
3002     }
3003     if (client_ec) {
3004         *client_ec = *ec;
3005     }
3006 #endif /* AFS_DEMAND_ATTACH_FS */
3007
3008  not_inited:
3009     assert(vp || *ec);
3010     return vp;
3011 }
3012
3013
3014 /***************************************************/
3015 /* Volume offline/detach routines                  */
3016 /***************************************************/
3017
3018 /* caller MUST hold a heavyweight ref on vp */
3019 #ifdef AFS_DEMAND_ATTACH_FS
3020 void
3021 VTakeOffline_r(register Volume * vp)
3022 {
3023     Error error;
3024
3025     assert(vp->nUsers > 0);
3026     assert(programType == fileServer);
3027
3028     VCreateReservation_r(vp);
3029     VWaitExclusiveState_r(vp);
3030
3031     vp->goingOffline = 1;
3032     V_needsSalvaged(vp) = 1;
3033
3034     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3035     VCancelReservation_r(vp);
3036 }
3037 #else /* AFS_DEMAND_ATTACH_FS */
3038 void
3039 VTakeOffline_r(register Volume * vp)
3040 {
3041     assert(vp->nUsers > 0);
3042     assert(programType == fileServer);
3043
3044     vp->goingOffline = 1;
3045     V_needsSalvaged(vp) = 1;
3046 }
3047 #endif /* AFS_DEMAND_ATTACH_FS */
3048
3049 void
3050 VTakeOffline(register Volume * vp)
3051 {
3052     VOL_LOCK;
3053     VTakeOffline_r(vp);
3054     VOL_UNLOCK;
3055 }
3056
3057 /**
3058  * force a volume offline.
3059  *
3060  * @param[in] vp     volume object pointer
3061  * @param[in] flags  flags (see note below)
3062  *
3063  * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3064  *       used when VUpdateVolume_r needs to call VForceOffline_r
3065  *       (which in turn would normally call VUpdateVolume_r)
3066  *
3067  * @see VUpdateVolume_r
3068  *
3069  * @pre VOL_LOCK must be held.
3070  *      for DAFS, caller must hold ref.
3071  *
3072  * @note for DAFS, it _is safe_ to call this function from an
3073  *       exclusive state
3074  *
3075  * @post needsSalvaged flag is set.
3076  *       for DAFS, salvage is requested.
3077  *       no further references to the volume through the volume 
3078  *       package will be honored.
3079  *       all file descriptor and vnode caches are invalidated.
3080  *
3081  * @warning this is a heavy-handed interface.  it results in
3082  *          a volume going offline regardless of the current 
3083  *          reference count state.
3084  *
3085  * @internal  volume package internal use only
3086  */
3087 void
3088 VForceOffline_r(Volume * vp, int flags)
3089 {
3090     Error error;
3091     if (!V_inUse(vp)) {
3092 #ifdef AFS_DEMAND_ATTACH_FS
3093         VChangeState_r(vp, VOL_STATE_ERROR);
3094 #endif
3095         return;
3096     }
3097
3098     strcpy(V_offlineMessage(vp),
3099            "Forced offline due to internal error: volume needs to be salvaged");
3100     Log("Volume %u forced offline:  it needs salvaging!\n", V_id(vp));
3101
3102     V_inUse(vp) = 0;
3103     vp->goingOffline = 0;
3104     V_needsSalvaged(vp) = 1;
3105     if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3106         VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3107     }
3108
3109 #ifdef AFS_DEMAND_ATTACH_FS
3110     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3111 #endif /* AFS_DEMAND_ATTACH_FS */
3112
3113 #ifdef AFS_PTHREAD_ENV
3114     assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3115 #else /* AFS_PTHREAD_ENV */
3116     LWP_NoYieldSignal(VPutVolume);
3117 #endif /* AFS_PTHREAD_ENV */
3118
3119     VReleaseVolumeHandles_r(vp);
3120 }
3121
3122 /**
3123  * force a volume offline.
3124  *
3125  * @param[in] vp  volume object pointer
3126  *
3127  * @see VForceOffline_r
3128  */
3129 void
3130 VForceOffline(Volume * vp)
3131 {
3132     VOL_LOCK;
3133     VForceOffline_r(vp, 0);
3134     VOL_UNLOCK;
3135 }
3136
3137 /* The opposite of VAttachVolume.  The volume header is written to disk, with
3138    the inUse bit turned off.  A copy of the header is maintained in memory,
3139    however (which is why this is VOffline, not VDetach).
3140  */
3141 void
3142 VOffline_r(Volume * vp, char *message)
3143 {
3144     Error error;
3145     VolumeId vid = V_id(vp);
3146
3147     assert(programType != volumeUtility);
3148     if (!V_inUse(vp)) {
3149         VPutVolume_r(vp);
3150         return;
3151     }
3152     if (V_offlineMessage(vp)[0] == '\0')
3153         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3154     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3155
3156     vp->goingOffline = 1;
3157 #ifdef AFS_DEMAND_ATTACH_FS
3158     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3159     VCreateReservation_r(vp);
3160     VPutVolume_r(vp);
3161
3162     /* wait for the volume to go offline */
3163     if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3164         VWaitStateChange_r(vp);
3165     }
3166     VCancelReservation_r(vp);
3167 #else /* AFS_DEMAND_ATTACH_FS */
3168     VPutVolume_r(vp);
3169     vp = VGetVolume_r(&error, vid);     /* Wait for it to go offline */
3170     if (vp)                     /* In case it was reattached... */
3171         VPutVolume_r(vp);
3172 #endif /* AFS_DEMAND_ATTACH_FS */
3173 }
3174
3175 #ifdef AFS_DEMAND_ATTACH_FS
3176 /**
3177  * Take a volume offline in order to perform a volume operation.
3178  *
3179  * @param[inout] ec       address in which to store error code
3180  * @param[in]    vp       volume object pointer
3181  * @param[in]    message  volume offline status message
3182  *
3183  * @pre
3184  *    - VOL_LOCK is held
3185  *    - caller MUST hold a heavyweight ref on vp
3186  *
3187  * @post
3188  *    - volume is taken offline
3189  *    - if possible, volume operation is promoted to running state
3190  *    - on failure, *ec is set to nonzero
3191  *
3192  * @note Although this function does not return any value, it may
3193  *       still fail to promote our pending volume operation to
3194  *       a running state.  Any caller MUST check the value of *ec,
3195  *       and MUST NOT blindly assume success.
3196  *
3197  * @warning if the caller does not hold a lightweight ref on vp,
3198  *          then it MUST NOT reference vp after this function
3199  *          returns to the caller.
3200  *
3201  * @internal volume package internal use only
3202  */
3203 void
3204 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3205 {
3206     assert(vp->pending_vol_op);
3207     if (!V_inUse(vp)) {
3208         VPutVolume_r(vp);
3209         *ec = 1;
3210         return;
3211     }
3212     if (V_offlineMessage(vp)[0] == '\0')
3213         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3214     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3215
3216     vp->goingOffline = 1;
3217     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3218     VCreateReservation_r(vp);
3219     VPutVolume_r(vp);
3220
3221     /* Wait for the volume to go offline */
3222     while (!VIsOfflineState(V_attachState(vp))) {
3223         /* do not give corrupted volumes to the volserver */
3224         if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3225            *ec = 1; 
3226            goto error;
3227         }
3228         VWaitStateChange_r(vp);
3229     }
3230     *ec = 0; 
3231  error:
3232     VCancelReservation_r(vp);
3233 }
3234 #endif /* AFS_DEMAND_ATTACH_FS */
3235
3236 void
3237 VOffline(Volume * vp, char *message)
3238 {
3239     VOL_LOCK;
3240     VOffline_r(vp, message);
3241     VOL_UNLOCK;
3242 }
3243
3244 /* This gets used for the most part by utility routines that don't want
3245  * to keep all the volume headers around.  Generally, the file server won't
3246  * call this routine, because then the offline message in the volume header
3247  * (or other information) won't be available to clients. For NAMEI, also
3248  * close the file handles.  However, the fileserver does call this during
3249  * an attach following a volume operation.
3250  */
3251 void
3252 VDetachVolume_r(Error * ec, Volume * vp)
3253 {
3254     VolumeId volume;
3255     struct DiskPartition64 *tpartp;
3256     int notifyServer = 0;
3257     int  useDone = FSYNC_VOL_ON;
3258
3259     *ec = 0;                    /* always "succeeds" */
3260     if (programType == volumeUtility) {
3261         notifyServer = vp->needsPutBack;
3262         if (V_destroyMe(vp) == DESTROY_ME)
3263             useDone = FSYNC_VOL_DONE;
3264 #ifdef AFS_DEMAND_ATTACH_FS
3265         else if (!V_blessed(vp) || !V_inService(vp))
3266             useDone = FSYNC_VOL_LEAVE_OFF;
3267 #endif
3268     }
3269     tpartp = vp->partition;
3270     volume = V_id(vp);
3271     DeleteVolumeFromHashTable(vp);
3272     vp->shuttingDown = 1;
3273 #ifdef AFS_DEMAND_ATTACH_FS
3274     DeleteVolumeFromVByPList_r(vp);
3275     VLRU_Delete_r(vp);
3276     VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3277 #else
3278     if (programType != fileServer) 
3279         V_inUse(vp) = 0;
3280 #endif /* AFS_DEMAND_ATTACH_FS */
3281     VPutVolume_r(vp);
3282     /* Will be detached sometime in the future--this is OK since volume is offline */
3283
3284     /* XXX the following code should really be moved to VCheckDetach() since the volume
3285      * is not technically detached until the refcounts reach zero
3286      */
3287 #ifdef FSSYNC_BUILD_CLIENT
3288     if (programType == volumeUtility && notifyServer) {
3289         /* 
3290          * Note:  The server is not notified in the case of a bogus volume 
3291          * explicitly to make it possible to create a volume, do a partial 
3292          * restore, then abort the operation without ever putting the volume 
3293          * online.  This is essential in the case of a volume move operation 
3294          * between two partitions on the same server.  In that case, there 
3295          * would be two instances of the same volume, one of them bogus, 
3296          * which the file server would attempt to put on line 
3297          */
3298         FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3299         /* XXX this code path is only hit by volume utilities, thus
3300          * V_BreakVolumeCallbacks will always be NULL.  if we really
3301          * want to break callbacks in this path we need to use FSYNC_VolOp() */
3302 #ifdef notdef
3303         /* Dettaching it so break all callbacks on it */
3304         if (V_BreakVolumeCallbacks) {
3305             Log("volume %u detached; breaking all call backs\n", volume);
3306             (*V_BreakVolumeCallbacks) (volume);
3307         }
3308 #endif
3309     }
3310 #endif /* FSSYNC_BUILD_CLIENT */
3311 }
3312
3313 void
3314 VDetachVolume(Error * ec, Volume * vp)
3315 {
3316     VOL_LOCK;
3317     VDetachVolume_r(ec, vp);
3318     VOL_UNLOCK;
3319 }
3320
3321
3322 /***************************************************/
3323 /* Volume fd/inode handle closing routines         */
3324 /***************************************************/
3325
3326 /* For VDetachVolume, we close all cached file descriptors, but keep
3327  * the Inode handles in case we need to read from a busy volume.
3328  */
3329 /* for demand attach, caller MUST hold ref count on vp */
3330 static void
3331 VCloseVolumeHandles_r(Volume * vp)
3332 {
3333 #ifdef AFS_DEMAND_ATTACH_FS
3334     VolState state_save;
3335
3336     state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3337 #endif
3338
3339     /* demand attach fs
3340      *
3341      * XXX need to investigate whether we can perform
3342      * DFlushVolume outside of vol_glock_mutex... 
3343      *
3344      * VCloseVnodeFiles_r drops the glock internally */
3345     DFlushVolume(V_id(vp));
3346     VCloseVnodeFiles_r(vp);
3347
3348 #ifdef AFS_DEMAND_ATTACH_FS
3349     VOL_UNLOCK;
3350 #endif
3351
3352     /* Too time consuming and unnecessary for the volserver */
3353     if (programType != volumeUtility) {
3354         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3355         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3356         IH_CONDSYNC(vp->diskDataHandle);
3357 #ifdef AFS_NT40_ENV
3358         IH_CONDSYNC(vp->linkHandle);
3359 #endif /* AFS_NT40_ENV */
3360     }
3361
3362     IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3363     IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3364     IH_REALLYCLOSE(vp->diskDataHandle);
3365     IH_REALLYCLOSE(vp->linkHandle);
3366
3367 #ifdef AFS_DEMAND_ATTACH_FS
3368     VOL_LOCK;
3369     VChangeState_r(vp, state_save);
3370 #endif
3371 }
3372
3373 /* For both VForceOffline and VOffline, we close all relevant handles.
3374  * For VOffline, if we re-attach the volume, the files may possible be
3375  * different than before. 
3376  */
3377 /* for demand attach, caller MUST hold a ref count on vp */
3378 static void
3379 VReleaseVolumeHandles_r(Volume * vp)
3380 {
3381 #ifdef AFS_DEMAND_ATTACH_FS
3382     VolState state_save;
3383
3384     state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3385 #endif
3386
3387     /* XXX need to investigate whether we can perform
3388      * DFlushVolume outside of vol_glock_mutex... */
3389     DFlushVolume(V_id(vp));
3390
3391     VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3392
3393 #ifdef AFS_DEMAND_ATTACH_FS
3394     VOL_UNLOCK;
3395 #endif
3396
3397     /* Too time consuming and unnecessary for the volserver */
3398     if (programType != volumeUtility) {
3399         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3400         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3401         IH_CONDSYNC(vp->diskDataHandle);
3402 #ifdef AFS_NT40_ENV
3403         IH_CONDSYNC(vp->linkHandle);
3404 #endif /* AFS_NT40_ENV */
3405     }
3406
3407     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3408     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3409     IH_RELEASE(vp->diskDataHandle);
3410     IH_RELEASE(vp->linkHandle);
3411
3412 #ifdef AFS_DEMAND_ATTACH_FS
3413     VOL_LOCK;
3414     VChangeState_r(vp, state_save);
3415 #endif
3416 }
3417
3418
3419 /***************************************************/
3420 /* Volume write and fsync routines                 */
3421 /***************************************************/
3422
3423 void
3424 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3425 {
3426 #ifdef AFS_DEMAND_ATTACH_FS
3427     VolState state_save;
3428
3429     if (flags & VOL_UPDATE_WAIT) {
3430         VCreateReservation_r(vp);
3431         VWaitExclusiveState_r(vp);
3432     }
3433 #endif
3434
3435     *ec = 0;
3436     if (programType == fileServer)
3437         V_uniquifier(vp) =
3438             (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3439              200 : V_nextVnodeUnique(vp));
3440
3441 #ifdef AFS_DEMAND_ATTACH_FS
3442     state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3443     VOL_UNLOCK;
3444 #endif
3445
3446     WriteVolumeHeader_r(ec, vp);
3447
3448 #ifdef AFS_DEMAND_ATTACH_FS
3449     VOL_LOCK;
3450     VChangeState_r(vp, state_save);
3451     if (flags & VOL_UPDATE_WAIT) {
3452         VCancelReservation_r(vp);
3453     }
3454 #endif
3455
3456     if (*ec) {
3457         Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3458             V_id(vp), V_name(vp));
3459         /* try to update on-disk header, 
3460          * while preventing infinite recursion */
3461         if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3462             VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3463         }
3464     }
3465 }
3466
3467 void
3468 VUpdateVolume(Error * ec, Volume * vp)
3469 {
3470     VOL_LOCK;
3471     VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3472     VOL_UNLOCK;
3473 }
3474
3475 void
3476 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3477 {
3478     FdHandle_t *fdP;
3479     int code;
3480 #ifdef AFS_DEMAND_ATTACH_FS
3481     VolState state_save;
3482 #endif
3483
3484     if (flags & VOL_SYNC_WAIT) {
3485         VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3486     } else {
3487         VUpdateVolume_r(ec, vp, 0);
3488     }
3489     if (!*ec) {
3490 #ifdef AFS_DEMAND_ATTACH_FS
3491         state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3492         VOL_UNLOCK;
3493 #endif
3494         fdP = IH_OPEN(V_diskDataHandle(vp));
3495         assert(fdP != NULL);
3496         code = FDH_SYNC(fdP);
3497         assert(code == 0);
3498         FDH_CLOSE(fdP);
3499 #ifdef AFS_DEMAND_ATTACH_FS
3500         VOL_LOCK;
3501         VChangeState_r(vp, state_save);
3502 #endif
3503     }
3504 }
3505
3506 void
3507 VSyncVolume(Error * ec, Volume * vp)
3508 {
3509     VOL_LOCK;
3510     VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3511     VOL_UNLOCK;
3512 }
3513
3514
3515 /***************************************************/
3516 /* Volume dealloaction routines                    */
3517 /***************************************************/
3518
3519 #ifdef AFS_DEMAND_ATTACH_FS
3520 static void
3521 FreeVolume(Volume * vp)
3522 {
3523     /* free the heap space, iff it's safe.
3524      * otherwise, pull it out of the hash table, so it
3525      * will get deallocated when all refs to it go away */
3526     if (!VCheckFree(vp)) {
3527         DeleteVolumeFromHashTable(vp);
3528         DeleteVolumeFromVByPList_r(vp);
3529
3530         /* make sure we invalidate the header cache entry */
3531         FreeVolumeHeader(vp);
3532     }
3533 }
3534 #endif /* AFS_DEMAND_ATTACH_FS */
3535
3536 static void
3537 ReallyFreeVolume(Volume * vp)
3538 {
3539     int i;
3540     if (!vp)
3541         return;
3542 #ifdef AFS_DEMAND_ATTACH_FS
3543     /* debug */
3544     VChangeState_r(vp, VOL_STATE_FREED);
3545     if (vp->pending_vol_op)
3546         free(vp->pending_vol_op);
3547 #endif /* AFS_DEMAND_ATTACH_FS */
3548     for (i = 0; i < nVNODECLASSES; i++)
3549         if (vp->vnodeIndex[i].bitmap)
3550             free(vp->vnodeIndex[i].bitmap);
3551     FreeVolumeHeader(vp);
3552 #ifndef AFS_DEMAND_ATTACH_FS
3553     DeleteVolumeFromHashTable(vp);
3554 #endif /* AFS_DEMAND_ATTACH_FS */
3555     free(vp);
3556 }
3557
3558 /* check to see if we should shutdown this volume
3559  * returns 1 if volume was freed, 0 otherwise */
3560 #ifdef AFS_DEMAND_ATTACH_FS
3561 static int
3562 VCheckDetach(register Volume * vp)
3563 {
3564     int ret = 0;
3565     Error ec = 0;
3566
3567     if (vp->nUsers || vp->nWaiters)
3568         return ret;
3569
3570     if (vp->shuttingDown) {
3571         ret = 1;
3572         if ((programType != fileServer) &&
3573             (V_inUse(vp) == programType) &&
3574             ((V_checkoutMode(vp) == V_VOLUPD) ||
3575              (V_checkoutMode(vp) == V_SECRETLY) ||
3576              ((V_checkoutMode(vp) == V_CLONE) &&
3577               (VolumeWriteable(vp))))) {
3578             V_inUse(vp) = 0;
3579             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3580             if (ec) {
3581                 Log("VCheckDetach: volume header update for volume %u "
3582                     "failed with errno %d\n", vp->hashid, errno);
3583             }
3584         }
3585         VReleaseVolumeHandles_r(vp);
3586         VCheckSalvage(vp);
3587         ReallyFreeVolume(vp);
3588         if (programType == fileServer) {
3589             assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3590         }
3591     }
3592     return ret;
3593 }
3594 #else /* AFS_DEMAND_ATTACH_FS */
3595 static int
3596 VCheckDetach(register Volume * vp)
3597 {
3598     int ret = 0;
3599     Error ec = 0;
3600
3601     if (vp->nUsers)
3602         return ret;
3603
3604     if (vp->shuttingDown) {
3605         ret = 1;
3606         if ((programType != fileServer) &&
3607             (V_inUse(vp) == programType) &&
3608             ((V_checkoutMode(vp) == V_VOLUPD) ||
3609              (V_checkoutMode(vp) == V_SECRETLY) ||
3610              ((V_checkoutMode(vp) == V_CLONE) &&
3611               (VolumeWriteable(vp))))) {
3612             V_inUse(vp) = 0;
3613             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3614             if (ec) {
3615                 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3616                     vp->hashid, errno);
3617             }
3618         }
3619         VReleaseVolumeHandles_r(vp);
3620         ReallyFreeVolume(vp);
3621         if (programType == fileServer) {
3622 #if defined(AFS_PTHREAD_ENV)
3623             assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3624 #else /* AFS_PTHREAD_ENV */
3625             LWP_NoYieldSignal(VPutVolume);
3626 #endif /* AFS_PTHREAD_ENV */
3627         }
3628     }
3629     return ret;
3630 }
3631 #endif /* AFS_DEMAND_ATTACH_FS */
3632
3633 /* check to see if we should offline this volume
3634  * return 1 if volume went offline, 0 otherwise */
3635 #ifdef AFS_DEMAND_ATTACH_FS
3636 static int
3637 VCheckOffline(register Volume * vp)
3638 {
3639     int ret = 0;
3640
3641     if (vp->goingOffline && !vp->nUsers) {
3642         Error error;
3643         assert(programType == fileServer);
3644         assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3645                (V_attachState(vp) != VOL_STATE_FREED) &&
3646                (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3647                (V_attachState(vp) != VOL_STATE_UNATTACHED));
3648
3649         /* valid states:
3650          *
3651          * VOL_STATE_GOING_OFFLINE
3652          * VOL_STATE_SHUTTING_DOWN
3653          * VIsErrorState(V_attachState(vp))
3654          * VIsExclusiveState(V_attachState(vp))
3655          */
3656
3657         VCreateReservation_r(vp);
3658         VChangeState_r(vp, VOL_STATE_OFFLINING);
3659
3660         ret = 1;
3661         /* must clear the goingOffline flag before we drop the glock */
3662         vp->goingOffline = 0;
3663         V_inUse(vp) = 0;
3664
3665         VLRU_Delete_r(vp);
3666
3667         /* perform async operations */
3668         VUpdateVolume_r(&error, vp, 0);
3669         VCloseVolumeHandles_r(vp);
3670
3671         if (LogLevel) {
3672             Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3673                 V_name(vp));
3674             if (V_offlineMessage(vp)[0])
3675                 Log(" (%s)", V_offlineMessage(vp));
3676             Log("\n");
3677         }
3678
3679         /* invalidate the volume header cache entry */
3680         FreeVolumeHeader(vp);
3681
3682         /* if nothing changed state to error or salvaging,
3683          * drop state to unattached */
3684         if (!VIsErrorState(V_attachState(vp))) {
3685             VChangeState_r(vp, VOL_STATE_UNATTACHED);
3686         }
3687         VCancelReservation_r(vp);
3688         /* no usage of vp is safe beyond this point */
3689     }
3690     return ret;
3691 }
3692 #else /* AFS_DEMAND_ATTACH_FS */
3693 static int
3694 VCheckOffline(register Volume * vp)
3695 {
3696     int ret = 0;
3697
3698     if (vp->goingOffline && !vp->nUsers) {
3699         Error error;
3700         assert(programType == fileServer);
3701
3702         ret = 1;
3703         vp->goingOffline = 0;
3704         V_inUse(vp) = 0;
3705         VUpdateVolume_r(&error, vp, 0);
3706         VCloseVolumeHandles_r(vp);
3707         if (LogLevel) {
3708             Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3709                 V_name(vp));
3710             if (V_offlineMessage(vp)[0])
3711                 Log(" (%s)", V_offlineMessage(vp));
3712             Log("\n");
3713         }
3714         FreeVolumeHeader(vp);
3715 #ifdef AFS_PTHREAD_ENV
3716         assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3717 #else /* AFS_PTHREAD_ENV */
3718         LWP_NoYieldSignal(VPutVolume);
3719 #endif /* AFS_PTHREAD_ENV */
3720     }
3721     return ret;
3722 }
3723 #endif /* AFS_DEMAND_ATTACH_FS */
3724
3725 /***************************************************/
3726 /* demand attach fs ref counting routines          */
3727 /***************************************************/
3728
3729 #ifdef AFS_DEMAND_ATTACH_FS
3730 /* the following two functions handle reference counting for
3731  * asynchronous operations on volume structs.
3732  *
3733  * their purpose is to prevent a VDetachVolume or VShutdown
3734  * from free()ing the Volume struct during an async i/o op */
3735
3736 /* register with the async volume op ref counter */
3737 /* VCreateReservation_r moved into inline code header because it 
3738  * is now needed in vnode.c -- tkeiser 11/20/2007 
3739  */
3740
3741 /**
3742  * decrement volume-package internal refcount.
3743  *
3744  * @param vp  volume object pointer
3745  *
3746  * @internal volume package internal use only
3747  *
3748  * @pre 
3749  *    @arg VOL_LOCK is held
3750  *    @arg lightweight refcount held
3751  *
3752  * @post volume waiters refcount is decremented; volume may
3753  *       have been deallocated/shutdown/offlined/salvaged/
3754  *       whatever during the process
3755  *
3756  * @warning once you have tossed your last reference (you can acquire
3757  *          lightweight refs recursively) it is NOT SAFE to reference
3758  *          a volume object pointer ever again
3759  *
3760  * @see VCreateReservation_r
3761  *
3762  * @note DEMAND_ATTACH_FS only
3763  */
3764 void
3765 VCancelReservation_r(Volume * vp)
3766 {
3767     assert(--vp->nWaiters >= 0);
3768     if (vp->nWaiters == 0) {
3769         VCheckOffline(vp);
3770         if (!VCheckDetach(vp)) {
3771             VCheckSalvage(vp);
3772             VCheckFree(vp);
3773         }
3774     }
3775 }
3776
3777 /* check to see if we should free this volume now
3778  * return 1 if volume was freed, 0 otherwise */
3779 static int
3780 VCheckFree(Volume * vp)
3781 {
3782     int ret = 0;
3783     if ((vp->nUsers == 0) &&
3784         (vp->nWaiters == 0) &&
3785         !(V_attachFlags(vp) & (VOL_IN_HASH | 
3786                                VOL_ON_VBYP_LIST | 
3787                                VOL_IS_BUSY |
3788                                VOL_ON_VLRU))) {
3789         ReallyFreeVolume(vp);
3790         ret = 1;
3791     }
3792     return ret;
3793 }
3794 #endif /* AFS_DEMAND_ATTACH_FS */
3795
3796
3797 /***************************************************/
3798 /* online volume operations routines               */
3799 /***************************************************/
3800
3801 #ifdef AFS_DEMAND_ATTACH_FS
3802 /**
3803  * register a volume operation on a given volume.
3804  *
3805  * @param[in] vp       volume object
3806  * @param[in] vopinfo  volume operation info object
3807  *
3808  * @pre VOL_LOCK is held
3809  *
3810  * @post volume operation info object attached to volume object.
3811  *       volume operation statistics updated.
3812  *
3813  * @note by "attached" we mean a copy of the passed in object is made
3814  *
3815  * @internal volume package internal use only
3816  */
3817 int
3818 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3819 {
3820     FSSYNC_VolOp_info * info;
3821
3822     /* attach a vol op info node to the volume struct */
3823     info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3824     assert(info != NULL);
3825     memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3826     vp->pending_vol_op = info;
3827
3828     /* update stats */
3829     vp->stats.last_vol_op = FT_ApproxTime();
3830     vp->stats.vol_ops++;
3831     IncUInt64(&VStats.vol_ops);
3832
3833     return 0;
3834 }
3835
3836 /**
3837  * deregister the volume operation attached to this volume.
3838  *
3839  * @param[in] vp  volume object pointer
3840  *
3841  * @pre VOL_LOCK is held
3842  *
3843  * @post the volume operation info object is detached from the volume object
3844  *
3845  * @internal volume package internal use only
3846  */
3847 int
3848 VDeregisterVolOp_r(Volume * vp)
3849 {
3850     if (vp->pending_vol_op) {
3851         free(vp->pending_vol_op);
3852         vp->pending_vol_op = NULL;
3853     }
3854     return 0;
3855 }
3856 #endif /* AFS_DEMAND_ATTACH_FS */
3857
3858 /**
3859  * determine whether it is safe to leave a volume online during
3860  * the volume operation described by the vopinfo object.
3861  *
3862  * @param[in] vp        volume object
3863  * @param[in] vopinfo   volume operation info object
3864  *
3865  * @return whether it is safe to leave volume online
3866  *    @retval 0  it is NOT SAFE to leave the volume online
3867  *    @retval 1  it is safe to leave the volume online during the operation
3868  *
3869  * @pre
3870  *    @arg VOL_LOCK is held
3871  *    @arg disk header attached to vp (heavyweight ref on vp will guarantee
3872  *         this condition is met)
3873  *
3874  * @internal volume package internal use only
3875  */
3876 int
3877 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3878 {
3879     return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
3880             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3881             (vopinfo->com.reason == V_READONLY ||
3882              (!VolumeWriteable(vp) &&
3883               (vopinfo->com.reason == V_CLONE ||
3884                vopinfo->com.reason == V_DUMP)))));
3885 }
3886
3887 /**
3888  * determine whether VBUSY should be set during this volume operation.
3889  *
3890  * @param[in] vp        volume object
3891  * @param[in] vopinfo   volume operation info object
3892  *
3893  * @return whether VBUSY should be set
3894  *   @retval 0  VBUSY does NOT need to be set
3895  *   @retval 1  VBUSY SHOULD be set
3896  *
3897  * @pre VOL_LOCK is held
3898  *
3899  * @internal volume package internal use only
3900  */
3901 int
3902 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3903 {
3904     return ((vopinfo->com.command == FSYNC_VOL_OFF &&
3905             vopinfo->com.reason == FSYNC_SALVAGE) ||
3906             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3907             (vopinfo->com.reason == V_CLONE ||
3908              vopinfo->com.reason == V_DUMP)));
3909 }
3910
3911
3912 /***************************************************/
3913 /* online salvager routines                        */
3914 /***************************************************/
3915 #if defined(AFS_DEMAND_ATTACH_FS)
3916 #define SALVAGE_PRIO_UPDATE_INTERVAL 3      /**< number of seconds between prio updates */
3917 #define SALVAGE_COUNT_MAX 16                /**< number of online salvages we
3918                                              *   allow before moving the volume
3919                                              *   into a permanent error state
3920                                              *
3921                                              *   once this threshold is reached,
3922                                              *   the operator will have to manually
3923                                              *   issue a 'bos salvage' to bring
3924                                              *   the volume back online
3925                                              */
3926
3927 /**
3928  * check whether a salvage needs to be performed on this volume.
3929  *
3930  * @param[in] vp   pointer to volume object
3931  *
3932  * @return status code
3933  *    @retval 0 no salvage scheduled
3934  *    @retval 1 a salvage has been scheduled with the salvageserver
3935  *
3936  * @pre VOL_LOCK is held
3937  *
3938  * @post if salvage request flag is set and nUsers and nWaiters are zero,
3939  *       then a salvage will be requested
3940  *
3941  * @note this is one of the event handlers called by VCancelReservation_r
3942  *
3943  * @see VCancelReservation_r
3944  *
3945  * @internal volume package internal use only.
3946  */
3947 static int
3948 VCheckSalvage(register Volume * vp)
3949 {
3950     int ret = 0;
3951 #ifdef SALVSYNC_BUILD_CLIENT
3952     if (vp->nUsers || vp->nWaiters)
3953         return ret;
3954     if (vp->salvage.requested) {
3955         VScheduleSalvage_r(vp);
3956         ret = 1;
3957     }
3958 #endif /* SALVSYNC_BUILD_CLIENT */
3959     return ret;
3960 }
3961
3962 /**
3963  * request volume salvage.
3964  *
3965  * @param[out] ec      computed client error code
3966  * @param[in]  vp      volume object pointer
3967  * @param[in]  reason  reason code (passed to salvageserver via SALVSYNC)
3968  * @param[in]  flags   see flags note below
3969  *
3970  * @note flags:
3971  *       VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry 
3972  *                                     to be invalidated.
3973  *
3974  * @pre VOL_LOCK is held.
3975  *
3976  * @post volume state is changed.
3977  *       for fileserver, salvage will be requested once refcount reaches zero.
3978  *
3979  * @return operation status code
3980  *   @retval 0  volume salvage will occur
3981  *   @retval 1  volume salvage could not be scheduled
3982  *
3983  * @note DAFS fileserver only
3984  *
3985  * @note this call does not synchronously schedule a volume salvage.  rather,
3986  *       it sets volume state so that when volume refcounts reach zero, a
3987  *       volume salvage will occur.  by "refcounts", we mean both nUsers and 
3988  *       nWaiters must be zero.
3989  *
3990  * @internal volume package internal use only.
3991  */
3992 int
3993 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
3994 {
3995     int code = 0;
3996     /*
3997      * for DAFS volume utilities, transition to error state
3998      * (at some point in the future, we should consider
3999      *  making volser talk to salsrv)
4000      */
4001     if (programType != fileServer) {
4002         VChangeState_r(vp, VOL_STATE_ERROR);
4003         *ec = VSALVAGE;
4004         return 1;
4005     }
4006
4007     if (!vp->salvage.requested) {
4008         vp->salvage.requested = 1;
4009         vp->salvage.reason = reason;
4010         vp->stats.last_salvage = FT_ApproxTime();
4011         if (VIsSalvager(V_inUse(vp))) {
4012             Log("VRequestSalvage: volume %u appears to be salvaging, but we\n", vp->hashid);
4013             Log("  didn't request a salvage. Forcing it offline waiting for the\n");
4014             Log("  salvage to finish; if you are sure no salvage is running,\n");
4015             Log("  run a salvage manually.\n");
4016
4017             /* make sure neither VScheduleSalvage_r nor
4018              * VUpdateSalvagePriority_r try to schedule another salvage */
4019             vp->salvage.requested = vp->salvage.scheduled = 0;
4020
4021             /* these stats aren't correct, but doing this makes them
4022              * slightly closer to being correct */
4023             vp->stats.salvages++;
4024             vp->stats.last_salvage_req = FT_ApproxTime();
4025             IncUInt64(&VStats.salvages);
4026
4027             VChangeState_r(vp, VOL_STATE_ERROR);
4028             *ec = VSALVAGE;
4029             code = 1;
4030
4031         } else if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4032             VChangeState_r(vp, VOL_STATE_SALVAGING);
4033             *ec = VSALVAGING;
4034         } else {
4035             Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4036             VChangeState_r(vp, VOL_STATE_ERROR);
4037             *ec = VSALVAGE;
4038             code = 1;
4039         }
4040         if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4041             /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader() 
4042                so that the the next VAttachVolumeByVp_r() invocation 
4043                of attach2() will pull in a cached header 
4044                entry and fail, then load a fresh one from disk and attach 
4045                it to the volume.             
4046             */
4047             FreeVolumeHeader(vp);
4048         }
4049     }
4050     return code;
4051 }
4052
4053 /**
4054  * update salvageserver scheduling priority for a volume.
4055  *
4056  * @param[in] vp  pointer to volume object
4057  *
4058  * @return operation status
4059  *   @retval 0  success
4060  *   @retval 1  request denied, or SALVSYNC communications failure
4061  *
4062  * @pre VOL_LOCK is held.
4063  *
4064  * @post in-core salvage priority counter is incremented.  if at least
4065  *       SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4066  *       last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4067  *       to update its priority queue.  if no salvage is scheduled,
4068  *       this function is a no-op.
4069  *
4070  * @note DAFS fileserver only
4071  *
4072  * @note this should be called whenever a VGetVolume fails due to a 
4073  *       pending salvage request
4074  *
4075  * @todo should set exclusive state and drop glock around salvsync call
4076  *
4077  * @internal volume package internal use only.
4078  */
4079 static int
4080 VUpdateSalvagePriority_r(Volume * vp)
4081 {
4082     int code, ret=0;
4083     afs_uint32 now;
4084
4085 #ifdef SALVSYNC_BUILD_CLIENT
4086     vp->salvage.prio++;
4087     now = FT_ApproxTime();
4088
4089     /* update the salvageserver priority queue occasionally so that
4090      * frequently requested volumes get moved to the head of the queue 
4091      */
4092     if ((vp->salvage.scheduled) &&
4093         (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4094         code = SALVSYNC_SalvageVolume(vp->hashid,
4095                                       VPartitionPath(vp->partition),
4096                                       SALVSYNC_RAISEPRIO,
4097                                       vp->salvage.reason,
4098                                       vp->salvage.prio,
4099                                       NULL);
4100         vp->stats.last_salvage_req = now;
4101         if (code != SYNC_OK) {
4102             ret = 1;
4103         }
4104     }
4105 #endif /* SALVSYNC_BUILD_CLIENT */
4106     return ret;
4107 }
4108
4109
4110 /**
4111  * schedule a salvage with the salvage server.
4112  *
4113  * @param[in] vp  pointer to volume object
4114  *
4115  * @return operation status
4116  *    @retval 0 salvage scheduled successfully
4117  *    @retval 1 salvage not scheduled, or SALVSYNC com error
4118  *
4119  * @pre 
4120  *    @arg VOL_LOCK is held.
4121  *    @arg nUsers and nWaiters should be zero.
4122  *
4123  * @post salvageserver is sent a salvage request
4124  *
4125  * @note DAFS fileserver only
4126  *
4127  * @internal volume package internal use only.
4128  */
4129 static int
4130 VScheduleSalvage_r(Volume * vp)
4131 {
4132     int code, ret=0;
4133 #ifdef SALVSYNC_BUILD_CLIENT
4134     VolState state_save;
4135     VThreadOptions_t * thread_opts;
4136     char partName[16];
4137
4138     if (vp->nWaiters || vp->nUsers) {
4139         return 1;
4140     }
4141
4142     /* prevent endless salvage,attach,salvage,attach,... loops */
4143     if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4144         return 1;
4145
4146     /*
4147      * don't perform salvsync ops on certain threads
4148      */
4149     thread_opts = pthread_getspecific(VThread_key);
4150     if (thread_opts == NULL) {
4151         thread_opts = &VThread_defaults;
4152     }
4153     if (thread_opts->disallow_salvsync) {
4154         return 1;
4155     }
4156
4157     /*
4158      * XXX the scheduling process should really be done asynchronously
4159      *     to avoid fssync deadlocks
4160      */
4161     if (!vp->salvage.scheduled) {
4162         /* if we haven't previously scheduled a salvage, do so now 
4163          *
4164          * set the volume to an exclusive state and drop the lock
4165          * around the SALVSYNC call
4166          *
4167          * note that we do NOT acquire a reservation here -- doing so
4168          * could result in unbounded recursion
4169          */
4170         strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4171         state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4172         VOL_UNLOCK;
4173
4174         /* can't use V_id() since there's no guarantee
4175          * we have the disk data header at this point */
4176         code = SALVSYNC_SalvageVolume(vp->hashid,
4177                                       partName,
4178                                       SALVSYNC_SALVAGE,
4179                                       vp->salvage.reason,
4180                                       vp->salvage.prio,
4181                                       NULL);
4182         VOL_LOCK;
4183         VChangeState_r(vp, state_save);
4184
4185         if (code == SYNC_OK) {
4186             vp->salvage.scheduled = 1;
4187             vp->stats.salvages++;
4188             vp->stats.last_salvage_req = FT_ApproxTime();
4189             IncUInt64(&VStats.salvages);
4190         } else {
4191             ret = 1;
4192             switch(code) {
4193             case SYNC_BAD_COMMAND:
4194             case SYNC_COM_ERROR:
4195                 break;
4196             case SYNC_DENIED:
4197                 Log("VScheduleSalvage_r:  SALVSYNC request denied\n");
4198                 break;
4199             default:
4200                 Log("VScheduleSalvage_r:  SALVSYNC unknown protocol error\n");
4201                 break;
4202             }
4203         }
4204     }
4205 #endif /* SALVSYNC_BUILD_CLIENT */
4206     return ret;
4207 }
4208
4209 #ifdef SALVSYNC_BUILD_CLIENT
4210 /**
4211  * connect to the salvageserver SYNC service.
4212  *
4213  * @return operation status
4214  *    @retval 0 failure
4215  *    @retval 1 success
4216  *
4217  * @post connection to salvageserver SYNC service established
4218  *
4219  * @see VConnectSALV_r
4220  * @see VDisconnectSALV
4221  * @see VReconnectSALV
4222  */
4223 int
4224 VConnectSALV(void)
4225 {
4226     int retVal;
4227     VOL_LOCK;
4228     retVal = VConnectSALV_r();
4229     VOL_UNLOCK;
4230     return retVal;
4231 }
4232
4233 /**
4234  * connect to the salvageserver SYNC service.
4235  *
4236  * @return operation status
4237  *    @retval 0 failure
4238  *    @retval 1 success
4239  *
4240  * @pre VOL_LOCK is held.
4241  *
4242  * @post connection to salvageserver SYNC service established
4243  *
4244  * @see VConnectSALV
4245  * @see VDisconnectSALV_r
4246  * @see VReconnectSALV_r
4247  * @see SALVSYNC_clientInit
4248  *
4249  * @internal volume package internal use only.
4250  */
4251 int
4252 VConnectSALV_r(void)
4253 {
4254     return SALVSYNC_clientInit();
4255 }
4256
4257 /**
4258  * disconnect from the salvageserver SYNC service.
4259  *
4260  * @return operation status
4261  *    @retval 0 success
4262  *
4263  * @pre client should have a live connection to the salvageserver
4264  *
4265  * @post connection to salvageserver SYNC service destroyed
4266  *
4267  * @see VDisconnectSALV_r
4268  * @see VConnectSALV
4269  * @see VReconnectSALV
4270  */
4271 int
4272 VDisconnectSALV(void)
4273 {
4274     int retVal;
4275     VOL_LOCK;
4276     VDisconnectSALV_r();
4277     VOL_UNLOCK;
4278     return retVal;
4279 }
4280
4281 /**
4282  * disconnect from the salvageserver SYNC service.
4283  *
4284  * @return operation status
4285  *    @retval 0 success
4286  *
4287  * @pre 
4288  *    @arg VOL_LOCK is held.
4289  *    @arg client should have a live connection to the salvageserver.
4290  *
4291  * @post connection to salvageserver SYNC service destroyed
4292  *
4293  * @see VDisconnectSALV
4294  * @see VConnectSALV_r
4295  * @see VReconnectSALV_r
4296  * @see SALVSYNC_clientFinis
4297  *
4298  * @internal volume package internal use only.
4299  */
4300 int
4301 VDisconnectSALV_r(void)
4302
4303     return SALVSYNC_clientFinis();
4304 }
4305
4306 /**
4307  * disconnect and then re-connect to the salvageserver SYNC service.
4308  *
4309  * @return operation status
4310  *    @retval 0 failure
4311  *    @retval 1 success
4312  *
4313  * @pre client should have a live connection to the salvageserver
4314  *
4315  * @post old connection is dropped, and a new one is established
4316  *
4317  * @see VConnectSALV
4318  * @see VDisconnectSALV
4319  * @see VReconnectSALV_r
4320  */
4321 int
4322 VReconnectSALV(void)
4323 {
4324     int retVal;
4325     VOL_LOCK;
4326     retVal = VReconnectSALV_r();
4327     VOL_UNLOCK;
4328     return retVal;
4329 }
4330
4331 /**
4332  * disconnect and then re-connect to the salvageserver SYNC service.
4333  *
4334  * @return operation status
4335  *    @retval 0 failure
4336  *    @retval 1 success
4337  *
4338  * @pre 
4339  *    @arg VOL_LOCK is held.
4340  *    @arg client should have a live connection to the salvageserver.
4341  *
4342  * @post old connection is dropped, and a new one is established
4343  *
4344  * @see VConnectSALV_r
4345  * @see VDisconnectSALV
4346  * @see VReconnectSALV
4347  * @see SALVSYNC_clientReconnect
4348  *
4349  * @internal volume package internal use only.
4350  */
4351 int
4352 VReconnectSALV_r(void)
4353 {
4354     return SALVSYNC_clientReconnect();
4355 }
4356 #endif /* SALVSYNC_BUILD_CLIENT */
4357 #endif /* AFS_DEMAND_ATTACH_FS */
4358
4359
4360 /***************************************************/
4361 /* FSSYNC routines                                 */
4362 /***************************************************/
4363
4364 /* This must be called by any volume utility which needs to run while the
4365    file server is also running.  This is separated from VInitVolumePackage so
4366    that a utility can fork--and each of the children can independently
4367    initialize communication with the file server */
4368 #ifdef FSSYNC_BUILD_CLIENT
4369 /**
4370  * connect to the fileserver SYNC service.
4371  *
4372  * @return operation status
4373  *    @retval 0 failure
4374  *    @retval 1 success
4375  *
4376  * @pre 
4377  *    @arg VInit must equal 2.
4378  *    @arg Program Type must not be fileserver or salvager.
4379  *
4380  * @post connection to fileserver SYNC service established
4381  *
4382  * @see VConnectFS_r
4383  * @see VDisconnectFS
4384  * @see VChildProcReconnectFS
4385  */
4386 int
4387 VConnectFS(void)
4388 {
4389     int retVal;
4390     VOL_LOCK;
4391     retVal = VConnectFS_r();
4392     VOL_UNLOCK;
4393     return retVal;
4394 }
4395
4396 /**
4397  * connect to the fileserver SYNC service.
4398  *
4399  * @return operation status
4400  *    @retval 0 failure
4401  *    @retval 1 success
4402  *
4403  * @pre 
4404  *    @arg VInit must equal 2.
4405  *    @arg Program Type must not be fileserver or salvager.
4406  *    @arg VOL_LOCK is held.
4407  *
4408  * @post connection to fileserver SYNC service established
4409  *
4410  * @see VConnectFS
4411  * @see VDisconnectFS_r
4412  * @see VChildProcReconnectFS_r
4413  *
4414  * @internal volume package internal use only.
4415  */
4416 int
4417 VConnectFS_r(void)
4418 {
4419     int rc;
4420     assert((VInit == 2) && 
4421            (programType != fileServer) &&
4422            (programType != salvager));
4423     rc = FSYNC_clientInit();
4424     if (rc)
4425         VInit = 3;
4426     return rc;
4427 }
4428
4429 /**
4430  * disconnect from the fileserver SYNC service.
4431  *
4432  * @pre 
4433  *    @arg client should have a live connection to the fileserver.
4434  *    @arg VOL_LOCK is held.
4435  *    @arg Program Type must not be fileserver or salvager.
4436  *
4437  * @post connection to fileserver SYNC service destroyed
4438  *
4439  * @see VDisconnectFS
4440  * @see VConnectFS_r
4441  * @see VChildProcReconnectFS_r
4442  *
4443  * @internal volume package internal use only.
4444  */
4445 void
4446 VDisconnectFS_r(void)
4447 {
4448     assert((programType != fileServer) &&
4449            (programType != salvager));
4450     FSYNC_clientFinis();
4451     VInit = 2;
4452 }
4453
4454 /**
4455  * disconnect from the fileserver SYNC service.
4456  *
4457  * @pre
4458  *    @arg client should have a live connection to the fileserver.
4459  *    @arg Program Type must not be fileserver or salvager.
4460  *
4461  * @post connection to fileserver SYNC service destroyed
4462  *
4463  * @see VDisconnectFS_r
4464  * @see VConnectFS
4465  * @see VChildProcReconnectFS
4466  */
4467 void
4468 VDisconnectFS(void)
4469 {
4470     VOL_LOCK;
4471     VDisconnectFS_r();
4472     VOL_UNLOCK;
4473 }
4474
4475 /**
4476  * connect to the fileserver SYNC service from a child process following a fork.
4477  *
4478  * @return operation status
4479  *    @retval 0 failure
4480  *    @retval 1 success
4481  *
4482  * @pre
4483  *    @arg VOL_LOCK is held.
4484  *    @arg current FSYNC handle is shared with a parent process
4485  *
4486  * @post current FSYNC handle is discarded and a new connection to the
4487  *       fileserver SYNC service is established
4488  *
4489  * @see VChildProcReconnectFS
4490  * @see VConnectFS_r
4491  * @see VDisconnectFS_r
4492  *
4493  * @internal volume package internal use only.
4494  */
4495 int
4496 VChildProcReconnectFS_r(void)
4497 {
4498     return FSYNC_clientChildProcReconnect();
4499 }
4500
4501 /**
4502  * connect to the fileserver SYNC service from a child process following a fork.
4503  *
4504  * @return operation status
4505  *    @retval 0 failure
4506  *    @retval 1 success
4507  *
4508  * @pre current FSYNC handle is shared with a parent process
4509  *
4510  * @post current FSYNC handle is discarded and a new connection to the
4511  *       fileserver SYNC service is established
4512  *
4513  * @see VChildProcReconnectFS_r
4514  * @see VConnectFS
4515  * @see VDisconnectFS
4516  */
4517 int
4518 VChildProcReconnectFS(void)
4519 {
4520     int ret;
4521     VOL_LOCK;
4522     ret = VChildProcReconnectFS_r();
4523     VOL_UNLOCK;
4524     return ret;
4525 }
4526 #endif /* FSSYNC_BUILD_CLIENT */
4527
4528
4529 /***************************************************/
4530 /* volume bitmap routines                          */
4531 /***************************************************/
4532
4533 /*
4534  * For demand attach fs, flags parameter controls
4535  * locking behavior.  If (flags & VOL_ALLOC_BITMAP_WAIT)
4536  * is set, then this function will create a reservation
4537  * and block on any other exclusive operations.  Otherwise,
4538  * this function assumes the caller already has exclusive
4539  * access to vp, and we just change the volume state.
4540  */
4541 VnodeId
4542 VAllocBitmapEntry_r(Error * ec, Volume * vp, 
4543                     struct vnodeIndex *index, int flags)
4544 {
4545     VnodeId ret;
4546     register byte *bp, *ep;
4547 #ifdef AFS_DEMAND_ATTACH_FS
4548     VolState state_save;
4549 #endif /* AFS_DEMAND_ATTACH_FS */
4550
4551     *ec = 0;
4552
4553     /* This test is probably redundant */
4554     if (!VolumeWriteable(vp)) {
4555         *ec = (bit32) VREADONLY;
4556         return 0;
4557     }
4558
4559 #ifdef AFS_DEMAND_ATTACH_FS
4560     if (flags & VOL_ALLOC_BITMAP_WAIT) {
4561         VCreateReservation_r(vp);
4562         VWaitExclusiveState_r(vp);
4563     }
4564     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4565 #endif /* AFS_DEMAND_ATTACH_FS */
4566
4567 #ifdef BITMAP_LATER
4568     if ((programType == fileServer) && !index->bitmap) {
4569         int i;
4570 #ifndef AFS_DEMAND_ATTACH_FS
4571         /* demand attach fs uses the volume state to avoid races.
4572          * specialStatus field is not used at all */
4573         int wasVBUSY = 0;
4574         if (vp->specialStatus == VBUSY) {
4575             if (vp->goingOffline) {     /* vos dump waiting for the volume to
4576                                          * go offline. We probably come here
4577                                          * from AddNewReadableResidency */
4578                 wasVBUSY = 1;
4579             } else {
4580                 while (vp->specialStatus == VBUSY) {
4581 #ifdef AFS_PTHREAD_ENV
4582                     VOL_UNLOCK;
4583                     sleep(2);
4584                     VOL_LOCK;
4585 #else /* !AFS_PTHREAD_ENV */
4586                     IOMGR_Sleep(2);
4587 #endif /* !AFS_PTHREAD_ENV */
4588                 }
4589             }
4590         }
4591 #endif /* !AFS_DEMAND_ATTACH_FS */
4592
4593         if (!index->bitmap) {
4594 #ifndef AFS_DEMAND_ATTACH_FS
4595             vp->specialStatus = VBUSY;  /* Stop anyone else from using it. */
4596 #endif /* AFS_DEMAND_ATTACH_FS */
4597             for (i = 0; i < nVNODECLASSES; i++) {
4598                 VGetBitmap_r(ec, vp, i);
4599                 if (*ec) {
4600 #ifdef AFS_DEMAND_ATTACH_FS
4601                     VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4602 #else /* AFS_DEMAND_ATTACH_FS */
4603                     DeleteVolumeFromHashTable(vp);
4604                     vp->shuttingDown = 1;       /* Let who has it free it. */
4605                     vp->specialStatus = 0;
4606 #endif /* AFS_DEMAND_ATTACH_FS */
4607                     ret = NULL;
4608                     goto done;
4609                 }
4610             }
4611 #ifndef AFS_DEMAND_ATTACH_FS
4612             if (!wasVBUSY)
4613                 vp->specialStatus = 0;  /* Allow others to have access. */
4614 #endif /* AFS_DEMAND_ATTACH_FS */
4615         }
4616     }
4617 #endif /* BITMAP_LATER */
4618
4619 #ifdef AFS_DEMAND_ATTACH_FS
4620     VOL_UNLOCK;
4621 #endif /* AFS_DEMAND_ATTACH_FS */
4622     bp = index->bitmap + index->bitmapOffset;
4623     ep = index->bitmap + index->bitmapSize;
4624     while (bp < ep) {
4625         if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4626             int o;
4627             index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4628             while (*bp == 0xff)
4629                 bp++;
4630             o = ffs(~*bp) - 1;  /* ffs is documented in BSTRING(3) */
4631             *bp |= (1 << o);
4632             ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4633 #ifdef AFS_DEMAND_ATTACH_FS
4634             VOL_LOCK;
4635 #endif /* AFS_DEMAND_ATTACH_FS */
4636             goto done;
4637         }
4638         bp += sizeof(bit32) /* i.e. 4 */ ;
4639     }
4640     /* No bit map entry--must grow bitmap */
4641     bp = (byte *)
4642         realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4643     assert(bp != NULL);
4644     index->bitmap = bp;
4645     bp += index->bitmapSize;
4646     memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4647     index->bitmapOffset = index->bitmapSize;
4648     index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4649     *bp = 1;
4650     ret = index->bitmapOffset * 8;
4651 #ifdef AFS_DEMAND_ATTACH_FS
4652     VOL_LOCK;
4653 #endif /* AFS_DEMAND_ATTACH_FS */
4654
4655  done:
4656 #ifdef AFS_DEMAND_ATTACH_FS
4657     VChangeState_r(vp, state_save);
4658     if (flags & VOL_ALLOC_BITMAP_WAIT) {
4659         VCancelReservation_r(vp);
4660     }
4661 #endif /* AFS_DEMAND_ATTACH_FS */
4662     return ret;
4663 }
4664
4665 VnodeId
4666 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4667 {
4668     VnodeId retVal;
4669     VOL_LOCK;
4670     retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4671     VOL_UNLOCK;
4672     return retVal;
4673 }
4674
4675 void
4676 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4677                    unsigned bitNumber)
4678 {
4679     unsigned int offset;
4680
4681     *ec = 0;
4682 #ifdef BITMAP_LATER
4683     if (!index->bitmap)
4684         return;
4685 #endif /* BITMAP_LATER */
4686     offset = bitNumber >> 3;
4687     if (offset >= index->bitmapSize) {
4688         *ec = VNOVNODE;
4689         return;
4690     }
4691     if (offset < index->bitmapOffset)
4692         index->bitmapOffset = offset & ~3;      /* Truncate to nearest bit32 */
4693     *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4694 }
4695
4696 void
4697 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4698                  unsigned bitNumber)
4699 {
4700     VOL_LOCK;
4701     VFreeBitMapEntry_r(ec, index, bitNumber);
4702     VOL_UNLOCK;
4703 }
4704
4705 /* this function will drop the glock internally.
4706  * for old pthread fileservers, this is safe thanks to vbusy.
4707  *
4708  * for demand attach fs, caller must have already called
4709  * VCreateReservation_r and VWaitExclusiveState_r */
4710 static void
4711 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4712 {
4713     StreamHandle_t *file;
4714     int nVnodes;
4715     int size;
4716     struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4717     struct vnodeIndex *vip = &vp->vnodeIndex[class];
4718     struct VnodeDiskObject *vnode;
4719     unsigned int unique = 0;
4720     FdHandle_t *fdP;
4721 #ifdef BITMAP_LATER
4722     byte *BitMap = 0;
4723 #endif /* BITMAP_LATER */
4724 #ifdef AFS_DEMAND_ATTACH_FS
4725     VolState state_save;
4726 #endif /* AFS_DEMAND_ATTACH_FS */
4727
4728     *ec = 0;
4729
4730 #ifdef AFS_DEMAND_ATTACH_FS
4731     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4732 #endif /* AFS_DEMAND_ATTACH_FS */
4733     VOL_UNLOCK;
4734
4735     fdP = IH_OPEN(vip->handle);
4736     assert(fdP != NULL);
4737     file = FDH_FDOPEN(fdP, "r");
4738     assert(file != NULL);
4739     vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4740     assert(vnode != NULL);
4741     size = OS_SIZE(fdP->fd_fd);
4742     assert(size != -1);
4743     nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4744         >> vcp->logSize;
4745     vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4;     /* The 10 is a little extra so
4746                                                          * a few files can be created in this volume,
4747                                                          * the whole thing is rounded up to nearest 4
4748                                                          * bytes, because the bit map allocator likes
4749                                                          * it that way */
4750 #ifdef BITMAP_LATER
4751     BitMap = (byte *) calloc(1, vip->bitmapSize);
4752     assert(BitMap != NULL);
4753 #else /* BITMAP_LATER */
4754     vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4755     assert(vip->bitmap != NULL);
4756     vip->bitmapOffset = 0;
4757 #endif /* BITMAP_LATER */
4758     if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4759         int bitNumber = 0;
4760         for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4761             if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4762                 break;
4763             if (vnode->type != vNull) {
4764                 if (vnode->vnodeMagic != vcp->magic) {
4765                     Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4766                     *ec = VSALVAGE;
4767                     break;
4768                 }
4769 #ifdef BITMAP_LATER
4770                 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4771 #else /* BITMAP_LATER */
4772                 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4773 #endif /* BITMAP_LATER */
4774                 if (unique <= vnode->uniquifier)
4775                     unique = vnode->uniquifier + 1;
4776             }
4777 #ifndef AFS_PTHREAD_ENV
4778             if ((bitNumber & 0x00ff) == 0x0ff) {        /* every 256 iterations */
4779                 IOMGR_Poll();
4780             }
4781 #endif /* !AFS_PTHREAD_ENV */
4782         }
4783     }
4784     if (vp->nextVnodeUnique < unique) {
4785         Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4786         *ec = VSALVAGE;
4787     }
4788     /* Paranoia, partly justified--I think fclose after fdopen
4789      * doesn't seem to close fd.  In any event, the documentation
4790      * doesn't specify, so it's safer to close it twice.
4791      */
4792     STREAM_CLOSE(file);
4793     FDH_CLOSE(fdP);
4794     free(vnode);
4795
4796     VOL_LOCK;
4797 #ifdef BITMAP_LATER
4798     /* There may have been a racing condition with some other thread, both
4799      * creating the bitmaps for this volume. If the other thread was faster
4800      * the pointer to bitmap should already be filled and we can free ours.
4801      */
4802     if (vip->bitmap == NULL) {
4803         vip->bitmap = BitMap;
4804         vip->bitmapOffset = 0;
4805     } else
4806         free((byte *) BitMap);
4807 #endif /* BITMAP_LATER */
4808 #ifdef AFS_DEMAND_ATTACH_FS
4809     VChangeState_r(vp, state_save);
4810 #endif /* AFS_DEMAND_ATTACH_FS */
4811 }
4812
4813
4814 /***************************************************/
4815 /* Volume Path and Volume Number utility routines  */
4816 /***************************************************/
4817
4818 /**
4819  * find the first occurrence of a volume header file and return the path.
4820  *
4821  * @param[out] ec          outbound error code
4822  * @param[in]  volumeId    volume id to find
4823  * @param[out] partitionp  pointer to disk partition path string
4824  * @param[out] namep       pointer to volume header file name string
4825  *
4826  * @post path to first occurrence of volume header is returned in partitionp
4827  *       and namep, or ec is set accordingly.
4828  *
4829  * @warning this function is NOT re-entrant -- partitionp and namep point to
4830  *          static data segments
4831  *
4832  * @note if a volume utility inadvertently leaves behind a stale volume header
4833  *       on a vice partition, it is possible for callers to get the wrong one,
4834  *       depending on the order of the disk partition linked list.
4835  *
4836  */
4837 void
4838 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4839 {
4840     static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4841     char path[VMAXPATHLEN];
4842     int found = 0;
4843     struct DiskPartition64 *dp;
4844
4845     *ec = 0;
4846     name[0] = '/';
4847     (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
4848     for (dp = DiskPartitionList; dp; dp = dp->next) {
4849         struct afs_stat status;
4850         strcpy(path, VPartitionPath(dp));
4851         strcat(path, name);
4852         if (afs_stat(path, &status) == 0) {
4853             strcpy(partition, dp->name);
4854             found = 1;
4855             break;
4856         }
4857     }
4858     if (!found) {
4859         *ec = VNOVOL;
4860         *partitionp = *namep = NULL;
4861     } else {
4862         *partitionp = partition;
4863         *namep = name;
4864     }
4865 }
4866
4867 /**
4868  * extract a volume number from a volume header filename string.
4869  *
4870  * @param[in] name  volume header filename string
4871  *
4872  * @return volume number
4873  *
4874  * @note the string must be of the form VFORMAT.  the only permissible
4875  *       deviation is a leading '/' character.
4876  *
4877  * @see VFORMAT
4878  */
4879 int
4880 VolumeNumber(char *name)
4881 {
4882     if (*name == '/')
4883         name++;
4884     return atoi(name + 1);
4885 }
4886
4887 /**
4888  * compute the volume header filename.
4889  *
4890  * @param[in] volumeId
4891  *
4892  * @return volume header filename
4893  *
4894  * @post volume header filename string is constructed
4895  *
4896  * @warning this function is NOT re-entrant -- the returned string is
4897  *          stored in a static char array.  see VolumeExternalName_r
4898  *          for a re-entrant equivalent.
4899  *
4900  * @see VolumeExternalName_r
4901  *
4902  * @deprecated due to the above re-entrancy warning, this interface should
4903  *             be considered deprecated.  Please use VolumeExternalName_r
4904  *             in its stead.
4905  */
4906 char *
4907 VolumeExternalName(VolumeId volumeId)
4908 {
4909     static char name[VMAXPATHLEN];
4910     (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
4911     return name;
4912 }
4913
4914 /**
4915  * compute the volume header filename.
4916  *
4917  * @param[in]     volumeId
4918  * @param[inout]  name       array in which to store filename
4919  * @param[in]     len        length of name array
4920  *
4921  * @return result code from afs_snprintf
4922  *
4923  * @see VolumeExternalName
4924  * @see afs_snprintf
4925  *
4926  * @note re-entrant equivalent of VolumeExternalName
4927  *
4928  * @internal volume package internal use only.
4929  */
4930 #ifdef AFS_DEMAND_ATTACH_FS
4931 static int
4932 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
4933 {
4934     return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
4935 }
4936 #endif
4937
4938
4939 /***************************************************/
4940 /* Volume Usage Statistics routines                */
4941 /***************************************************/
4942
4943 #if OPENAFS_VOL_STATS
4944 #define OneDay  (86400)         /* 24 hours' worth of seconds */
4945 #else
4946 #define OneDay  (24*60*60)      /* 24 hours */
4947 #endif /* OPENAFS_VOL_STATS */
4948
4949 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
4950
4951 /*------------------------------------------------------------------------
4952  * [export] VAdjustVolumeStatistics
4953  *
4954  * Description:
4955  *      If we've passed midnight, we need to update all the day use
4956  *      statistics as well as zeroing the detailed volume statistics
4957  *      (if we are implementing them).
4958  *
4959  * Arguments:
4960  *      vp : Pointer to the volume structure describing the lucky
4961  *              volume being considered for update.
4962  *
4963  * Returns:
4964  *      0 (always!)
4965  *
4966  * Environment:
4967  *      Nothing interesting.
4968  *
4969  * Side Effects:
4970  *      As described.
4971  *------------------------------------------------------------------------*/
4972
4973 int
4974 VAdjustVolumeStatistics_r(register Volume * vp)
4975 {
4976     unsigned int now = FT_ApproxTime();
4977
4978     if (now - V_dayUseDate(vp) > OneDay) {
4979         register int ndays, i;
4980
4981         ndays = (now - V_dayUseDate(vp)) / OneDay;
4982         for (i = 6; i > ndays - 1; i--)
4983             V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
4984         for (i = 0; i < ndays - 1 && i < 7; i++)
4985             V_weekUse(vp)[i] = 0;
4986         if (ndays <= 7)
4987             V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
4988         V_dayUse(vp) = 0;
4989         V_dayUseDate(vp) = Midnight(now);
4990
4991 #if OPENAFS_VOL_STATS
4992         /*
4993          * All we need to do is bzero the entire VOL_STATS_BYTES of
4994          * the detailed volume statistics area.
4995          */
4996         memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
4997 #endif /* OPENAFS_VOL_STATS */
4998     }
4999
5000     /*It's been more than a day of collection */
5001     /*
5002      * Always return happily.
5003      */
5004     return (0);
5005 }                               /*VAdjustVolumeStatistics */
5006
5007 int
5008 VAdjustVolumeStatistics(register Volume * vp)
5009 {
5010     int retVal;
5011     VOL_LOCK;
5012     retVal = VAdjustVolumeStatistics_r(vp);
5013     VOL_UNLOCK;
5014     return retVal;
5015 }
5016
5017 void
5018 VBumpVolumeUsage_r(register Volume * vp)
5019 {
5020     unsigned int now = FT_ApproxTime();
5021     if (now - V_dayUseDate(vp) > OneDay)
5022         VAdjustVolumeStatistics_r(vp);
5023     /*
5024      * Save the volume header image to disk after every 128 bumps to dayUse.
5025      */
5026     if ((V_dayUse(vp)++ & 127) == 0) {
5027         Error error;
5028         VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5029     }
5030 }
5031
5032 void
5033 VBumpVolumeUsage(register Volume * vp)
5034 {
5035     VOL_LOCK;
5036     VBumpVolumeUsage_r(vp);
5037     VOL_UNLOCK;
5038 }
5039
5040 void
5041 VSetDiskUsage_r(void)
5042 {
5043 #ifndef AFS_DEMAND_ATTACH_FS
5044     static int FifteenMinuteCounter = 0;
5045 #endif
5046
5047     while (VInit < 2) {
5048         /* NOTE: Don't attempt to access the partitions list until the
5049          * initialization level indicates that all volumes are attached,
5050          * which implies that all partitions are initialized. */
5051 #ifdef AFS_PTHREAD_ENV
5052         sleep(10);
5053 #else /* AFS_PTHREAD_ENV */
5054         IOMGR_Sleep(10);
5055 #endif /* AFS_PTHREAD_ENV */
5056     }
5057
5058     VResetDiskUsage_r();
5059
5060 #ifndef AFS_DEMAND_ATTACH_FS
5061     if (++FifteenMinuteCounter == 3) {
5062         FifteenMinuteCounter = 0;
5063         VScanUpdateList();
5064     }
5065 #endif /* !AFS_DEMAND_ATTACH_FS */
5066 }
5067
5068 void
5069 VSetDiskUsage(void)
5070 {
5071     VOL_LOCK;
5072     VSetDiskUsage_r();
5073     VOL_UNLOCK;
5074 }
5075
5076
5077 /***************************************************/
5078 /* Volume Update List routines                     */
5079 /***************************************************/
5080
5081 /* The number of minutes that a volume hasn't been updated before the
5082  * "Dont salvage" flag in the volume header will be turned on */
5083 #define SALVAGE_INTERVAL        (10*60)
5084
5085 /*
5086  * demand attach fs
5087  *
5088  * volume update list functionality has been moved into the VLRU
5089  * the DONT_SALVAGE flag is now set during VLRU demotion
5090  */
5091
5092 #ifndef AFS_DEMAND_ATTACH_FS
5093 static VolumeId *UpdateList = NULL;     /* Pointer to array of Volume ID's */
5094 static int nUpdatedVolumes = 0;         /* Updated with entry in UpdateList, salvage after crash flag on */
5095 static int updateSize = 0;              /* number of entries possible */
5096 #define UPDATE_LIST_SIZE 128            /* initial size increment (must be a power of 2!) */
5097 #endif /* !AFS_DEMAND_ATTACH_FS */
5098
5099 void
5100 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5101 {
5102     *ec = 0;
5103     vp->updateTime = FT_ApproxTime();
5104     if (V_dontSalvage(vp) == 0)
5105         return;
5106     V_dontSalvage(vp) = 0;
5107     VSyncVolume_r(ec, vp, 0);
5108 #ifdef AFS_DEMAND_ATTACH_FS
5109     V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5110 #else /* !AFS_DEMAND_ATTACH_FS */
5111     if (*ec)
5112         return;
5113     if (UpdateList == NULL) {
5114         updateSize = UPDATE_LIST_SIZE;
5115         UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5116     } else {
5117         if (nUpdatedVolumes == updateSize) {
5118             updateSize <<= 1;
5119             if (updateSize > 524288) {
5120                 Log("warning: there is likely a bug in the volume update scanner\n");
5121                 return;
5122             }
5123             UpdateList =
5124                 (VolumeId *) realloc(UpdateList,
5125                                      sizeof(VolumeId) * updateSize);
5126         }
5127     }
5128     assert(UpdateList != NULL);
5129     UpdateList[nUpdatedVolumes++] = V_id(vp);
5130 #endif /* !AFS_DEMAND_ATTACH_FS */
5131 }
5132
5133 #ifndef AFS_DEMAND_ATTACH_FS
5134 static void
5135 VScanUpdateList(void)
5136 {
5137     register int i, gap;
5138     register Volume *vp;
5139     Error error;
5140     afs_uint32 now = FT_ApproxTime();
5141     /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5142     for (i = gap = 0; i < nUpdatedVolumes; i++) {
5143         if (gap)
5144             UpdateList[i - gap] = UpdateList[i];
5145
5146         /* XXX this routine needlessly messes up the Volume LRU by
5147          * breaking the LRU temporal-locality assumptions.....
5148          * we should use a special volume header allocator here */
5149         vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5150         if (error) {
5151             gap++;
5152         } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5153             V_dontSalvage(vp) = DONT_SALVAGE;
5154             VUpdateVolume_r(&error, vp, 0);     /* No need to fsync--not critical */
5155             gap++;
5156         }
5157
5158         if (vp) {
5159             VPutVolume_r(vp);
5160         }
5161
5162 #ifndef AFS_PTHREAD_ENV
5163         IOMGR_Poll();
5164 #endif /* !AFS_PTHREAD_ENV */
5165     }
5166     nUpdatedVolumes -= gap;
5167 }
5168 #endif /* !AFS_DEMAND_ATTACH_FS */
5169
5170
5171 /***************************************************/
5172 /* Volume LRU routines                             */
5173 /***************************************************/
5174
5175 /* demand attach fs
5176  * volume LRU
5177  *
5178  * with demand attach fs, we attempt to soft detach(1)
5179  * volumes which have not been accessed in a long time
5180  * in order to speed up fileserver shutdown
5181  *
5182  * (1) by soft detach we mean a process very similar
5183  *     to VOffline, except the final state of the 
5184  *     Volume will be VOL_STATE_PREATTACHED, instead
5185  *     of the usual VOL_STATE_UNATTACHED
5186  */
5187 #ifdef AFS_DEMAND_ATTACH_FS
5188
5189 /* implementation is reminiscent of a generational GC
5190  *
5191  * queue 0 is newly attached volumes. this queue is
5192  * sorted by attach timestamp
5193  *
5194  * queue 1 is volumes that have been around a bit
5195  * longer than queue 0. this queue is sorted by
5196  * attach timestamp
5197  *
5198  * queue 2 is volumes tha have been around the longest.
5199  * this queue is unsorted
5200  *
5201  * queue 3 is volumes that have been marked as
5202  * candidates for soft detachment. this queue is
5203  * unsorted
5204  */
5205 #define VLRU_GENERATIONS  3   /**< number of generations in VLRU */
5206 #define VLRU_QUEUES       5   /**< total number of VLRU queues */
5207
5208 /**
5209  * definition of a VLRU queue.
5210  */
5211 struct VLRU_q {
5212     volatile struct rx_queue q;
5213     volatile int len;
5214     volatile int busy;
5215     pthread_cond_t cv;
5216 };
5217
5218 /**
5219  * main VLRU data structure.
5220  */
5221 struct VLRU {
5222     struct VLRU_q q[VLRU_QUEUES];   /**< VLRU queues */
5223
5224     /* VLRU config */
5225     /** time interval (in seconds) between promotion passes for
5226      *  each young generation queue. */
5227     afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5228
5229     /** time interval (in seconds) between soft detach candidate
5230      *  scans for each generation queue.
5231      *
5232      *  scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5233      *  we perform a soft detach pass. */
5234     afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5235
5236     /* scheduler state */
5237     int next_idx;                                       /**< next queue to receive attention */
5238     afs_uint32 last_promotion[VLRU_GENERATIONS-1];      /**< timestamp of last promotion scan */
5239     afs_uint32 last_scan[VLRU_GENERATIONS+1];           /**< timestamp of last detach scan */
5240
5241     int scanner_state;                                  /**< state of scanner thread */
5242     pthread_cond_t cv;                                  /**< state transition CV */
5243 };
5244
5245 /** global VLRU state */
5246 static struct VLRU volume_LRU;
5247
5248 /**
5249  * defined states for VLRU scanner thread.
5250  */
5251 typedef enum {
5252     VLRU_SCANNER_STATE_OFFLINE        = 0,    /**< vlru scanner thread is offline */
5253     VLRU_SCANNER_STATE_ONLINE         = 1,    /**< vlru scanner thread is online */
5254     VLRU_SCANNER_STATE_SHUTTING_DOWN  = 2,    /**< vlru scanner thread is shutting down */
5255     VLRU_SCANNER_STATE_PAUSING        = 3,    /**< vlru scanner thread is getting ready to pause */
5256     VLRU_SCANNER_STATE_PAUSED         = 4     /**< vlru scanner thread is paused */
5257 } vlru_thread_state_t;
5258
5259 /* vlru disk data header stuff */
5260 #define VLRU_DISK_MAGIC      0x7a8b9cad        /**< vlru disk entry magic number */
5261 #define VLRU_DISK_VERSION    1                 /**< vlru disk entry version number */
5262
5263 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5264 #define VLRU_DUMP_EXPIRATION_TIME   (60*60*24*7)  /* expire vlru data after 1 week */
5265
5266
5267 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5268  *  soft detachment. */
5269 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5270
5271 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5272 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5273
5274 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5275 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5276
5277 /** VLRU control flag.  non-zero value implies VLRU subsystem is activated. */
5278 static afs_uint32 VLRU_enabled = 1;
5279
5280 /* queue synchronization routines */
5281 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5282 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5283 static void VLRU_Wait_r(struct VLRU_q * q);
5284
5285 /**
5286  * set VLRU subsystem tunable parameters.
5287  *
5288  * @param[in] option  tunable option to modify
5289  * @param[in] val     new value for tunable parameter
5290  *
5291  * @pre @c VInitVolumePackage has not yet been called.
5292  *
5293  * @post tunable parameter is modified
5294  *
5295  * @note DAFS only
5296  *
5297  * @note valid option parameters are:
5298  *    @arg @c VLRU_SET_THRESH 
5299  *         set the period of inactivity after which
5300  *         volumes are eligible for soft detachment
5301  *    @arg @c VLRU_SET_INTERVAL 
5302  *         set the time interval between calls
5303  *         to the volume LRU "garbage collector"
5304  *    @arg @c VLRU_SET_MAX 
5305  *         set the max number of volumes to deallocate
5306  *         in one GC pass
5307  */
5308 void
5309 VLRU_SetOptions(int option, afs_uint32 val)
5310 {
5311     if (option == VLRU_SET_THRESH) {
5312         VLRU_offline_thresh = val;
5313     } else if (option == VLRU_SET_INTERVAL) {
5314         VLRU_offline_interval = val;
5315     } else if (option == VLRU_SET_MAX) {
5316         VLRU_offline_max = val;
5317     } else if (option == VLRU_SET_ENABLED) {
5318         VLRU_enabled = val;
5319     }
5320     VLRU_ComputeConstants();
5321 }
5322
5323 /**
5324  * compute VLRU internal timing parameters.
5325  *
5326  * @post VLRU scanner thread internal timing parameters are computed
5327  *
5328  * @note computes internal timing parameters based upon user-modifiable 
5329  *       tunable parameters.
5330  *
5331  * @note DAFS only
5332  *
5333  * @internal volume package internal use only.
5334  */
5335 static void
5336 VLRU_ComputeConstants(void)
5337 {
5338     afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5339
5340     /* compute the candidate scan interval */
5341     volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5342
5343     /* compute the promotion intervals */
5344     volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5345     volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5346
5347     if (factor > 16) {
5348         /* compute the gen 0 scan interval */
5349         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5350     } else {
5351         /* compute the gen 0 scan interval */
5352         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5353     }
5354 }
5355
5356 /**
5357  * initialize VLRU subsystem.
5358  *
5359  * @pre this function has not yet been called
5360  *
5361  * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5362  *
5363  * @note DAFS only
5364  *
5365  * @internal volume package internal use only.
5366  */
5367 static void
5368 VInitVLRU(void)
5369 {
5370     pthread_t tid;
5371     pthread_attr_t attrs;
5372     int i;
5373
5374     if (!VLRU_enabled) {
5375         Log("VLRU: disabled\n");
5376         return;
5377     }
5378
5379     /* initialize each of the VLRU queues */
5380     for (i = 0; i < VLRU_QUEUES; i++) {
5381         queue_Init(&volume_LRU.q[i]);
5382         volume_LRU.q[i].len = 0;
5383         volume_LRU.q[i].busy = 0;
5384         assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5385     }
5386
5387     /* setup the timing constants */
5388     VLRU_ComputeConstants();
5389
5390     /* XXX put inside LogLevel check? */
5391     Log("VLRU: starting scanner with the following configuration parameters:\n");
5392     Log("VLRU:  offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5393     Log("VLRU:  running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5394     Log("VLRU:  taking up to %d volumes offline per pass\n", VLRU_offline_max);
5395     Log("VLRU:  scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5396     Log("VLRU:  scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5397     Log("VLRU:  scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5398
5399     /* start up the VLRU scanner */
5400     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5401     if (programType == fileServer) {
5402         assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5403         assert(pthread_attr_init(&attrs) == 0);
5404         assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5405         assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5406     }
5407 }
5408
5409 /**
5410  * initialize the VLRU-related fields of a newly allocated volume object.
5411  *
5412  * @param[in] vp  pointer to volume object
5413  *
5414  * @pre
5415  *    @arg @c VOL_LOCK is held.
5416  *    @arg volume object is not on a VLRU queue.
5417  *
5418  * @post VLRU fields are initialized to indicate that volume object is not
5419  *       currently registered with the VLRU subsystem
5420  *
5421  * @note DAFS only
5422  *
5423  * @internal volume package interal use only.
5424  */
5425 static void
5426 VLRU_Init_Node_r(volatile Volume * vp)
5427 {
5428     if (!VLRU_enabled)
5429         return;
5430
5431     assert(queue_IsNotOnQueue(&vp->vlru));
5432     vp->vlru.idx = VLRU_QUEUE_INVALID;
5433 }
5434
5435 /**
5436  * add a volume object to a VLRU queue.
5437  *
5438  * @param[in] vp  pointer to volume object
5439  *
5440  * @pre
5441  *    @arg @c VOL_LOCK is held.
5442  *    @arg caller MUST hold a lightweight ref on @p vp.
5443  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5444  *
5445  * @post the volume object is added to the appropriate VLRU queue
5446  *
5447  * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5448  *       then the volume is added to that queue.  Otherwise, the value
5449  *       @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5450  *       volume is added to the NEW generation queue.
5451  *
5452  * @note @c VOL_LOCK may be dropped internally
5453  *
5454  * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5455  *       during the add operation, and is restored to the previous
5456  *       state prior to return.
5457  *
5458  * @note DAFS only
5459  *
5460  * @internal volume package internal use only.
5461  */
5462 static void
5463 VLRU_Add_r(volatile Volume * vp)
5464 {
5465     int idx;
5466     VolState state_save;
5467
5468     if (!VLRU_enabled)
5469         return;
5470
5471     if (queue_IsOnQueue(&vp->vlru))
5472         return;
5473
5474     state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5475
5476     idx = vp->vlru.idx;
5477     if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5478         idx = VLRU_QUEUE_NEW;
5479     }
5480
5481     VLRU_Wait_r(&volume_LRU.q[idx]);
5482
5483     /* repeat check since VLRU_Wait_r may have dropped
5484      * the glock */
5485     if (queue_IsNotOnQueue(&vp->vlru)) {
5486         vp->vlru.idx = idx;
5487         queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5488         volume_LRU.q[idx].len++;
5489         V_attachFlags(vp) |= VOL_ON_VLRU;
5490         vp->stats.last_promote = FT_ApproxTime();
5491     }
5492
5493     VChangeState_r(vp, state_save);
5494 }
5495
5496 /**
5497  * delete a volume object from a VLRU queue.
5498  *
5499  * @param[in] vp  pointer to volume object
5500  *
5501  * @pre
5502  *    @arg @c VOL_LOCK is held.
5503  *    @arg caller MUST hold a lightweight ref on @p vp.
5504  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5505  *
5506  * @post volume object is removed from the VLRU queue
5507  *
5508  * @note @c VOL_LOCK may be dropped internally
5509  *
5510  * @note DAFS only
5511  *
5512  * @todo We should probably set volume state to something exlcusive 
5513  *       (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5514  *
5515  * @internal volume package internal use only.
5516  */
5517 static void
5518 VLRU_Delete_r(volatile Volume * vp)
5519 {
5520     int idx;
5521
5522     if (!VLRU_enabled)
5523         return;
5524
5525     if (queue_IsNotOnQueue(&vp->vlru))
5526         return;
5527
5528     /* handle races */
5529     do {
5530       idx = vp->vlru.idx;
5531       if (idx == VLRU_QUEUE_INVALID)
5532           return;
5533       VLRU_Wait_r(&volume_LRU.q[idx]);
5534     } while (idx != vp->vlru.idx);
5535
5536     /* now remove from the VLRU and update 
5537      * the appropriate counter */
5538     queue_Remove(&vp->vlru);
5539     volume_LRU.q[idx].len--;
5540     vp->vlru.idx = VLRU_QUEUE_INVALID;
5541     V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5542 }
5543
5544 /**
5545  * tell the VLRU subsystem that a volume was just accessed.
5546  *
5547  * @param[in] vp  pointer to volume object
5548  *
5549  * @pre
5550  *    @arg @c VOL_LOCK is held
5551  *    @arg caller MUST hold a lightweight ref on @p vp
5552  *    @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5553  *
5554  * @post volume VLRU access statistics are updated.  If the volume was on
5555  *       the VLRU soft detach candidate queue, it is moved to the NEW
5556  *       generation queue.
5557  *
5558  * @note @c VOL_LOCK may be dropped internally
5559  *
5560  * @note DAFS only
5561  *
5562  * @internal volume package internal use only.
5563  */
5564 static void
5565 VLRU_UpdateAccess_r(volatile Volume * vp)
5566 {
5567     afs_uint32 live_interval;
5568     Volume * rvp = NULL;
5569
5570     if (!VLRU_enabled)
5571         return;
5572
5573     if (queue_IsNotOnQueue(&vp->vlru))
5574         return;
5575
5576     assert(V_attachFlags(vp) & VOL_ON_VLRU);
5577
5578     /* update the access timestamp */
5579     vp->stats.last_get = FT_ApproxTime();
5580
5581     /*
5582      * if the volume is on the soft detach candidate
5583      * list, we need to safely move it back to a
5584      * regular generation.  this has to be done
5585      * carefully so we don't race against the scanner
5586      * thread.
5587      */
5588
5589     /* if this volume is on the soft detach candidate queue,
5590      * then grab exclusive access to the necessary queues */
5591     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5592         rvp = vp;
5593         VCreateReservation_r(rvp);
5594
5595         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5596         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5597         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5598         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5599     }
5600
5601     /* make sure multiple threads don't race to update */
5602     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5603         VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5604     }
5605
5606     if (rvp) {
5607       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5608       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5609       VCancelReservation_r(rvp);
5610     }
5611 }
5612
5613 /**
5614  * switch a volume between two VLRU queues.
5615  *
5616  * @param[in] vp       pointer to volume object
5617  * @param[in] new_idx  index of VLRU queue onto which the volume will be moved
5618  * @param[in] append   controls whether the volume will be appended or 
5619  *                     prepended to the queue.  A nonzero value means it will
5620  *                     be appended; zero means it will be prepended.
5621  *
5622  * @pre The new (and old, if applicable) queue(s) must either be owned 
5623  *      exclusively by the calling thread for asynchronous manipulation,
5624  *      or the queue(s) must be quiescent and VOL_LOCK must be held.
5625  *      Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5626  *      for further details of the queue asynchronous processing mechanism.
5627  *
5628  * @post If the volume object was already on a VLRU queue, it is
5629  *       removed from the queue.  Depending on the value of the append
5630  *       parameter, the volume object is either appended or prepended
5631  *       to the VLRU queue referenced by the new_idx parameter.
5632  *
5633  * @note DAFS only
5634  *
5635  * @see VLRU_BeginExclusive_r
5636  * @see VLRU_EndExclusive_r
5637  * @see VLRU_Wait_r
5638  *
5639  * @internal volume package internal use only.
5640  */
5641 static void
5642 VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append)
5643 {
5644     if (queue_IsNotOnQueue(&vp->vlru))
5645         return;
5646
5647     queue_Remove(&vp->vlru);
5648     volume_LRU.q[vp->vlru.idx].len--;
5649     
5650     /* put the volume back on the correct generational queue */
5651     if (append) {
5652         queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5653     } else {
5654         queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5655     }
5656
5657     volume_LRU.q[new_idx].len++;
5658     vp->vlru.idx = new_idx;
5659 }
5660
5661 /**
5662  * VLRU background thread.
5663  *
5664  * The VLRU Scanner Thread is responsible for periodically scanning through
5665  * each VLRU queue looking for volumes which should be moved to another
5666  * queue, or soft detached.
5667  *
5668  * @param[in] args  unused thread arguments parameter
5669  *
5670  * @return unused thread return value
5671  *    @retval NULL always
5672  *
5673  * @internal volume package internal use only.
5674  */
5675 static void *
5676 VLRU_ScannerThread(void * args)
5677 {
5678     afs_uint32 now, min_delay, delay;
5679     afs_uint32 next_scan[VLRU_GENERATIONS];
5680     afs_uint32 next_promotion[VLRU_GENERATIONS];
5681     int i, min_idx, min_op, overdue, state;
5682
5683     /* set t=0 for promotion cycle to be 
5684      * fileserver startup */
5685     now = FT_ApproxTime();
5686     for (i=0; i < VLRU_GENERATIONS-1; i++) {
5687         volume_LRU.last_promotion[i] = now;
5688     }
5689
5690     /* don't start the scanner until VLRU_offline_thresh
5691      * plus a small delay for VInitVolumePackage to finish
5692      * has gone by */
5693
5694     sleep(VLRU_offline_thresh + 60);
5695
5696     /* set t=0 for scan cycle to be now */
5697     now = FT_ApproxTime();
5698     for (i=0; i < VLRU_GENERATIONS+1; i++) {
5699         volume_LRU.last_scan[i] = now;
5700     }
5701
5702     VOL_LOCK;
5703     if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5704         volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5705     }
5706
5707     while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5708         /* check to see if we've been asked to pause */
5709         if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5710             volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5711             assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5712             do {
5713                 VOL_CV_WAIT(&volume_LRU.cv);
5714             } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5715         }
5716
5717         /* scheduling can happen outside the glock */
5718         VOL_UNLOCK;
5719
5720         /* figure out what is next on the schedule */
5721
5722         /* figure out a potential schedule for the new generation first */
5723         overdue = 0;
5724         min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5725         min_idx = 0;
5726         min_op = 0;
5727         if (min_delay > volume_LRU.scan_interval[0]) {
5728             /* unsigned overflow -- we're overdue to run this scan */
5729             min_delay = 0;
5730             overdue = 1;
5731         }
5732
5733         /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5734         if (!overdue) {
5735             i = VLRU_QUEUE_CANDIDATE;
5736             delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5737             if (delay < min_delay) {
5738                 min_delay = delay;
5739                 min_idx = i;
5740             }
5741             if (delay > volume_LRU.scan_interval[i]) {
5742                 /* unsigned overflow -- we're overdue to run this scan */
5743                 min_delay = 0;
5744                 min_idx = i;
5745                 overdue = 1;
5746             }
5747         }
5748
5749         /* if we're still not overdue for something, figure out schedules for promotions */
5750         for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
5751             delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
5752             if (delay < min_delay) {
5753                 min_delay = delay;
5754                 min_idx = i;
5755                 min_op = 1;
5756             }
5757             if (delay > volume_LRU.promotion_interval[i]) {
5758                 /* unsigned overflow -- we're overdue to run this promotion */
5759                 min_delay = 0;
5760                 min_idx = i;
5761                 min_op = 1;
5762                 overdue = 1;
5763                 break;
5764             }
5765         }
5766
5767         /* sleep as needed */
5768         if (min_delay) {
5769             sleep(min_delay);
5770         }
5771
5772         /* do whatever is next */
5773         VOL_LOCK;
5774         if (min_op) {
5775             VLRU_Promote_r(min_idx);
5776             VLRU_Demote_r(min_idx+1);
5777         } else {
5778             VLRU_Scan_r(min_idx);
5779         }
5780         now = FT_ApproxTime();
5781     }
5782
5783     Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
5784
5785     /* signal that scanner is down */
5786     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5787     assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5788     VOL_UNLOCK;
5789     return NULL;
5790 }
5791
5792 /**
5793  * promote volumes from one VLRU generation to the next.
5794  *
5795  * This routine scans a VLRU generation looking for volumes which are
5796  * eligible to be promoted to the next generation.  All volumes which
5797  * meet the eligibility requirement are promoted.
5798  *
5799  * Promotion eligibility is based upon meeting both of the following
5800  * requirements:
5801  *
5802  *    @arg The volume has been accessed since the last promotion:
5803  *         @c (vp->stats.last_get >= vp->stats.last_promote)
5804  *    @arg The last promotion occurred at least 
5805  *         @c volume_LRU.promotion_interval[idx] seconds ago
5806  *
5807  * As a performance optimization, promotions are "globbed".  In other
5808  * words, we promote arbitrarily large contiguous sublists of elements
5809  * as one operation.  
5810  *
5811  * @param[in] idx  VLRU queue index to scan
5812  *
5813  * @note DAFS only
5814  *
5815  * @internal VLRU internal use only.
5816  */
5817 static void
5818 VLRU_Promote_r(int idx)
5819 {
5820     int len, chaining, promote;
5821     afs_uint32 now, thresh;
5822     struct rx_queue *qp, *nqp;
5823     Volume * vp, *start, *end;
5824
5825     /* get exclusive access to two chains, and drop the glock */
5826     VLRU_Wait_r(&volume_LRU.q[idx]);
5827     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5828     VLRU_Wait_r(&volume_LRU.q[idx+1]);
5829     VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
5830     VOL_UNLOCK;
5831
5832     thresh = volume_LRU.promotion_interval[idx];
5833     now = FT_ApproxTime();
5834
5835     len = chaining = 0;
5836     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5837         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5838         promote = (((vp->stats.last_promote + thresh) <= now) &&
5839                    (vp->stats.last_get >= vp->stats.last_promote));
5840
5841         if (chaining) {
5842             if (promote) {
5843                 vp->vlru.idx++;
5844                 len++;
5845                 start = vp;
5846             } else {
5847                 /* promote and prepend chain */
5848                 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5849                 chaining = 0;
5850             }
5851         } else {
5852             if (promote) {
5853                 vp->vlru.idx++;
5854                 len++;
5855                 chaining = 1;
5856                 start = end = vp;
5857             }
5858         }
5859     }
5860
5861     if (chaining) {
5862         /* promote and prepend */
5863         queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5864     }
5865
5866     if (len) {
5867         volume_LRU.q[idx].len -= len;
5868         volume_LRU.q[idx+1].len += len;
5869     }
5870
5871     /* release exclusive access to the two chains */
5872     VOL_LOCK;
5873     volume_LRU.last_promotion[idx] = now;
5874     VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5875     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5876 }
5877
5878 /* run the demotions */
5879 static void
5880 VLRU_Demote_r(int idx)
5881 {
5882     Error ec;
5883     int len, chaining, demote;
5884     afs_uint32 now, thresh;
5885     struct rx_queue *qp, *nqp;
5886     Volume * vp, *start, *end;
5887     Volume ** salv_flag_vec = NULL;
5888     int salv_vec_offset = 0;
5889
5890     assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5891
5892     /* get exclusive access to two chains, and drop the glock */
5893     VLRU_Wait_r(&volume_LRU.q[idx-1]);
5894     VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5895     VLRU_Wait_r(&volume_LRU.q[idx]);
5896     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5897     VOL_UNLOCK;
5898
5899     /* no big deal if this allocation fails */
5900     if (volume_LRU.q[idx].len) {
5901         salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
5902     }
5903
5904     now = FT_ApproxTime();
5905     thresh = volume_LRU.promotion_interval[idx-1];
5906
5907     len = chaining = 0;
5908     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5909         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5910         demote = (((vp->stats.last_promote + thresh) <= now) &&
5911                   (vp->stats.last_get < (now - thresh)));
5912
5913         /* we now do volume update list DONT_SALVAGE flag setting during
5914          * demotion passes */
5915         if (salv_flag_vec &&
5916             !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5917             demote && 
5918             (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5919             (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5920             salv_flag_vec[salv_vec_offset++] = vp;
5921             VCreateReservation_r(vp);
5922         }
5923
5924         if (chaining) {
5925             if (demote) {
5926                 vp->vlru.idx--;
5927                 len++;
5928                 start = vp;
5929             } else {
5930                 /* demote and append chain */
5931                 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5932                 chaining = 0;
5933             }
5934         } else {
5935             if (demote) {
5936                 vp->vlru.idx--;
5937                 len++;
5938                 chaining = 1;
5939                 start = end = vp;
5940             }
5941         }
5942     }
5943
5944     if (chaining) {
5945         queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5946     }
5947
5948     if (len) {
5949         volume_LRU.q[idx].len -= len;
5950         volume_LRU.q[idx-1].len += len;
5951     }
5952
5953     /* release exclusive access to the two chains */
5954     VOL_LOCK;
5955     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5956     VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
5957
5958     /* now go back and set the DONT_SALVAGE flags as appropriate */
5959     if (salv_flag_vec) {
5960         int i;
5961         for (i = 0; i < salv_vec_offset; i++) {
5962             vp = salv_flag_vec[i];
5963             if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5964                 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5965                 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5966                 ec = VHold_r(vp);
5967                 if (!ec) {
5968                     V_attachFlags(vp) |= VOL_HDR_DONTSALV;
5969                     V_dontSalvage(vp) = DONT_SALVAGE;
5970                     VUpdateVolume_r(&ec, vp, 0);
5971                     VPutVolume_r(vp);
5972                 }
5973             }
5974             VCancelReservation_r(vp);
5975         }
5976         free(salv_flag_vec);
5977     }
5978 }
5979
5980 /* run a pass of the VLRU GC scanner */
5981 static void
5982 VLRU_Scan_r(int idx)
5983 {
5984     afs_uint32 now, thresh;
5985     struct rx_queue *qp, *nqp;
5986     volatile Volume * vp;
5987     int i, locked = 1;
5988
5989     assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
5990
5991     /* gain exclusive access to the idx VLRU */
5992     VLRU_Wait_r(&volume_LRU.q[idx]);
5993     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5994
5995     if (idx != VLRU_QUEUE_CANDIDATE) {
5996         /* gain exclusive access to the candidate VLRU */
5997         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5998         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5999     }
6000
6001     now = FT_ApproxTime();
6002     thresh = now - VLRU_offline_thresh;
6003
6004     /* perform candidate selection and soft detaching */
6005     if (idx == VLRU_QUEUE_CANDIDATE) {
6006         /* soft detach some volumes from the candidate pool */
6007         VOL_UNLOCK;
6008         locked = 0;
6009
6010         for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6011             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6012             if (i >= VLRU_offline_max) {
6013                 break;
6014             }
6015             /* check timestamp to see if it's a candidate for soft detaching */
6016             if (vp->stats.last_get <= thresh) {
6017                 VOL_LOCK;
6018                 if (VCheckSoftDetach(vp, thresh))
6019                     i++;
6020                 VOL_UNLOCK;
6021             }
6022         }
6023     } else {
6024         /* scan for volumes to become soft detach candidates */
6025         for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6026             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6027
6028             /* check timestamp to see if it's a candidate for soft detaching */
6029             if (vp->stats.last_get <= thresh) {
6030                 VCheckSoftDetachCandidate(vp, thresh);
6031             }
6032
6033             if (!(i&0x7f)) {   /* lock coarsening optimization */
6034                 VOL_UNLOCK;
6035                 pthread_yield();
6036                 VOL_LOCK;
6037             }
6038         }
6039     }
6040
6041     /* relinquish exclusive access to the VLRU chains */
6042     if (!locked) {
6043         VOL_LOCK;
6044     }
6045     volume_LRU.last_scan[idx] = now;
6046     if (idx != VLRU_QUEUE_CANDIDATE) {
6047         VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6048     }
6049     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6050 }
6051
6052 /* check whether volume is safe to soft detach
6053  * caller MUST NOT hold a ref count on vp */
6054 static int
6055 VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh)
6056 {
6057     int ret=0;
6058
6059     if (vp->nUsers || vp->nWaiters)
6060         return 0;
6061
6062     if (vp->stats.last_get <= thresh) {
6063         ret = VSoftDetachVolume_r(vp, thresh);
6064     }
6065
6066     return ret;
6067 }
6068
6069 /* check whether volume should be made a 
6070  * soft detach candidate */
6071 static int
6072 VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh)
6073 {
6074     int idx, ret = 0;
6075     if (vp->nUsers || vp->nWaiters)
6076         return 0;
6077
6078     idx = vp->vlru.idx;
6079
6080     assert(idx == VLRU_QUEUE_NEW);
6081
6082     if (vp->stats.last_get <= thresh) {
6083         /* move to candidate pool */
6084         queue_Remove(&vp->vlru);
6085         volume_LRU.q[VLRU_QUEUE_NEW].len--;
6086         queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6087         vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6088         volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6089         ret = 1;
6090     }
6091
6092     return ret;
6093 }
6094
6095
6096 /* begin exclusive access on VLRU */
6097 static void
6098 VLRU_BeginExclusive_r(struct VLRU_q * q)
6099 {
6100     assert(q->busy == 0);
6101     q->busy = 1;
6102 }
6103
6104 /* end exclusive access on VLRU */
6105 static void
6106 VLRU_EndExclusive_r(struct VLRU_q * q)
6107 {
6108     assert(q->busy);
6109     q->busy = 0;
6110     assert(pthread_cond_broadcast(&q->cv) == 0);
6111 }
6112
6113 /* wait for another thread to end exclusive access on VLRU */
6114 static void
6115 VLRU_Wait_r(struct VLRU_q * q)
6116 {
6117     while(q->busy) {
6118         VOL_CV_WAIT(&q->cv);
6119     }
6120 }
6121
6122 /* demand attach fs
6123  * volume soft detach
6124  *
6125  * caller MUST NOT hold a ref count on vp */
6126 static int
6127 VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh)
6128 {
6129     afs_uint32 ts_save;
6130     int ret = 0;
6131
6132     assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6133
6134     ts_save = vp->stats.last_get;
6135     if (ts_save > thresh)
6136         return 0;
6137
6138     if (vp->nUsers || vp->nWaiters)
6139         return 0;
6140
6141     if (VIsExclusiveState(V_attachState(vp))) {
6142         return 0;
6143     }
6144
6145     switch (V_attachState(vp)) {
6146     case VOL_STATE_UNATTACHED:
6147     case VOL_STATE_PREATTACHED:
6148     case VOL_STATE_ERROR:
6149     case VOL_STATE_GOING_OFFLINE:
6150     case VOL_STATE_SHUTTING_DOWN:
6151     case VOL_STATE_SALVAGING:
6152         volume_LRU.q[vp->vlru.idx].len--;
6153
6154         /* create and cancel a reservation to
6155          * give the volume an opportunity to
6156          * be deallocated */
6157         VCreateReservation_r(vp);
6158         queue_Remove(&vp->vlru);
6159         vp->vlru.idx = VLRU_QUEUE_INVALID;
6160         V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6161         VCancelReservation_r(vp);
6162         return 0;
6163     }
6164
6165     /* hold the volume and take it offline.
6166      * no need for reservations, as VHold_r
6167      * takes care of that internally. */
6168     if (VHold_r(vp) == 0) {
6169         /* vhold drops the glock, so now we should
6170          * check to make sure we aren't racing against
6171          * other threads.  if we are racing, offlining vp
6172          * would be wasteful, and block the scanner for a while 
6173          */
6174         if (vp->nWaiters || 
6175             (vp->nUsers > 1) ||
6176             (vp->shuttingDown) ||
6177             (vp->goingOffline) ||
6178             (vp->stats.last_get != ts_save)) {
6179             /* looks like we're racing someone else. bail */
6180             VPutVolume_r(vp);
6181             vp = NULL;
6182         } else {
6183             /* pull it off the VLRU */
6184             assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6185             volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6186             queue_Remove(&vp->vlru);
6187             vp->vlru.idx = VLRU_QUEUE_INVALID;
6188             V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6189
6190             /* take if offline */
6191             VOffline_r(vp, "volume has been soft detached");
6192
6193             /* invalidate the volume header cache */
6194             FreeVolumeHeader(vp);
6195
6196             /* update stats */
6197             IncUInt64(&VStats.soft_detaches);
6198             vp->stats.soft_detaches++;
6199
6200             /* put in pre-attached state so demand
6201              * attacher can work on it */
6202             VChangeState_r(vp, VOL_STATE_PREATTACHED);
6203             ret = 1;
6204         }
6205     }
6206     return ret;
6207 }
6208 #endif /* AFS_DEMAND_ATTACH_FS */
6209
6210
6211 /***************************************************/
6212 /* Volume Header Cache routines                    */
6213 /***************************************************/
6214
6215 /** 
6216  * volume header cache.
6217  */
6218 struct volume_hdr_LRU_t volume_hdr_LRU;
6219
6220 /**
6221  * initialize the volume header cache.
6222  *
6223  * @param[in] howMany  number of header cache entries to preallocate
6224  *
6225  * @pre VOL_LOCK held.  Function has never been called before.
6226  *
6227  * @post howMany cache entries are allocated, initialized, and added 
6228  *       to the LRU list.  Header cache statistics are initialized.
6229  *
6230  * @note only applicable to fileServer program type.  Should only be
6231  *       called once during volume package initialization.
6232  *
6233  * @internal volume package internal use only.
6234  */
6235 static void
6236 VInitVolumeHeaderCache(afs_uint32 howMany)
6237 {
6238     register struct volHeader *hp;
6239     if (programType != fileServer)
6240         return;
6241     queue_Init(&volume_hdr_LRU);
6242     volume_hdr_LRU.stats.free = 0;
6243     volume_hdr_LRU.stats.used = howMany;
6244     volume_hdr_LRU.stats.attached = 0;
6245     hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6246     assert(hp != NULL);
6247
6248     while (howMany--)
6249         /* We are using ReleaseVolumeHeader to initialize the values on the header list
6250          * to ensure they have the right values
6251          */
6252         ReleaseVolumeHeader(hp++);
6253 }
6254
6255 /**
6256  * get a volume header and attach it to the volume object.
6257  *
6258  * @param[in] vp  pointer to volume object
6259  *
6260  * @return cache entry status
6261  *    @retval 0  volume header was newly attached; cache data is invalid
6262  *    @retval 1  volume header was previously attached; cache data is valid
6263  *
6264  * @pre VOL_LOCK held.  For DAFS, lightweight ref must be held on volume object.
6265  *
6266  * @post volume header attached to volume object.  if necessary, header cache 
6267  *       entry on LRU is synchronized to disk.  Header is removed from LRU list.
6268  *
6269  * @note VOL_LOCK may be dropped
6270  *
6271  * @warning this interface does not load header data from disk.  it merely
6272  *          attaches a header object to the volume object, and may sync the old
6273  *          header cache data out to disk in the process.
6274  *
6275  * @internal volume package internal use only.
6276  */
6277 static int
6278 GetVolumeHeader(register Volume * vp)
6279 {
6280     Error error;
6281     register struct volHeader *hd;
6282     int old;
6283     static int everLogged = 0;
6284
6285 #ifdef AFS_DEMAND_ATTACH_FS
6286     VolState vp_save, back_save;
6287
6288     /* XXX debug 9/19/05 we've apparently got
6289      * a ref counting bug somewhere that's
6290      * breaking the nUsers == 0 => header on LRU
6291      * assumption */
6292     if (vp->header && queue_IsNotOnQueue(vp->header)) {
6293         Log("nUsers == 0, but header not on LRU\n");
6294         return 1;
6295     }
6296 #endif
6297
6298     old = (vp->header != NULL); /* old == volume already has a header */
6299
6300     if (programType != fileServer) {
6301         /* for volume utilities, we allocate volHeaders as needed */
6302         if (!vp->header) {
6303             hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6304             assert(hd != NULL);
6305             vp->header = hd;
6306             hd->back = vp;
6307 #ifdef AFS_DEMAND_ATTACH_FS
6308             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6309 #endif
6310         }
6311     } else {
6312         /* for the fileserver, we keep a volume header cache */
6313         if (old) {
6314             /* the header we previously dropped in the lru is
6315              * still available. pull it off the lru and return */
6316             hd = vp->header;
6317             queue_Remove(hd);
6318             assert(hd->back == vp);
6319         } else {
6320             /* we need to grab a new element off the LRU */
6321             if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6322                 /* grab an element and pull off of LRU */
6323                 hd = queue_First(&volume_hdr_LRU, volHeader);
6324                 queue_Remove(hd);
6325             } else {
6326                 /* LRU is empty, so allocate a new volHeader 
6327                  * this is probably indicative of a leak, so let the user know */
6328                 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6329                 assert(hd != NULL);
6330                 if (!everLogged) {
6331                     Log("****Allocated more volume headers, probably leak****\n");
6332                     everLogged = 1;
6333                 }
6334                 volume_hdr_LRU.stats.free++;
6335             }
6336             if (hd->back) {
6337                 /* this header used to belong to someone else. 
6338                  * we'll need to check if the header needs to
6339                  * be sync'd out to disk */
6340
6341 #ifdef AFS_DEMAND_ATTACH_FS
6342                 /* if hd->back were in an exclusive state, then
6343                  * its volHeader would not be on the LRU... */
6344                 assert(!VIsExclusiveState(V_attachState(hd->back)));
6345 #endif
6346
6347                 if (hd->diskstuff.inUse) {
6348                     /* volume was in use, so we'll need to sync
6349                      * its header to disk */
6350
6351 #ifdef AFS_DEMAND_ATTACH_FS
6352                     back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6353                     vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6354                     VCreateReservation_r(hd->back);
6355                     VOL_UNLOCK;
6356 #endif
6357
6358                     WriteVolumeHeader_r(&error, hd->back);
6359                     /* Ignore errors; catch them later */
6360
6361 #ifdef AFS_DEMAND_ATTACH_FS
6362                     VOL_LOCK;
6363 #endif
6364                 }
6365
6366                 hd->back->header = NULL;
6367 #ifdef AFS_DEMAND_ATTACH_FS
6368                 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6369
6370                 if (hd->diskstuff.inUse) {
6371                     VChangeState_r(hd->back, back_save);
6372                     VCancelReservation_r(hd->back);
6373                     VChangeState_r(vp, vp_save);
6374                 }
6375 #endif
6376             } else {
6377                 volume_hdr_LRU.stats.attached++;
6378             }
6379             hd->back = vp;
6380             vp->header = hd;
6381 #ifdef AFS_DEMAND_ATTACH_FS
6382             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6383 #endif
6384         }
6385         volume_hdr_LRU.stats.free--;
6386         volume_hdr_LRU.stats.used++;
6387     }
6388     IncUInt64(&VStats.hdr_gets);
6389 #ifdef AFS_DEMAND_ATTACH_FS
6390     IncUInt64(&vp->stats.hdr_gets);
6391     vp->stats.last_hdr_get = FT_ApproxTime();
6392 #endif
6393     return old;
6394 }
6395
6396
6397 /**
6398  * make sure volume header is attached and contains valid cache data.
6399  *
6400  * @param[out] ec  outbound error code
6401  * @param[in]  vp  pointer to volume object
6402  *
6403  * @pre VOL_LOCK held.  For DAFS, lightweight ref held on vp.
6404  *
6405  * @post header cache entry attached, and loaded with valid data, or
6406  *       *ec is nonzero, and the header is released back into the LRU.
6407  *
6408  * @internal volume package internal use only.
6409  */
6410 static void
6411 LoadVolumeHeader(Error * ec, Volume * vp)
6412 {
6413 #ifdef AFS_DEMAND_ATTACH_FS
6414     VolState state_save;
6415     afs_uint32 now;
6416     *ec = 0;
6417
6418     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6419         IncUInt64(&VStats.hdr_loads);
6420         state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6421         VOL_UNLOCK;
6422
6423         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6424                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6425                    VOLUMEINFOVERSION);
6426         IncUInt64(&vp->stats.hdr_loads);
6427         now = FT_ApproxTime();
6428
6429         VOL_LOCK;
6430         if (!*ec) {
6431             V_attachFlags(vp) |= VOL_HDR_LOADED;
6432             vp->stats.last_hdr_load = now;
6433         }
6434         VChangeState_r(vp, state_save);
6435     }
6436 #else /* AFS_DEMAND_ATTACH_FS */
6437     *ec = 0;
6438     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6439         IncUInt64(&VStats.hdr_loads);
6440
6441         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6442                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6443                    VOLUMEINFOVERSION);
6444     }
6445 #endif /* AFS_DEMAND_ATTACH_FS */
6446     if (*ec) {
6447         /* maintain (nUsers==0) => header in LRU invariant */
6448         FreeVolumeHeader(vp);
6449     }
6450 }
6451
6452 /**
6453  * release a header cache entry back into the LRU list.
6454  *
6455  * @param[in] hd  pointer to volume header cache object
6456  *
6457  * @pre VOL_LOCK held.
6458  *
6459  * @post header cache object appended onto end of LRU list.
6460  *
6461  * @note only applicable to fileServer program type.
6462  *
6463  * @note used to place a header cache entry back into the
6464  *       LRU pool without invalidating it as a cache entry.
6465  *
6466  * @internal volume package internal use only.
6467  */
6468 static void
6469 ReleaseVolumeHeader(register struct volHeader *hd)
6470 {
6471     if (programType != fileServer)
6472         return;
6473     if (!hd || queue_IsOnQueue(hd))     /* no header, or header already released */
6474         return;
6475     queue_Append(&volume_hdr_LRU, hd);
6476 #ifdef AFS_DEMAND_ATTACH_FS
6477     if (hd->back) {
6478         V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6479     }
6480 #endif
6481     volume_hdr_LRU.stats.free++;
6482     volume_hdr_LRU.stats.used--;
6483 }
6484
6485 /**
6486  * free/invalidate a volume header cache entry.
6487  *
6488  * @param[in] vp  pointer to volume object
6489  *
6490  * @pre VOL_LOCK is held.
6491  *
6492  * @post For fileserver, header cache entry is returned to LRU, and it is
6493  *       invalidated as a cache entry.  For volume utilities, the header
6494  *       cache entry is freed.
6495  *
6496  * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6497  *       whenever it is necessary to invalidate the header cache entry.
6498  *
6499  * @see ReleaseVolumeHeader
6500  *
6501  * @internal volume package internal use only.
6502  */
6503 static void
6504 FreeVolumeHeader(register Volume * vp)
6505 {
6506     register struct volHeader *hd = vp->header;
6507     if (!hd)
6508         return;
6509     if (programType == fileServer) {
6510         ReleaseVolumeHeader(hd);
6511         hd->back = NULL;
6512     } else {
6513         free(hd);
6514     }
6515 #ifdef AFS_DEMAND_ATTACH_FS
6516     V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6517 #endif
6518     volume_hdr_LRU.stats.attached--;
6519     vp->header = NULL;
6520 }
6521
6522
6523 /***************************************************/
6524 /* Volume Hash Table routines                      */
6525 /***************************************************/
6526
6527 /**
6528  * set size of volume object hash table.
6529  *
6530  * @param[in] logsize   log(2) of desired hash table size
6531  *
6532  * @return operation status
6533  *    @retval 0 success
6534  *    @retval -1 failure
6535  *
6536  * @pre MUST be called prior to VInitVolumePackage
6537  *
6538  * @post Volume Hash Table will have 2^logsize buckets
6539  */
6540 int 
6541 VSetVolHashSize(int logsize)
6542 {
6543     /* 64 to 16384 hash buckets seems like a reasonable range */
6544     if ((logsize < 6 ) || (logsize > 14)) {
6545         return -1;
6546     }
6547     
6548     if (!VInit) {
6549         VolumeHashTable.Size = 1 << logsize;
6550         VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6551     } else {
6552         /* we can't yet support runtime modification of this
6553          * parameter. we'll need a configuration rwlock to
6554          * make runtime modification feasible.... */
6555         return -1;
6556     }
6557     return 0;
6558 }
6559
6560 /**
6561  * initialize dynamic data structures for volume hash table.
6562  *
6563  * @post hash table is allocated, and fields are initialized.
6564  *
6565  * @internal volume package internal use only.
6566  */
6567 static void
6568 VInitVolumeHash(void)
6569 {
6570     register int i;
6571
6572     VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size, 
6573                                                            sizeof(VolumeHashChainHead));
6574     assert(VolumeHashTable.Table != NULL);
6575     
6576     for (i=0; i < VolumeHashTable.Size; i++) {
6577         queue_Init(&VolumeHashTable.Table[i]);
6578 #ifdef AFS_DEMAND_ATTACH_FS
6579         assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6580 #endif /* AFS_DEMAND_ATTACH_FS */
6581     }
6582 }
6583
6584 /**
6585  * add a volume object to the hash table.
6586  *
6587  * @param[in] vp      pointer to volume object
6588  * @param[in] hashid  hash of volume id
6589  *
6590  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
6591  *      reference on vp.
6592  *
6593  * @post volume is added to hash chain.
6594  *
6595  * @internal volume package internal use only.
6596  *
6597  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6598  *       asynchronous hash chain reordering to finish.
6599  */
6600 static void
6601 AddVolumeToHashTable(register Volume * vp, int hashid)
6602 {
6603     VolumeHashChainHead * head;
6604
6605     if (queue_IsOnQueue(vp))
6606         return;
6607
6608     head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6609
6610 #ifdef AFS_DEMAND_ATTACH_FS
6611     /* wait for the hash chain to become available */
6612     VHashWait_r(head);
6613
6614     V_attachFlags(vp) |= VOL_IN_HASH;
6615     vp->chainCacheCheck = ++head->cacheCheck;
6616 #endif /* AFS_DEMAND_ATTACH_FS */
6617
6618     head->len++;
6619     vp->hashid = hashid;
6620     queue_Append(head, vp);
6621     vp->vnodeHashOffset = VolumeHashOffset_r();
6622 }
6623
6624 /**
6625  * delete a volume object from the hash table.
6626  *
6627  * @param[in] vp  pointer to volume object
6628  *
6629  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
6630  *      reference on vp.
6631  *
6632  * @post volume is removed from hash chain.
6633  *
6634  * @internal volume package internal use only.
6635  *
6636  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6637  *       asynchronous hash chain reordering to finish.
6638  */
6639 static void
6640 DeleteVolumeFromHashTable(register Volume * vp)
6641 {
6642     VolumeHashChainHead * head;
6643
6644     if (!queue_IsOnQueue(vp))
6645         return;
6646
6647     head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6648
6649 #ifdef AFS_DEMAND_ATTACH_FS
6650     /* wait for the hash chain to become available */
6651     VHashWait_r(head);
6652
6653     V_attachFlags(vp) &= ~(VOL_IN_HASH);
6654     head->cacheCheck++;
6655 #endif /* AFS_DEMAND_ATTACH_FS */
6656
6657     head->len--;
6658     queue_Remove(vp);
6659     /* do NOT reset hashid to zero, as the online
6660      * salvager package may need to know the volume id
6661      * after the volume is removed from the hash */
6662 }
6663
6664 /**
6665  * lookup a volume object in the hash table given a volume id.
6666  *
6667  * @param[out] ec        error code return
6668  * @param[in]  volumeId  volume id
6669  * @param[in]  hint      volume object which we believe could be the correct 
6670                          mapping
6671  *
6672  * @return volume object pointer
6673  *    @retval NULL  no such volume id is registered with the hash table.
6674  *
6675  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight 
6676         ref on hint.
6677  *
6678  * @post volume object with the given id is returned.  volume object and 
6679  *       hash chain access statistics are updated.  hash chain may have 
6680  *       been reordered.
6681  *
6682  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an 
6683  *       asynchronous hash chain reordering operation to finish, or 
6684  *       in order for us to perform an asynchronous chain reordering.
6685  *
6686  * @note Hash chain reorderings occur when the access count for the 
6687  *       volume object being looked up exceeds the sum of the previous 
6688  *       node's (the node ahead of it in the hash chain linked list) 
6689  *       access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6690  *
6691  * @note For DAFS, the hint parameter allows us to short-circuit if the 
6692  *       cacheCheck fields match between the hash chain head and the 
6693  *       hint volume object.
6694  */
6695 Volume *
6696 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6697 {
6698     register int looks = 0;
6699     Volume * vp, *np;
6700 #ifdef AFS_DEMAND_ATTACH_FS
6701     Volume *pp;
6702 #endif
6703     VolumeHashChainHead * head;
6704     *ec = 0;
6705
6706     head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6707
6708 #ifdef AFS_DEMAND_ATTACH_FS
6709     /* wait for the hash chain to become available */
6710     VHashWait_r(head);
6711
6712     /* check to see if we can short circuit without walking the hash chain */
6713     if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6714         IncUInt64(&hint->stats.hash_short_circuits);
6715         return hint;
6716     }
6717 #endif /* AFS_DEMAND_ATTACH_FS */
6718
6719     /* someday we need to either do per-chain locks, RWlocks,
6720      * or both for volhash access. 
6721      * (and move to a data structure with better cache locality) */
6722
6723     /* search the chain for this volume id */
6724     for(queue_Scan(head, vp, np, Volume)) {
6725         looks++;
6726         if ((vp->hashid == volumeId)) {
6727             break;
6728         }
6729     }
6730
6731     if (queue_IsEnd(head, vp)) {
6732         vp = NULL;
6733     }
6734
6735 #ifdef AFS_DEMAND_ATTACH_FS
6736     /* update hash chain statistics */
6737     {
6738         afs_uint64 lks;
6739         FillInt64(lks, 0, looks);
6740         AddUInt64(head->looks, lks, &head->looks);
6741         AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6742         IncUInt64(&head->gets);
6743     }
6744
6745     if (vp) {
6746         afs_uint64 thresh;
6747         IncUInt64(&vp->stats.hash_lookups);
6748
6749         /* for demand attach fileserver, we permit occasional hash chain reordering
6750          * so that frequently looked up volumes move towards the head of the chain */
6751         pp = queue_Prev(vp, Volume);
6752         if (!queue_IsEnd(head, pp)) {
6753             FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
6754             AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
6755             if (GEInt64(vp->stats.hash_lookups, thresh)) {
6756                 VReorderHash_r(head, pp, vp);
6757             }
6758         }
6759
6760         /* update the short-circuit cache check */
6761         vp->chainCacheCheck = head->cacheCheck;
6762     }
6763 #endif /* AFS_DEMAND_ATTACH_FS */    
6764
6765     return vp;
6766 }
6767
6768 #ifdef AFS_DEMAND_ATTACH_FS
6769 /* perform volume hash chain reordering.
6770  *
6771  * advance a subchain beginning at vp ahead of
6772  * the adjacent subchain ending at pp */
6773 static void
6774 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
6775 {
6776     Volume *tp, *np, *lp;
6777     afs_uint64 move_thresh;
6778
6779     /* this should never be called if the chain is already busy, so
6780      * no need to wait for other exclusive chain ops to finish */
6781
6782     /* this is a rather heavy set of operations,
6783      * so let's set the chain busy flag and drop
6784      * the vol_glock */
6785     VHashBeginExclusive_r(head);
6786     VOL_UNLOCK;
6787
6788     /* scan forward in the chain from vp looking for the last element
6789      * in the chain we want to advance */
6790     FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
6791     AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
6792     for(queue_ScanFrom(head, vp, tp, np, Volume)) {
6793         if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
6794             break;
6795         }
6796     }
6797     lp = queue_Prev(tp, Volume);
6798
6799     /* scan backwards from pp to determine where to splice and
6800      * insert the subchain we're advancing */
6801     for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
6802         if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
6803             break;
6804         }
6805     }
6806     tp = queue_Next(tp, Volume);
6807
6808     /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
6809     queue_MoveChainBefore(tp,vp,lp);
6810
6811     VOL_LOCK;
6812     IncUInt64(&VStats.hash_reorders);
6813     head->cacheCheck++;
6814     IncUInt64(&head->reorders);
6815
6816     /* wake up any threads waiting for the hash chain */
6817     VHashEndExclusive_r(head);
6818 }
6819
6820
6821 /* demand-attach fs volume hash
6822  * asynchronous exclusive operations */
6823
6824 /**
6825  * begin an asynchronous exclusive operation on a volume hash chain.
6826  *
6827  * @param[in] head   pointer to volume hash chain head object
6828  *
6829  * @pre VOL_LOCK held.  hash chain is quiescent.
6830  *
6831  * @post hash chain marked busy.
6832  *
6833  * @note this interface is used in conjunction with VHashEndExclusive_r and
6834  *       VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
6835  *       volume hash chain.  Its main use case is hash chain reordering, which
6836  *       has the potential to be a highly latent operation.
6837  *
6838  * @see VHashEndExclusive_r
6839  * @see VHashWait_r
6840  *
6841  * @note DAFS only
6842  *
6843  * @internal volume package internal use only.
6844  */
6845 static void
6846 VHashBeginExclusive_r(VolumeHashChainHead * head)
6847 {
6848     assert(head->busy == 0);
6849     head->busy = 1;
6850 }
6851
6852 /**
6853  * relinquish exclusive ownership of a volume hash chain.
6854  *
6855  * @param[in] head   pointer to volume hash chain head object
6856  *
6857  * @pre VOL_LOCK held.  thread owns the hash chain exclusively.
6858  *
6859  * @post hash chain is marked quiescent.  threads awaiting use of
6860  *       chain are awakened.
6861  *
6862  * @see VHashBeginExclusive_r
6863  * @see VHashWait_r
6864  *
6865  * @note DAFS only
6866  *
6867  * @internal volume package internal use only.
6868  */
6869 static void
6870 VHashEndExclusive_r(VolumeHashChainHead * head)
6871 {
6872     assert(head->busy);
6873     head->busy = 0;
6874     assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
6875 }
6876
6877 /**
6878  * wait for all asynchronous operations on a hash chain to complete.
6879  *
6880  * @param[in] head   pointer to volume hash chain head object
6881  *
6882  * @pre VOL_LOCK held.
6883  *
6884  * @post hash chain object is quiescent.
6885  *
6886  * @see VHashBeginExclusive_r
6887  * @see VHashEndExclusive_r
6888  *
6889  * @note DAFS only
6890  *
6891  * @note This interface should be called before any attempt to
6892  *       traverse the hash chain.  It is permissible for a thread
6893  *       to gain exclusive access to the chain, and then perform
6894  *       latent operations on the chain asynchronously wrt the 
6895  *       VOL_LOCK.
6896  *
6897  * @warning if waiting is necessary, VOL_LOCK is dropped
6898  *
6899  * @internal volume package internal use only.
6900  */
6901 static void
6902 VHashWait_r(VolumeHashChainHead * head)
6903 {
6904     while (head->busy) {
6905         VOL_CV_WAIT(&head->chain_busy_cv);
6906     }
6907 }
6908 #endif /* AFS_DEMAND_ATTACH_FS */
6909
6910
6911 /***************************************************/
6912 /* Volume by Partition List routines               */
6913 /***************************************************/
6914
6915 /*
6916  * demand attach fileserver adds a
6917  * linked list of volumes to each
6918  * partition object, thus allowing
6919  * for quick enumeration of all
6920  * volumes on a partition
6921  */
6922
6923 #ifdef AFS_DEMAND_ATTACH_FS
6924 /**
6925  * add a volume to its disk partition VByPList.
6926  *
6927  * @param[in] vp  pointer to volume object
6928  *
6929  * @pre either the disk partition VByPList is owned exclusively
6930  *      by the calling thread, or the list is quiescent and
6931  *      VOL_LOCK is held.
6932  *
6933  * @post volume is added to disk partition VByPList
6934  *
6935  * @note DAFS only
6936  *
6937  * @warning it is the caller's responsibility to ensure list
6938  *          quiescence.
6939  *
6940  * @see VVByPListWait_r
6941  * @see VVByPListBeginExclusive_r
6942  * @see VVByPListEndExclusive_r
6943  *
6944  * @internal volume package internal use only.
6945  */
6946 static void
6947 AddVolumeToVByPList_r(Volume * vp)
6948 {
6949     if (queue_IsNotOnQueue(&vp->vol_list)) {
6950         queue_Append(&vp->partition->vol_list, &vp->vol_list);
6951         V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
6952         vp->partition->vol_list.len++;
6953     }
6954 }
6955
6956 /**
6957  * delete a volume from its disk partition VByPList.
6958  *
6959  * @param[in] vp  pointer to volume object
6960  *
6961  * @pre either the disk partition VByPList is owned exclusively
6962  *      by the calling thread, or the list is quiescent and
6963  *      VOL_LOCK is held.
6964  *
6965  * @post volume is removed from the disk partition VByPList
6966  *
6967  * @note DAFS only
6968  *
6969  * @warning it is the caller's responsibility to ensure list
6970  *          quiescence.
6971  *
6972  * @see VVByPListWait_r
6973  * @see VVByPListBeginExclusive_r
6974  * @see VVByPListEndExclusive_r
6975  *
6976  * @internal volume package internal use only.
6977  */
6978 static void
6979 DeleteVolumeFromVByPList_r(Volume * vp)
6980 {
6981     if (queue_IsOnQueue(&vp->vol_list)) {
6982         queue_Remove(&vp->vol_list);
6983         V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
6984         vp->partition->vol_list.len--;
6985     }
6986 }
6987
6988 /**
6989  * begin an asynchronous exclusive operation on a VByPList.
6990  *
6991  * @param[in] dp   pointer to disk partition object
6992  *
6993  * @pre VOL_LOCK held.  VByPList is quiescent.
6994  *
6995  * @post VByPList marked busy.
6996  *
6997  * @note this interface is used in conjunction with VVByPListEndExclusive_r and
6998  *       VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
6999  *       VByPList.
7000  *
7001  * @see VVByPListEndExclusive_r
7002  * @see VVByPListWait_r
7003  *
7004  * @note DAFS only
7005  *
7006  * @internal volume package internal use only.
7007  */
7008 /* take exclusive control over the list */
7009 static void
7010 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7011 {
7012     assert(dp->vol_list.busy == 0);
7013     dp->vol_list.busy = 1;
7014 }
7015
7016 /**
7017  * relinquish exclusive ownership of a VByPList.
7018  *
7019  * @param[in] dp   pointer to disk partition object
7020  *
7021  * @pre VOL_LOCK held.  thread owns the VByPList exclusively.
7022  *
7023  * @post VByPList is marked quiescent.  threads awaiting use of
7024  *       the list are awakened.
7025  *
7026  * @see VVByPListBeginExclusive_r
7027  * @see VVByPListWait_r
7028  *
7029  * @note DAFS only
7030  *
7031  * @internal volume package internal use only.
7032  */
7033 static void
7034 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7035 {
7036     assert(dp->vol_list.busy);
7037     dp->vol_list.busy = 0;
7038     assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7039 }
7040
7041 /**
7042  * wait for all asynchronous operations on a VByPList to complete.
7043  *
7044  * @param[in] dp  pointer to disk partition object
7045  *
7046  * @pre VOL_LOCK is held.
7047  *
7048  * @post disk partition's VByP list is quiescent
7049  *
7050  * @note DAFS only
7051  *
7052  * @note This interface should be called before any attempt to
7053  *       traverse the VByPList.  It is permissible for a thread
7054  *       to gain exclusive access to the list, and then perform
7055  *       latent operations on the list asynchronously wrt the 
7056  *       VOL_LOCK.
7057  *
7058  * @warning if waiting is necessary, VOL_LOCK is dropped
7059  *
7060  * @see VVByPListEndExclusive_r
7061  * @see VVByPListBeginExclusive_r
7062  *
7063  * @internal volume package internal use only.
7064  */
7065 static void
7066 VVByPListWait_r(struct DiskPartition64 * dp)
7067 {
7068     while (dp->vol_list.busy) {
7069         VOL_CV_WAIT(&dp->vol_list.cv);
7070     }
7071 }
7072 #endif /* AFS_DEMAND_ATTACH_FS */
7073
7074 /***************************************************/
7075 /* Volume Cache Statistics routines                */
7076 /***************************************************/
7077
7078 void
7079 VPrintCacheStats_r(void)
7080 {
7081     afs_uint32 get_hi, get_lo, load_hi, load_lo;
7082     register struct VnodeClassInfo *vcp;
7083     vcp = &VnodeClassInfo[vLarge];
7084     Log("Large vnode cache, %d entries, %d allocs, %d gets (%d reads), %d writes\n", vcp->cacheSize, vcp->allocs, vcp->gets, vcp->reads, vcp->writes);
7085     vcp = &VnodeClassInfo[vSmall];
7086     Log("Small vnode cache,%d entries, %d allocs, %d gets (%d reads), %d writes\n", vcp->cacheSize, vcp->allocs, vcp->gets, vcp->reads, vcp->writes);
7087     SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7088     SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7089     Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7090         VStats.hdr_cache_size, get_lo, load_lo);
7091 }
7092
7093 void
7094 VPrintCacheStats(void)
7095 {
7096     VOL_LOCK;
7097     VPrintCacheStats_r();
7098     VOL_UNLOCK;
7099 }
7100
7101 #ifdef AFS_DEMAND_ATTACH_FS
7102 static double
7103 UInt64ToDouble(afs_uint64 * x)
7104 {
7105     static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7106     afs_uint32 h, l;
7107     SplitInt64(*x, h, l);
7108     return (((double)h) * c32) + ((double) l);
7109 }
7110
7111 static char *
7112 DoubleToPrintable(double x, char * buf, int len)
7113 {
7114     static double billion = 1000000000.0;
7115     afs_uint32 y[3];
7116
7117     y[0] = (afs_uint32) (x / (billion * billion));
7118     y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7119     y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7120
7121     if (y[0]) {
7122         snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7123     } else if (y[1]) {
7124         snprintf(buf, len, "%d%09d", y[1], y[2]);
7125     } else {
7126         snprintf(buf, len, "%d", y[2]);
7127     }
7128     buf[len-1] = '\0';
7129     return buf;
7130 }
7131
7132 struct VLRUExtStatsEntry {
7133     VolumeId volid;
7134 };
7135
7136 struct VLRUExtStats {
7137     afs_uint32 len;
7138     afs_uint32 used;
7139     struct {
7140         afs_uint32 start;
7141         afs_uint32 len;
7142     } queue_info[VLRU_QUEUE_INVALID];
7143     struct VLRUExtStatsEntry * vec;
7144 };
7145
7146 /** 
7147  * add a 256-entry fudge factor onto the vector in case state changes
7148  * out from under us.
7149  */
7150 #define VLRU_EXT_STATS_VEC_LEN_FUDGE   256
7151
7152 /**
7153  * collect extended statistics for the VLRU subsystem.
7154  *
7155  * @param[out] stats  pointer to stats structure to be populated
7156  * @param[in] nvols   number of volumes currently known to exist
7157  *
7158  * @pre VOL_LOCK held
7159  *
7160  * @post stats->vec allocated and populated
7161  *
7162  * @return operation status
7163  *    @retval 0 success
7164  *    @retval 1 failure
7165  */
7166 static int
7167 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7168 {
7169     afs_uint32 cur, idx, len;
7170     struct rx_queue * qp, * nqp;
7171     Volume * vp;
7172     struct VLRUExtStatsEntry * vec;
7173
7174     len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7175     vec = stats->vec = calloc(len,
7176                               sizeof(struct VLRUExtStatsEntry));
7177     if (vec == NULL) {
7178         return 1;
7179     }
7180
7181     cur = 0;
7182     for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7183         VLRU_Wait_r(&volume_LRU.q[idx]);
7184         VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7185         VOL_UNLOCK;
7186
7187         stats->queue_info[idx].start = cur;
7188
7189         for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7190             if (cur == len) {
7191                 /* out of space in vec */
7192                 break;
7193             }
7194             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7195             vec[cur].volid = vp->hashid;
7196             cur++;
7197         }
7198
7199         stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7200
7201         VOL_LOCK;
7202         VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7203     }
7204
7205     stats->len = len;
7206     stats->used = cur;
7207     return 0;
7208 }
7209
7210 #define ENUMTOSTRING(en)  #en
7211 #define ENUMCASE(en) \
7212     case en: \
7213         return ENUMTOSTRING(en); \
7214         break
7215
7216 static char *
7217 vlru_idx_to_string(int idx)
7218 {
7219     switch (idx) {
7220         ENUMCASE(VLRU_QUEUE_NEW);
7221         ENUMCASE(VLRU_QUEUE_MID);
7222         ENUMCASE(VLRU_QUEUE_OLD);
7223         ENUMCASE(VLRU_QUEUE_CANDIDATE);
7224         ENUMCASE(VLRU_QUEUE_HELD);
7225         ENUMCASE(VLRU_QUEUE_INVALID);
7226     default:
7227         return "**UNKNOWN**";
7228     }
7229 }
7230
7231 void
7232 VPrintExtendedCacheStats_r(int flags)
7233 {
7234     int i, j;
7235     afs_uint32 vol_sum = 0;
7236     struct stats {
7237         double min;
7238         double max;
7239         double sum;
7240         double avg;
7241     };
7242     struct stats looks, gets, reorders, len;
7243     struct stats ch_looks, ch_gets, ch_reorders;
7244     char pr_buf[4][32];
7245     VolumeHashChainHead *head;
7246     Volume *vp, *np;
7247     struct VLRUExtStats vlru_stats;
7248
7249     /* zero out stats */
7250     memset(&looks, 0, sizeof(struct stats));
7251     memset(&gets, 0, sizeof(struct stats));
7252     memset(&reorders, 0, sizeof(struct stats));
7253     memset(&len, 0, sizeof(struct stats));
7254     memset(&ch_looks, 0, sizeof(struct stats));
7255     memset(&ch_gets, 0, sizeof(struct stats));
7256     memset(&ch_reorders, 0, sizeof(struct stats));
7257
7258     for (i = 0; i < VolumeHashTable.Size; i++) {
7259         head = &VolumeHashTable.Table[i];
7260
7261         VHashWait_r(head);
7262         VHashBeginExclusive_r(head);
7263         VOL_UNLOCK;
7264
7265         ch_looks.sum    = UInt64ToDouble(&head->looks);
7266         ch_gets.sum     = UInt64ToDouble(&head->gets);
7267         ch_reorders.sum = UInt64ToDouble(&head->reorders);
7268
7269         /* update global statistics */
7270         {
7271             looks.sum    += ch_looks.sum;
7272             gets.sum     += ch_gets.sum;
7273             reorders.sum += ch_reorders.sum;
7274             len.sum      += (double)head->len;
7275             vol_sum      += head->len;
7276             
7277             if (i == 0) {
7278                 len.min      = (double) head->len;
7279                 len.max      = (double) head->len;
7280                 looks.min    = ch_looks.sum;
7281                 looks.max    = ch_looks.sum;
7282                 gets.min     = ch_gets.sum;
7283                 gets.max     = ch_gets.sum;
7284                 reorders.min = ch_reorders.sum;
7285                 reorders.max = ch_reorders.sum;
7286             } else {
7287                 if (((double)head->len) < len.min)
7288                     len.min = (double) head->len;
7289                 if (((double)head->len) > len.max)
7290                     len.max = (double) head->len;
7291                 if (ch_looks.sum < looks.min)
7292                     looks.min = ch_looks.sum;
7293                 else if (ch_looks.sum > looks.max)
7294                     looks.max = ch_looks.sum;
7295                 if (ch_gets.sum < gets.min)
7296                     gets.min = ch_gets.sum;
7297                 else if (ch_gets.sum > gets.max)
7298                     gets.max = ch_gets.sum;
7299                 if (ch_reorders.sum < reorders.min)
7300                     reorders.min = ch_reorders.sum;
7301                 else if (ch_reorders.sum > reorders.max)
7302                     reorders.max = ch_reorders.sum;
7303             }
7304         }
7305
7306         if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7307             /* compute detailed per-chain stats */
7308             struct stats hdr_loads, hdr_gets;
7309             double v_looks, v_loads, v_gets;
7310
7311             /* initialize stats with data from first element in chain */
7312             vp = queue_First(head, Volume);
7313             v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7314             v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7315             v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
7316             ch_gets.min = ch_gets.max = v_looks;
7317             hdr_loads.min = hdr_loads.max = v_loads;
7318             hdr_gets.min = hdr_gets.max = v_gets;
7319             hdr_loads.sum = hdr_gets.sum = 0;
7320
7321             vp = queue_Next(vp, Volume);
7322
7323             /* pull in stats from remaining elements in chain */
7324             for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7325                 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7326                 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7327                 v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
7328
7329                 hdr_loads.sum += v_loads;
7330                 hdr_gets.sum += v_gets;
7331
7332                 if (v_looks < ch_gets.min)
7333                     ch_gets.min = v_looks;
7334                 else if (v_looks > ch_gets.max)
7335                     ch_gets.max = v_looks;
7336
7337                 if (v_loads < hdr_loads.min)
7338                     hdr_loads.min = v_loads;
7339                 else if (v_loads > hdr_loads.max)
7340                     hdr_loads.max = v_loads;
7341
7342                 if (v_gets < hdr_gets.min)
7343                     hdr_gets.min = v_gets;
7344                 else if (v_gets > hdr_gets.max)
7345                     hdr_gets.max = v_gets;
7346             }
7347
7348             /* compute per-chain averages */
7349             ch_gets.avg = ch_gets.sum / ((double)head->len);
7350             hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7351             hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7352
7353             /* dump per-chain stats */
7354             Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7355                 i, head->len, 
7356                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7357                 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7358             Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7359                 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7360                 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7361                 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7362                 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7363             Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7364                 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7365                 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7366                 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7367                 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7368             Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7369                 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7370                 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7371                 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7372                 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7373         } else if (flags & VOL_STATS_PER_CHAIN) {
7374             /* dump simple per-chain stats */
7375             Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7376                 i, head->len, 
7377                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7378                 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7379                 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7380         }
7381
7382         VOL_LOCK;
7383         VHashEndExclusive_r(head);
7384     }
7385
7386     VOL_UNLOCK;
7387
7388     /* compute global averages */
7389     len.avg      = len.sum      / ((double)VolumeHashTable.Size);
7390     looks.avg    = looks.sum    / ((double)VolumeHashTable.Size);
7391     gets.avg     = gets.sum     / ((double)VolumeHashTable.Size);
7392     reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7393
7394     /* dump global stats */
7395     Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7396     Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7397         DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7398         DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7399         DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7400         DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7401     Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7402         DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7403         DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7404         DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7405         DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7406     Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7407         DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7408         DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7409         DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7410         DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7411     Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7412         DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7413         DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7414         DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7415         DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7416
7417     /* print extended disk related statistics */
7418     {
7419         struct DiskPartition64 * diskP;
7420         afs_uint32 vol_count[VOLMAXPARTS+1];
7421         byte part_exists[VOLMAXPARTS+1];
7422         Device id;
7423         int i;
7424
7425         memset(vol_count, 0, sizeof(vol_count));
7426         memset(part_exists, 0, sizeof(part_exists));
7427
7428         VOL_LOCK;
7429
7430         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7431             id = diskP->index;
7432             vol_count[id] = diskP->vol_list.len;
7433             part_exists[id] = 1;
7434         }
7435
7436         VOL_UNLOCK;
7437         for (i = 0; i <= VOLMAXPARTS; i++) {
7438             if (part_exists[i]) {
7439                 /* XXX while this is currently safe, it is a violation
7440                  *     of the VGetPartitionById_r interface contract. */
7441                 diskP = VGetPartitionById_r(i, 0);
7442                 if (diskP) {
7443                     Log("Partition %s has %d online volumes\n", 
7444                         VPartitionPath(diskP), diskP->vol_list.len);
7445                 }
7446             }
7447         }
7448         VOL_LOCK;
7449     }
7450
7451     /* print extended VLRU statistics */
7452     if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7453         afs_uint32 idx, cur, lpos;
7454         VOL_UNLOCK;
7455         VolumeId line[5];
7456
7457         Log("VLRU State Dump:\n\n");
7458
7459         for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7460             Log("\t%s:\n", vlru_idx_to_string(idx));
7461
7462             lpos = 0;
7463             for (cur = vlru_stats.queue_info[idx].start;
7464                  cur < vlru_stats.queue_info[idx].len;
7465                  cur++) {
7466                 line[lpos++] = vlru_stats.vec[cur].volid;
7467                 if (lpos==5) {
7468                     Log("\t\t%u, %u, %u, %u, %u,\n",
7469                         line[0], line[1], line[2], line[3], line[4]);
7470                     lpos = 0;
7471                 }
7472             }
7473
7474             if (lpos) {
7475                 while (lpos < 5) {
7476                     line[lpos++] = 0;
7477                 }
7478                 Log("\t\t%u, %u, %u, %u, %u\n",
7479                     line[0], line[1], line[2], line[3], line[4]);
7480             }
7481             Log("\n");
7482         }
7483
7484         free(vlru_stats.vec);
7485
7486         VOL_LOCK;
7487     }
7488 }
7489
7490 void
7491 VPrintExtendedCacheStats(int flags)
7492 {
7493     VOL_LOCK;
7494     VPrintExtendedCacheStats_r(flags);
7495     VOL_UNLOCK;
7496 }
7497 #endif /* AFS_DEMAND_ATTACH_FS */