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