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