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