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