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