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