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