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