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