2 * Copyright 2000, International Business Machines Corporation and others.
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
9 * Portions Copyright (c) 2005-2008 Sine Nomine Associates
12 /* 1/1/89: NB: this stuff is all going to be replaced. Don't take it too seriously */
17 Institution: The Information Technology Center, Carnegie-Mellon University
21 #include <afsconfig.h>
22 #include <afs/param.h>
30 #ifdef HAVE_SYS_FILE_H
35 #include <afs/afsint.h>
38 #if !defined(AFS_SGI_ENV)
41 #else /* AFS_OSF_ENV */
42 #ifdef AFS_VFSINCL_ENV
45 #include <sys/fs/ufs_fs.h>
47 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
48 #include <ufs/ufs/dinode.h>
49 #include <ufs/ffs/fs.h>
54 #else /* AFS_VFSINCL_ENV */
55 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
58 #endif /* AFS_VFSINCL_ENV */
59 #endif /* AFS_OSF_ENV */
60 #endif /* AFS_SGI_ENV */
61 #endif /* !AFS_NT40_ENV */
69 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
71 #include <sys/mnttab.h>
72 #include <sys/mntent.h>
78 #if defined(AFS_SGI_ENV)
81 #ifndef AFS_LINUX20_ENV
82 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
85 #endif /* AFS_SGI_ENV */
87 #endif /* AFS_HPUX_ENV */
91 #include <afs/errors.h>
94 #include <afs/afssyscalls.h>
96 #include <afs/afsutil.h>
97 #include "daemon_com.h"
102 #include "partition.h"
103 #include "volume_inline.h"
108 #ifdef AFS_PTHREAD_ENV
109 pthread_mutex_t vol_glock_mutex;
110 pthread_mutex_t vol_trans_mutex;
111 pthread_cond_t vol_put_volume_cond;
112 pthread_cond_t vol_sleep_cond;
113 pthread_cond_t vol_init_attach_cond;
114 pthread_cond_t vol_vinit_cond;
115 int vol_attach_threads = 1;
116 #endif /* AFS_PTHREAD_ENV */
118 /* start-time configurable I/O parameters */
119 ih_init_params vol_io_params;
121 #ifdef AFS_DEMAND_ATTACH_FS
122 pthread_mutex_t vol_salvsync_mutex;
125 * Set this to 1 to disallow SALVSYNC communication in all threads; used
126 * during shutdown, since the salvageserver may have gone away.
128 static volatile sig_atomic_t vol_disallow_salvsync = 0;
129 #endif /* AFS_DEMAND_ATTACH_FS */
132 * has VShutdown_r been called / is VShutdown_r running?
134 static int vol_shutting_down = 0;
137 extern void *calloc(), *realloc();
140 /* Forward declarations */
141 static Volume *attach2(Error * ec, VolId volumeId, char *path,
142 struct DiskPartition64 *partp, Volume * vp,
143 int isbusy, int mode, int *acheckedOut);
144 static void ReallyFreeVolume(Volume * vp);
145 #ifdef AFS_DEMAND_ATTACH_FS
146 static void FreeVolume(Volume * vp);
147 #else /* !AFS_DEMAND_ATTACH_FS */
148 #define FreeVolume(vp) ReallyFreeVolume(vp)
149 static void VScanUpdateList(void);
150 #endif /* !AFS_DEMAND_ATTACH_FS */
151 static void VInitVolumeHeaderCache(afs_uint32 howMany);
152 static int GetVolumeHeader(Volume * vp);
153 static void ReleaseVolumeHeader(struct volHeader *hd);
154 static void FreeVolumeHeader(Volume * vp);
155 static void AddVolumeToHashTable(Volume * vp, int hashid);
156 static void DeleteVolumeFromHashTable(Volume * vp);
158 static int VHold(Volume * vp);
160 static int VHold_r(Volume * vp);
161 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
162 static void VReleaseVolumeHandles_r(Volume * vp);
163 static void VCloseVolumeHandles_r(Volume * vp);
164 static void LoadVolumeHeader(Error * ec, Volume * vp);
165 static int VCheckOffline(Volume * vp);
166 static int VCheckDetach(Volume * vp);
167 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
168 Volume * hint, const struct timespec *ts);
170 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
171 * defined when not linked with vice, XXXX */
172 ProgramType programType; /* The type of program using the package */
173 static VolumePackageOptions vol_opts;
175 /* extended volume package statistics */
178 #ifdef VOL_LOCK_DEBUG
179 pthread_t vol_glock_holder = 0;
183 /* this parameter needs to be tunable at runtime.
184 * 128 was really inadequate for largish servers -- at 16384 volumes this
185 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
186 * talk about bad spatial locality...
188 * an AVL or splay tree might work a lot better, but we'll just increase
189 * the default hash table size for now
191 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
192 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
193 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
196 * turn volume hash chains into partially ordered lists.
197 * when the threshold is exceeded between two adjacent elements,
198 * perform a chain rebalancing operation.
200 * keep the threshold high in order to keep cache line invalidates
201 * low "enough" on SMPs
203 #define VOLUME_HASH_REORDER_THRESHOLD 200
206 * when possible, don't just reorder single elements, but reorder
207 * entire chains of elements at once. a chain of elements that
208 * exceed the element previous to the pivot by at least CHAIN_THRESH
209 * accesses are moved in front of the chain whose elements have at
210 * least CHAIN_THRESH less accesses than the pivot element
212 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
214 #include "rx/rx_queue.h"
217 VolumeHashTable_t VolumeHashTable = {
218 DEFAULT_VOLUME_HASH_SIZE,
219 DEFAULT_VOLUME_HASH_MASK,
224 static void VInitVolumeHash(void);
228 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
232 afs_int32 ffs_tmp = x;
236 for (ffs_i = 1;; ffs_i++) {
243 #endif /* !AFS_HAVE_FFS */
245 #ifdef AFS_PTHREAD_ENV
247 * disk partition queue element
249 typedef struct diskpartition_queue_t {
250 struct rx_queue queue; /**< queue header */
251 struct DiskPartition64 *diskP; /**< disk partition table entry */
252 } diskpartition_queue_t;
254 #ifndef AFS_DEMAND_ATTACH_FS
256 typedef struct vinitvolumepackage_thread_t {
257 struct rx_queue queue;
258 pthread_cond_t thread_done_cv;
259 int n_threads_complete;
260 } vinitvolumepackage_thread_t;
261 static void * VInitVolumePackageThread(void * args);
263 #else /* !AFS_DEMAND_ATTTACH_FS */
264 #define VINIT_BATCH_MAX_SIZE 512
267 * disk partition work queue
269 struct partition_queue {
270 struct rx_queue head; /**< diskpartition_queue_t queue */
271 pthread_mutex_t mutex;
276 * volumes parameters for preattach
278 struct volume_init_batch {
279 struct rx_queue queue; /**< queue header */
280 int thread; /**< posting worker thread */
281 int last; /**< indicates thread is done */
282 int size; /**< number of volume ids in batch */
283 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
287 * volume parameters work queue
289 struct volume_init_queue {
290 struct rx_queue head; /**< volume_init_batch queue */
291 pthread_mutex_t mutex;
296 * volume init worker thread parameters
298 struct vinitvolumepackage_thread_param {
299 int nthreads; /**< total number of worker threads */
300 int thread; /**< thread number for this worker thread */
301 struct partition_queue *pq; /**< queue partitions to scan */
302 struct volume_init_queue *vq; /**< queue of volume to preattach */
305 static void *VInitVolumePackageThread(void *args);
306 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
307 static VolId VInitNextVolumeId(DIR *dirp);
308 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
310 #endif /* !AFS_DEMAND_ATTACH_FS */
311 #endif /* AFS_PTHREAD_ENV */
313 #ifndef AFS_DEMAND_ATTACH_FS
314 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
315 int * nAttached, int * nUnattached);
316 #endif /* AFS_DEMAND_ATTACH_FS */
319 #ifdef AFS_DEMAND_ATTACH_FS
320 /* demand attach fileserver extensions */
323 * in the future we will support serialization of VLRU state into the fs_state
326 * these structures are the beginning of that effort
328 struct VLRU_DiskHeader {
329 struct versionStamp stamp; /* magic and structure version number */
330 afs_uint32 mtime; /* time of dump to disk */
331 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
334 struct VLRU_DiskEntry {
335 afs_uint32 vid; /* volume ID */
336 afs_uint32 idx; /* generation */
337 afs_uint32 last_get; /* timestamp of last get */
340 struct VLRU_StartupQueue {
341 struct VLRU_DiskEntry * entry;
346 typedef struct vshutdown_thread_t {
348 pthread_mutex_t lock;
350 pthread_cond_t master_cv;
352 int n_threads_complete;
354 int schedule_version;
357 byte n_parts_done_pass;
358 byte part_thread_target[VOLMAXPARTS+1];
359 byte part_done_pass[VOLMAXPARTS+1];
360 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
361 int stats[4][VOLMAXPARTS+1];
362 } vshutdown_thread_t;
363 static void * VShutdownThread(void * args);
366 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
367 static int VCheckFree(Volume * vp);
370 static void AddVolumeToVByPList_r(Volume * vp);
371 static void DeleteVolumeFromVByPList_r(Volume * vp);
372 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
373 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
374 static void VVByPListWait_r(struct DiskPartition64 * dp);
376 /* online salvager */
378 VCHECK_SALVAGE_OK = 0, /**< no pending salvage */
379 VCHECK_SALVAGE_SCHEDULED = 1, /**< salvage has been scheduled */
380 VCHECK_SALVAGE_ASYNC = 2, /**< salvage being scheduled */
381 VCHECK_SALVAGE_DENIED = 3, /**< salvage not scheduled; denied */
382 VCHECK_SALVAGE_FAIL = 4 /**< salvage not scheduled; failed */
384 static int VCheckSalvage(Volume * vp);
385 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
386 static int VScheduleSalvage_r(Volume * vp);
389 /* Volume hash table */
390 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
391 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
392 static void VHashEndExclusive_r(VolumeHashChainHead * head);
393 static void VHashWait_r(VolumeHashChainHead * head);
396 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
397 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
398 struct rx_queue ** idx);
399 static void ShutdownController(vshutdown_thread_t * params);
400 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
403 static void VLRU_ComputeConstants(void);
404 static void VInitVLRU(void);
405 static void VLRU_Init_Node_r(Volume * vp);
406 static void VLRU_Add_r(Volume * vp);
407 static void VLRU_Delete_r(Volume * vp);
408 static void VLRU_UpdateAccess_r(Volume * vp);
409 static void * VLRU_ScannerThread(void * args);
410 static void VLRU_Scan_r(int idx);
411 static void VLRU_Promote_r(int idx);
412 static void VLRU_Demote_r(int idx);
413 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
416 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
417 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
418 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
421 pthread_key_t VThread_key;
422 VThreadOptions_t VThread_defaults = {
423 0 /**< allow salvsync */
425 #endif /* AFS_DEMAND_ATTACH_FS */
428 struct Lock vol_listLock; /* Lock obtained when listing volumes:
429 * prevents a volume from being missed
430 * if the volume is attached during a
434 /* Common message used when the volume goes off line */
435 char *VSalvageMessage =
436 "Files in this volume are currently unavailable; call operations";
438 int VInit; /* 0 - uninitialized,
439 * 1 - initialized but not all volumes have been attached,
440 * 2 - initialized and all volumes have been attached,
441 * 3 - initialized, all volumes have been attached, and
442 * VConnectFS() has completed. */
444 static int vinit_attach_abort = 0;
446 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
447 * used to stamp volume headers and in-core
448 * vnodes. When the volume goes on-line the
449 * vnode will be invalidated
450 * access only with VOL_LOCK held */
455 /***************************************************/
456 /* Startup routines */
457 /***************************************************/
459 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
460 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
461 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
465 * assign default values to a VolumePackageOptions struct.
467 * Always call this on a VolumePackageOptions struct first, then set any
468 * specific options you want, then call VInitVolumePackage2.
470 * @param[in] pt caller's program type
471 * @param[out] opts volume package options
474 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
476 opts->nLargeVnodes = opts->nSmallVnodes = 5;
479 opts->canScheduleSalvage = 0;
480 opts->canUseFSSYNC = 0;
481 opts->canUseSALVSYNC = 0;
483 opts->interrupt_rxcall = NULL;
484 opts->offline_timeout = -1;
485 opts->offline_shutdown_timeout = -1;
486 opts->usage_threshold = 128;
487 opts->usage_rate_limit = 5;
490 opts->unsafe_attach = 1;
491 #else /* !FAST_RESTART */
492 opts->unsafe_attach = 0;
493 #endif /* !FAST_RESTART */
497 opts->canScheduleSalvage = 1;
498 opts->canUseSALVSYNC = 1;
502 opts->canUseFSSYNC = 1;
506 opts->nLargeVnodes = 0;
507 opts->nSmallVnodes = 0;
509 opts->canScheduleSalvage = 1;
510 opts->canUseFSSYNC = 1;
520 * Set VInit to a certain value, and signal waiters.
522 * @param[in] value the value to set VInit to
527 VSetVInit_r(int value)
530 CV_BROADCAST(&vol_vinit_cond);
534 VLogOfflineTimeout(const char *type, afs_int32 timeout)
540 Log("VInitVolumePackage: Interrupting clients accessing %s "
541 "immediately\n", type);
543 Log("VInitVolumePackage: Interrupting clients accessing %s "
544 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
549 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
551 int errors = 0; /* Number of errors while finding vice partitions. */
556 #ifndef AFS_PTHREAD_ENV
557 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
558 Log("VInitVolumePackage: offline_timeout and/or "
559 "offline_shutdown_timeout was specified, but the volume package "
560 "does not support these for LWP builds\n");
564 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
565 VLogOfflineTimeout("volumes going offline during shutdown",
566 opts->offline_shutdown_timeout);
568 memset(&VStats, 0, sizeof(VStats));
569 VStats.hdr_cache_size = 200;
571 VInitPartitionPackage();
573 #ifdef AFS_DEMAND_ATTACH_FS
574 if (programType == fileServer) {
577 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
579 opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
582 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
583 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
584 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
585 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
586 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
587 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
588 #ifndef AFS_PTHREAD_ENV
590 #endif /* AFS_PTHREAD_ENV */
591 Lock_Init(&vol_listLock);
593 srandom(time(0)); /* For VGetVolumeInfo */
595 #ifdef AFS_DEMAND_ATTACH_FS
596 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
597 #endif /* AFS_DEMAND_ATTACH_FS */
599 /* Ok, we have done enough initialization that fileserver can
600 * start accepting calls, even though the volumes may not be
601 * available just yet.
605 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
606 if (programType == salvageServer) {
609 #endif /* AFS_DEMAND_ATTACH_FS */
610 #ifdef FSSYNC_BUILD_SERVER
611 if (programType == fileServer) {
615 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
616 if (VCanUseSALVSYNC()) {
617 /* establish a connection to the salvager at this point */
618 opr_Verify(VConnectSALV() != 0);
620 #endif /* AFS_DEMAND_ATTACH_FS */
622 if (opts->volcache > VStats.hdr_cache_size)
623 VStats.hdr_cache_size = opts->volcache;
624 VInitVolumeHeaderCache(VStats.hdr_cache_size);
626 VInitVnodes(vLarge, opts->nLargeVnodes);
627 VInitVnodes(vSmall, opts->nSmallVnodes);
630 errors = VAttachPartitions();
634 if (programType != fileServer) {
635 errors = VInitAttachVolumes(programType);
641 #ifdef FSSYNC_BUILD_CLIENT
642 if (VCanUseFSSYNC()) {
644 #ifdef AFS_DEMAND_ATTACH_FS
645 if (programType == salvageServer) {
646 Log("Unable to connect to file server; aborted\n");
649 #endif /* AFS_DEMAND_ATTACH_FS */
650 Log("Unable to connect to file server; will retry at need\n");
653 #endif /* FSSYNC_BUILD_CLIENT */
658 #if !defined(AFS_PTHREAD_ENV)
660 * Attach volumes in vice partitions
662 * @param[in] pt calling program type
665 * @note This is the original, non-threaded version of attach parititions.
667 * @post VInit state is 2
670 VInitAttachVolumes(ProgramType pt)
672 opr_Assert(VInit==1);
673 if (pt == fileServer) {
674 struct DiskPartition64 *diskP;
675 /* Attach all the volumes in this partition */
676 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
677 int nAttached = 0, nUnattached = 0;
678 opr_Verify(VAttachVolumesByPartition(diskP,
679 &nAttached, &nUnattached)
684 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
685 LWP_NoYieldSignal(VInitAttachVolumes);
689 #endif /* !AFS_PTHREAD_ENV */
691 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
693 * Attach volumes in vice partitions
695 * @param[in] pt calling program type
698 * @note Threaded version of attach parititions.
700 * @post VInit state is 2
703 VInitAttachVolumes(ProgramType pt)
705 opr_Assert(VInit==1);
706 if (pt == fileServer) {
707 struct DiskPartition64 *diskP;
708 struct vinitvolumepackage_thread_t params;
709 struct diskpartition_queue_t * dpq;
710 int i, threads, parts;
712 pthread_attr_t attrs;
714 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
716 params.n_threads_complete = 0;
718 /* create partition work queue */
719 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
720 dpq = malloc(sizeof(struct diskpartition_queue_t));
721 opr_Assert(dpq != NULL);
723 queue_Append(¶ms,dpq);
726 threads = min(parts, vol_attach_threads);
729 /* spawn off a bunch of initialization threads */
730 opr_Verify(pthread_attr_init(&attrs) == 0);
731 opr_Verify(pthread_attr_setdetachstate(&attrs,
732 PTHREAD_CREATE_DETACHED)
735 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
736 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
740 for (i=0; i < threads; i++) {
743 opr_Verify(pthread_create(&tid, &attrs,
744 &VInitVolumePackageThread,
746 AFS_SIGSET_RESTORE();
749 while(params.n_threads_complete < threads) {
750 VOL_CV_WAIT(¶ms.thread_done_cv);
754 opr_Verify(pthread_attr_destroy(&attrs) == 0);
756 /* if we're only going to run one init thread, don't bother creating
758 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
759 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
762 VInitVolumePackageThread(¶ms);
765 CV_DESTROY(¶ms.thread_done_cv);
768 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
769 CV_BROADCAST(&vol_init_attach_cond);
775 VInitVolumePackageThread(void * args) {
777 struct DiskPartition64 *diskP;
778 struct vinitvolumepackage_thread_t * params;
779 struct diskpartition_queue_t * dpq;
781 params = (vinitvolumepackage_thread_t *) args;
785 /* Attach all the volumes in this partition */
786 while (queue_IsNotEmpty(params)) {
787 int nAttached = 0, nUnattached = 0;
789 if (vinit_attach_abort) {
790 Log("Aborting initialization\n");
794 dpq = queue_First(params,diskpartition_queue_t);
800 opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
807 params->n_threads_complete++;
808 CV_SIGNAL(¶ms->thread_done_cv);
812 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
814 #if defined(AFS_DEMAND_ATTACH_FS)
816 * Attach volumes in vice partitions
818 * @param[in] pt calling program type
821 * @note Threaded version of attach partitions.
823 * @post VInit state is 2
826 VInitAttachVolumes(ProgramType pt)
828 opr_Assert(VInit==1);
829 if (pt == fileServer) {
831 struct DiskPartition64 *diskP;
832 struct partition_queue pq;
833 struct volume_init_queue vq;
835 int i, threads, parts;
837 pthread_attr_t attrs;
839 /* create partition work queue */
841 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
842 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
843 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
844 struct diskpartition_queue_t *dp;
845 dp = malloc(sizeof(struct diskpartition_queue_t));
846 opr_Assert(dp != NULL);
848 queue_Append(&pq, dp);
851 /* number of worker threads; at least one, not to exceed the number of partitions */
852 threads = min(parts, vol_attach_threads);
854 /* create volume work queue */
856 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
857 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
859 opr_Verify(pthread_attr_init(&attrs) == 0);
860 opr_Verify(pthread_attr_setdetachstate(&attrs,
861 PTHREAD_CREATE_DETACHED) == 0);
863 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
864 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
867 /* create threads to scan disk partitions. */
868 for (i=0; i < threads; i++) {
869 struct vinitvolumepackage_thread_param *params;
872 params = malloc(sizeof(struct vinitvolumepackage_thread_param));
876 params->nthreads = threads;
877 params->thread = i+1;
880 opr_Verify(pthread_create(&tid, &attrs,
881 &VInitVolumePackageThread,
882 (void*)params) == 0);
883 AFS_SIGSET_RESTORE();
886 VInitPreAttachVolumes(threads, &vq);
888 opr_Verify(pthread_attr_destroy(&attrs) == 0);
890 MUTEX_DESTROY(&pq.mutex);
892 MUTEX_DESTROY(&vq.mutex);
896 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
897 CV_BROADCAST(&vol_init_attach_cond);
904 * Volume package initialization worker thread. Scan partitions for volume
905 * header files. Gather batches of volume ids and dispatch them to
906 * the main thread to be preattached. The volume preattachement is done
907 * in the main thread to avoid global volume lock contention.
910 VInitVolumePackageThread(void *args)
912 struct vinitvolumepackage_thread_param *params;
913 struct DiskPartition64 *partition;
914 struct partition_queue *pq;
915 struct volume_init_queue *vq;
916 struct volume_init_batch *vb;
919 params = (struct vinitvolumepackage_thread_param *)args;
925 vb = malloc(sizeof(struct volume_init_batch));
927 vb->thread = params->thread;
931 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
932 while((partition = VInitNextPartition(pq))) {
936 Log("Partition %s: pre-attaching volumes\n", partition->name);
937 dirp = opendir(VPartitionPath(partition));
939 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
942 while ((vid = VInitNextVolumeId(dirp))) {
943 Volume *vp = calloc(1, sizeof(Volume));
945 vp->device = partition->device;
946 vp->partition = partition;
948 queue_Init(&vp->vnode_list);
949 queue_Init(&vp->rx_call_list);
950 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
952 vb->batch[vb->size++] = vp;
953 if (vb->size == VINIT_BATCH_MAX_SIZE) {
954 MUTEX_ENTER(&vq->mutex);
955 queue_Append(vq, vb);
956 CV_BROADCAST(&vq->cv);
957 MUTEX_EXIT(&vq->mutex);
959 vb = malloc(sizeof(struct volume_init_batch));
961 vb->thread = params->thread;
970 MUTEX_ENTER(&vq->mutex);
971 queue_Append(vq, vb);
972 CV_BROADCAST(&vq->cv);
973 MUTEX_EXIT(&vq->mutex);
975 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
981 * Read next element from the pre-populated partition list.
983 static struct DiskPartition64*
984 VInitNextPartition(struct partition_queue *pq)
986 struct DiskPartition64 *partition;
987 struct diskpartition_queue_t *dp; /* queue element */
989 if (vinit_attach_abort) {
990 Log("Aborting volume preattach thread.\n");
994 /* get next partition to scan */
995 MUTEX_ENTER(&pq->mutex);
996 if (queue_IsEmpty(pq)) {
997 MUTEX_EXIT(&pq->mutex);
1000 dp = queue_First(pq, diskpartition_queue_t);
1002 MUTEX_EXIT(&pq->mutex);
1005 opr_Assert(dp->diskP);
1007 partition = dp->diskP;
1013 * Find next volume id on the partition.
1016 VInitNextVolumeId(DIR *dirp)
1022 while((d = readdir(dirp))) {
1023 if (vinit_attach_abort) {
1024 Log("Aborting volume preattach thread.\n");
1027 ext = strrchr(d->d_name, '.');
1028 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1029 vid = VolumeNumber(d->d_name);
1033 Log("Warning: bogus volume header file: %s\n", d->d_name);
1040 * Preattach volumes in batches to avoid lock contention.
1043 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1045 struct volume_init_batch *vb;
1049 /* dequeue next volume */
1050 MUTEX_ENTER(&vq->mutex);
1051 if (queue_IsEmpty(vq)) {
1052 CV_WAIT(&vq->cv, &vq->mutex);
1054 vb = queue_First(vq, volume_init_batch);
1056 MUTEX_EXIT(&vq->mutex);
1060 for (i = 0; i<vb->size; i++) {
1066 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1068 Log("Error looking up volume, code=%d\n", ec);
1071 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1074 /* put pre-attached volume onto the hash table
1075 * and bring it up to the pre-attached state */
1076 AddVolumeToHashTable(vp, vp->hashid);
1077 AddVolumeToVByPList_r(vp);
1078 VLRU_Init_Node_r(vp);
1079 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1092 #endif /* AFS_DEMAND_ATTACH_FS */
1094 #if !defined(AFS_DEMAND_ATTACH_FS)
1096 * attach all volumes on a given disk partition
1099 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1105 Log("Partition %s: attaching volumes\n", diskP->name);
1106 dirp = opendir(VPartitionPath(diskP));
1108 Log("opendir on Partition %s failed!\n", diskP->name);
1112 while ((dp = readdir(dirp))) {
1114 p = strrchr(dp->d_name, '.');
1116 if (vinit_attach_abort) {
1117 Log("Partition %s: abort attach volumes\n", diskP->name);
1121 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1124 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1126 (*(vp ? nAttached : nUnattached))++;
1127 if (error == VOFFLINE)
1128 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1129 else if (LogLevel >= 5) {
1130 Log("Partition %s: attached volume %d (%s)\n",
1131 diskP->name, VolumeNumber(dp->d_name),
1140 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1145 #endif /* !AFS_DEMAND_ATTACH_FS */
1147 /***************************************************/
1148 /* Shutdown routines */
1149 /***************************************************/
1153 * highly multithreaded volume package shutdown
1155 * with the demand attach fileserver extensions,
1156 * VShutdown has been modified to be multithreaded.
1157 * In order to achieve optimal use of many threads,
1158 * the shutdown code involves one control thread and
1159 * n shutdown worker threads. The control thread
1160 * periodically examines the number of volumes available
1161 * for shutdown on each partition, and produces a worker
1162 * thread allocation schedule. The idea is to eliminate
1163 * redundant scheduling computation on the workers by
1164 * having a single master scheduler.
1166 * The scheduler's objectives are:
1168 * each partition with volumes remaining gets allocated
1169 * at least 1 thread (assuming sufficient threads)
1171 * threads are allocated proportional to the number of
1172 * volumes remaining to be offlined. This ensures that
1173 * the OS I/O scheduler has many requests to elevator
1174 * seek on partitions that will (presumably) take the
1175 * longest amount of time (from now) to finish shutdown
1176 * (3) keep threads busy
1177 * when there are extra threads, they are assigned to
1178 * partitions using a simple round-robin algorithm
1180 * In the future, we may wish to add the ability to adapt
1181 * to the relative performance patterns of each disk
1186 * multi-step shutdown process
1188 * demand attach shutdown is a four-step process. Each
1189 * shutdown "pass" shuts down increasingly more difficult
1190 * volumes. The main purpose is to achieve better cache
1191 * utilization during shutdown.
1194 * shutdown volumes in the unattached, pre-attached
1197 * shutdown attached volumes with cached volume headers
1199 * shutdown all volumes in non-exclusive states
1201 * shutdown all remaining volumes
1204 #ifdef AFS_DEMAND_ATTACH_FS
1210 struct DiskPartition64 * diskP;
1211 struct diskpartition_queue_t * dpq;
1212 vshutdown_thread_t params;
1214 pthread_attr_t attrs;
1216 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1219 Log("VShutdown: aborting attach volumes\n");
1220 vinit_attach_abort = 1;
1221 VOL_CV_WAIT(&vol_init_attach_cond);
1224 for (params.n_parts=0, diskP = DiskPartitionList;
1225 diskP; diskP = diskP->next, params.n_parts++);
1227 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1228 params.n_parts, params.n_parts > 1 ? "s" : "");
1230 vol_shutting_down = 1;
1232 if (vol_attach_threads > 1) {
1233 /* prepare for parallel shutdown */
1234 params.n_threads = vol_attach_threads;
1235 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1236 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1237 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1238 opr_Verify(pthread_attr_init(&attrs) == 0);
1239 opr_Verify(pthread_attr_setdetachstate(&attrs,
1240 PTHREAD_CREATE_DETACHED) == 0);
1241 queue_Init(¶ms);
1243 /* setup the basic partition information structures for
1244 * parallel shutdown */
1245 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1247 struct rx_queue * qp, * nqp;
1251 VVByPListWait_r(diskP);
1252 VVByPListBeginExclusive_r(diskP);
1255 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1256 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1260 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1261 VPartitionPath(diskP), count);
1264 /* build up the pass 0 shutdown work queue */
1265 dpq = malloc(sizeof(struct diskpartition_queue_t));
1266 opr_Assert(dpq != NULL);
1268 queue_Prepend(¶ms, dpq);
1270 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1273 Log("VShutdown: beginning parallel fileserver shutdown\n");
1274 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1275 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1277 /* do pass 0 shutdown */
1278 MUTEX_ENTER(¶ms.lock);
1279 for (i=0; i < params.n_threads; i++) {
1280 opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1284 /* wait for all the pass 0 shutdowns to complete */
1285 while (params.n_threads_complete < params.n_threads) {
1286 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1288 params.n_threads_complete = 0;
1290 CV_BROADCAST(¶ms.cv);
1291 MUTEX_EXIT(¶ms.lock);
1293 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1294 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1296 /* run the parallel shutdown scheduler. it will drop the glock internally */
1297 ShutdownController(¶ms);
1299 /* wait for all the workers to finish pass 3 and terminate */
1300 while (params.pass < 4) {
1301 VOL_CV_WAIT(¶ms.cv);
1304 opr_Verify(pthread_attr_destroy(&attrs) == 0);
1305 CV_DESTROY(¶ms.cv);
1306 CV_DESTROY(¶ms.master_cv);
1307 MUTEX_DESTROY(¶ms.lock);
1309 /* drop the VByPList exclusive reservations */
1310 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1311 VVByPListEndExclusive_r(diskP);
1312 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1313 VPartitionPath(diskP),
1314 params.stats[0][diskP->index],
1315 params.stats[1][diskP->index],
1316 params.stats[2][diskP->index],
1317 params.stats[3][diskP->index]);
1320 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1322 /* if we're only going to run one shutdown thread, don't bother creating
1324 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1326 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1327 VShutdownByPartition_r(diskP);
1331 Log("VShutdown: complete.\n");
1334 #else /* AFS_DEMAND_ATTACH_FS */
1344 Log("VShutdown: aborting attach volumes\n");
1345 vinit_attach_abort = 1;
1346 #ifdef AFS_PTHREAD_ENV
1347 VOL_CV_WAIT(&vol_init_attach_cond);
1349 LWP_WaitProcess(VInitAttachVolumes);
1350 #endif /* AFS_PTHREAD_ENV */
1353 Log("VShutdown: shutting down on-line volumes...\n");
1354 vol_shutting_down = 1;
1355 for (i = 0; i < VolumeHashTable.Size; i++) {
1356 /* try to hold first volume in the hash table */
1357 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1361 Log("VShutdown: Attempting to take volume %u offline.\n",
1364 /* next, take the volume offline (drops reference count) */
1365 VOffline_r(vp, "File server was shut down");
1369 Log("VShutdown: complete.\n");
1371 #endif /* AFS_DEMAND_ATTACH_FS */
1377 opr_Assert(VInit>0);
1384 * stop new activity (e.g. SALVSYNC) from occurring
1386 * Use this to make the volume package less busy; for example, during
1387 * shutdown. This doesn't actually shutdown/detach anything in the
1388 * volume package, but prevents certain processes from ocurring. For
1389 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1390 * could also use this to prevent new volume attachment, or prevent
1391 * other programs from checking out volumes, etc.
1396 #ifdef AFS_DEMAND_ATTACH_FS
1397 /* make sure we don't try to contact the salvageserver, since it may
1398 * not be around anymore */
1399 vol_disallow_salvsync = 1;
1403 #ifdef AFS_DEMAND_ATTACH_FS
1406 * shutdown control thread
1409 ShutdownController(vshutdown_thread_t * params)
1412 struct DiskPartition64 * diskP;
1414 vshutdown_thread_t shadow;
1416 ShutdownCreateSchedule(params);
1418 while ((params->pass < 4) &&
1419 (params->n_threads_complete < params->n_threads)) {
1420 /* recompute schedule once per second */
1422 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1426 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1427 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1428 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1429 shadow.n_threads_complete, shadow.n_parts_done_pass);
1430 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1432 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1434 diskP->vol_list.len,
1435 shadow.part_thread_target[id],
1436 shadow.part_done_pass[id],
1437 shadow.part_pass_head[id]);
1443 ShutdownCreateSchedule(params);
1447 /* create the shutdown thread work schedule.
1448 * this scheduler tries to implement fairness
1449 * by allocating at least 1 thread to each
1450 * partition with volumes to be shutdown,
1451 * and then it attempts to allocate remaining
1452 * threads based upon the amount of work left
1455 ShutdownCreateSchedule(vshutdown_thread_t * params)
1457 struct DiskPartition64 * diskP;
1458 int sum, thr_workload, thr_left;
1459 int part_residue[VOLMAXPARTS+1];
1462 /* compute the total number of outstanding volumes */
1464 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1465 sum += diskP->vol_list.len;
1468 params->schedule_version++;
1469 params->vol_remaining = sum;
1474 /* compute average per-thread workload */
1475 thr_workload = sum / params->n_threads;
1476 if (sum % params->n_threads)
1479 thr_left = params->n_threads;
1480 memset(&part_residue, 0, sizeof(part_residue));
1482 /* for fairness, give every partition with volumes remaining
1483 * at least one thread */
1484 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1486 if (diskP->vol_list.len) {
1487 params->part_thread_target[id] = 1;
1490 params->part_thread_target[id] = 0;
1494 if (thr_left && thr_workload) {
1495 /* compute length-weighted workloads */
1498 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1500 delta = (diskP->vol_list.len / thr_workload) -
1501 params->part_thread_target[id];
1505 if (delta < thr_left) {
1506 params->part_thread_target[id] += delta;
1509 params->part_thread_target[id] += thr_left;
1517 /* try to assign any leftover threads to partitions that
1518 * had volume lengths closer to needing thread_target+1 */
1519 int max_residue, max_id = 0;
1521 /* compute the residues */
1522 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1524 part_residue[id] = diskP->vol_list.len -
1525 (params->part_thread_target[id] * thr_workload);
1528 /* now try to allocate remaining threads to partitions with the
1529 * highest residues */
1532 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1534 if (part_residue[id] > max_residue) {
1535 max_residue = part_residue[id];
1544 params->part_thread_target[max_id]++;
1546 part_residue[max_id] = 0;
1551 /* punt and give any remaining threads equally to each partition */
1553 if (thr_left >= params->n_parts) {
1554 alloc = thr_left / params->n_parts;
1555 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1557 params->part_thread_target[id] += alloc;
1562 /* finish off the last of the threads */
1563 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1565 params->part_thread_target[id]++;
1571 /* worker thread for parallel shutdown */
1573 VShutdownThread(void * args)
1575 vshutdown_thread_t * params;
1576 int found, pass, schedule_version_save, count;
1577 struct DiskPartition64 *diskP;
1578 struct diskpartition_queue_t * dpq;
1581 params = (vshutdown_thread_t *) args;
1583 /* acquire the shutdown pass 0 lock */
1584 MUTEX_ENTER(¶ms->lock);
1586 /* if there's still pass 0 work to be done,
1587 * get a work entry, and do a pass 0 shutdown */
1588 if (queue_IsNotEmpty(params)) {
1589 dpq = queue_First(params, diskpartition_queue_t);
1591 MUTEX_EXIT(¶ms->lock);
1597 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1599 params->stats[0][diskP->index] = count;
1600 MUTEX_ENTER(¶ms->lock);
1603 params->n_threads_complete++;
1604 if (params->n_threads_complete == params->n_threads) {
1605 /* notify control thread that all workers have completed pass 0 */
1606 CV_SIGNAL(¶ms->master_cv);
1608 while (params->pass == 0) {
1609 CV_WAIT(¶ms->cv, ¶ms->lock);
1613 MUTEX_EXIT(¶ms->lock);
1616 pass = params->pass;
1617 opr_Assert(pass > 0);
1619 /* now escalate through the more complicated shutdowns */
1621 schedule_version_save = params->schedule_version;
1623 /* find a disk partition to work on */
1624 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1626 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1627 params->part_thread_target[id]--;
1634 /* hmm. for some reason the controller thread couldn't find anything for
1635 * us to do. let's see if there's anything we can do */
1636 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1638 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1641 } else if (!params->part_done_pass[id]) {
1642 params->part_done_pass[id] = 1;
1643 params->n_parts_done_pass++;
1645 Log("VShutdown: done shutting down volumes on partition %s.\n",
1646 VPartitionPath(diskP));
1652 /* do work on this partition until either the controller
1653 * creates a new schedule, or we run out of things to do
1654 * on this partition */
1657 while (!params->part_done_pass[id] &&
1658 (schedule_version_save == params->schedule_version)) {
1659 /* ShutdownVolumeWalk_r will drop the glock internally */
1660 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1661 if (!params->part_done_pass[id]) {
1662 params->part_done_pass[id] = 1;
1663 params->n_parts_done_pass++;
1665 Log("VShutdown: done shutting down volumes on partition %s.\n",
1666 VPartitionPath(diskP));
1674 params->stats[pass][id] += count;
1676 /* ok, everyone is done this pass, proceed */
1679 params->n_threads_complete++;
1680 while (params->pass == pass) {
1681 if (params->n_threads_complete == params->n_threads) {
1682 /* we are the last thread to complete, so we will
1683 * reinitialize worker pool state for the next pass */
1684 params->n_threads_complete = 0;
1685 params->n_parts_done_pass = 0;
1687 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1689 params->part_done_pass[id] = 0;
1690 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1693 /* compute a new thread schedule before releasing all the workers */
1694 ShutdownCreateSchedule(params);
1696 /* wake up all the workers */
1697 CV_BROADCAST(¶ms->cv);
1700 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1701 pass, params->n_threads, params->n_parts);
1704 VOL_CV_WAIT(¶ms->cv);
1707 pass = params->pass;
1721 /* shut down all volumes on a given disk partition
1723 * note that this function will not allow mp-fast
1724 * shutdown of a partition */
1726 VShutdownByPartition_r(struct DiskPartition64 * dp)
1732 /* wait for other exclusive ops to finish */
1733 VVByPListWait_r(dp);
1735 /* begin exclusive access */
1736 VVByPListBeginExclusive_r(dp);
1738 /* pick the low-hanging fruit first,
1739 * then do the complicated ones last
1740 * (has the advantage of keeping
1741 * in-use volumes up until the bitter end) */
1742 for (pass = 0, total=0; pass < 4; pass++) {
1743 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1744 total += pass_stats[pass];
1747 /* end exclusive access */
1748 VVByPListEndExclusive_r(dp);
1750 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1751 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1756 /* internal shutdown functionality
1758 * for multi-pass shutdown:
1759 * 0 to only "shutdown" {pre,un}attached and error state volumes
1760 * 1 to also shutdown attached volumes w/ volume header loaded
1761 * 2 to also shutdown attached volumes w/o volume header loaded
1762 * 3 to also shutdown exclusive state volumes
1764 * caller MUST hold exclusive access on the hash chain
1765 * because we drop vol_glock_mutex internally
1767 * this function is reentrant for passes 1--3
1768 * (e.g. multiple threads can cooperate to
1769 * shutdown a partition mp-fast)
1771 * pass 0 is not scaleable because the volume state data is
1772 * synchronized by vol_glock mutex, and the locking overhead
1773 * is too high to drop the lock long enough to do linked list
1777 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1779 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1782 while (ShutdownVolumeWalk_r(dp, pass, &q))
1788 /* conditionally shutdown one volume on partition dp
1789 * returns 1 if a volume was shutdown in this pass,
1792 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1793 struct rx_queue ** idx)
1795 struct rx_queue *qp, *nqp;
1800 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1801 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1805 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1806 (V_attachState(vp) != VOL_STATE_ERROR) &&
1807 (V_attachState(vp) != VOL_STATE_DELETED) &&
1808 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1812 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1813 (vp->header == NULL)) {
1817 if (VIsExclusiveState(V_attachState(vp))) {
1822 DeleteVolumeFromVByPList_r(vp);
1823 VShutdownVolume_r(vp);
1833 * shutdown a specific volume
1835 /* caller MUST NOT hold a heavyweight ref on vp */
1837 VShutdownVolume_r(Volume * vp)
1841 VCreateReservation_r(vp);
1843 if (LogLevel >= 5) {
1844 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1845 vp->hashid, vp->partition->device, V_attachState(vp));
1848 /* wait for other blocking ops to finish */
1849 VWaitExclusiveState_r(vp);
1851 opr_Assert(VIsValidState(V_attachState(vp)));
1853 switch(V_attachState(vp)) {
1854 case VOL_STATE_SALVAGING:
1855 /* Leave salvaging volumes alone. Any in-progress salvages will
1856 * continue working after viced shuts down. This is intentional.
1859 case VOL_STATE_PREATTACHED:
1860 case VOL_STATE_ERROR:
1861 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1862 case VOL_STATE_UNATTACHED:
1863 case VOL_STATE_DELETED:
1865 case VOL_STATE_GOING_OFFLINE:
1866 case VOL_STATE_SHUTTING_DOWN:
1867 case VOL_STATE_ATTACHED:
1871 Log("VShutdown: Attempting to take volume %u offline.\n",
1874 /* take the volume offline (drops reference count) */
1875 VOffline_r(vp, "File server was shut down");
1882 VCancelReservation_r(vp);
1886 #endif /* AFS_DEMAND_ATTACH_FS */
1889 /***************************************************/
1890 /* Header I/O routines */
1891 /***************************************************/
1894 HeaderName(bit32 magic)
1897 case VOLUMEINFOMAGIC:
1898 return "volume info";
1899 case SMALLINDEXMAGIC:
1900 return "small index";
1901 case LARGEINDEXMAGIC:
1902 return "large index";
1903 case LINKTABLEMAGIC:
1904 return "link table";
1909 /* open a descriptor for the inode (h),
1910 * read in an on-disk structure into buffer (to) of size (size),
1911 * verify versionstamp in structure has magic (magic) and
1912 * optionally verify version (version) if (version) is nonzero
1915 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1918 struct versionStamp *vsn;
1920 afs_sfsize_t nbytes;
1925 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1933 Log("ReadHeader: Failed to open %s header file "
1934 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1935 PrintInode(stmp, h->ih_ino), errno);
1940 vsn = (struct versionStamp *)to;
1941 nbytes = FDH_PREAD(fdP, to, size, 0);
1943 Log("ReadHeader: Failed to read %s header file "
1944 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1945 PrintInode(stmp, h->ih_ino), errno);
1947 FDH_REALLYCLOSE(fdP);
1950 if (nbytes != size) {
1951 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1952 "(volume=%u, inode=%s); expected=%d, read=%d\n",
1953 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), size,
1956 FDH_REALLYCLOSE(fdP);
1959 if (vsn->magic != magic) {
1960 Log("ReadHeader: Incorrect magic for %s header file "
1961 "(volume=%u, inode=%s); expected=0x%x, read=0x%x\n",
1962 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), magic,
1965 FDH_REALLYCLOSE(fdP);
1971 /* Check is conditional, in case caller wants to inspect version himself */
1972 if (version && vsn->version != version) {
1973 Log("ReadHeader: Incorrect version for %s header file "
1974 "(volume=%u, inode=%s); expected=%x, read=%x\n",
1975 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino),
1976 version, vsn->version);
1982 WriteVolumeHeader_r(Error * ec, Volume * vp)
1984 IHandle_t *h = V_diskDataHandle(vp);
1994 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1995 != sizeof(V_disk(vp))) {
1997 FDH_REALLYCLOSE(fdP);
2003 /* VolumeHeaderToDisk
2004 * Allows for storing 64 bit inode numbers in on-disk volume header
2007 /* convert in-memory representation of a volume header to the
2008 * on-disk representation of a volume header */
2010 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2013 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2014 dh->stamp = h->stamp;
2016 dh->parent = h->parent;
2018 #ifdef AFS_64BIT_IOPS_ENV
2019 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2020 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2021 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2022 dh->smallVnodeIndex_hi =
2023 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2024 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2025 dh->largeVnodeIndex_hi =
2026 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2027 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2028 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2030 dh->volumeInfo_lo = h->volumeInfo;
2031 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2032 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2033 dh->linkTable_lo = h->linkTable;
2037 /* DiskToVolumeHeader
2038 * Converts an on-disk representation of a volume header to
2039 * the in-memory representation of a volume header.
2041 * Makes the assumption that AFS has *always*
2042 * zero'd the volume header file so that high parts of inode
2043 * numbers are 0 in older (SGI EFS) volume header files.
2046 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2048 memset(h, 0, sizeof(VolumeHeader_t));
2049 h->stamp = dh->stamp;
2051 h->parent = dh->parent;
2053 #ifdef AFS_64BIT_IOPS_ENV
2055 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2057 h->smallVnodeIndex =
2058 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2059 smallVnodeIndex_hi << 32);
2061 h->largeVnodeIndex =
2062 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2063 largeVnodeIndex_hi << 32);
2065 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2067 h->volumeInfo = dh->volumeInfo_lo;
2068 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2069 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2070 h->linkTable = dh->linkTable_lo;
2075 /***************************************************/
2076 /* Volume Attachment routines */
2077 /***************************************************/
2079 #ifdef AFS_DEMAND_ATTACH_FS
2081 * pre-attach a volume given its path.
2083 * @param[out] ec outbound error code
2084 * @param[in] partition partition path string
2085 * @param[in] name volume id string
2087 * @return volume object pointer
2089 * @note A pre-attached volume will only have its partition
2090 * and hashid fields initialized. At first call to
2091 * VGetVolume, the volume will be fully attached.
2095 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2099 vp = VPreAttachVolumeByName_r(ec, partition, name);
2105 * pre-attach a volume given its path.
2107 * @param[out] ec outbound error code
2108 * @param[in] partition path to vice partition
2109 * @param[in] name volume id string
2111 * @return volume object pointer
2113 * @pre VOL_LOCK held
2115 * @internal volume package internal use only.
2118 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2120 return VPreAttachVolumeById_r(ec,
2122 VolumeNumber(name));
2126 * pre-attach a volume given its path and numeric volume id.
2128 * @param[out] ec error code return
2129 * @param[in] partition path to vice partition
2130 * @param[in] volumeId numeric volume id
2132 * @return volume object pointer
2134 * @pre VOL_LOCK held
2136 * @internal volume package internal use only.
2139 VPreAttachVolumeById_r(Error * ec,
2144 struct DiskPartition64 *partp;
2148 opr_Assert(programType == fileServer);
2150 if (!(partp = VGetPartition_r(partition, 0))) {
2152 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2156 vp = VLookupVolume_r(ec, volumeId, NULL);
2161 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2165 * preattach a volume.
2167 * @param[out] ec outbound error code
2168 * @param[in] partp pointer to partition object
2169 * @param[in] vp pointer to volume object
2170 * @param[in] vid volume id
2172 * @return volume object pointer
2174 * @pre VOL_LOCK is held.
2176 * @warning Returned volume object pointer does not have to
2177 * equal the pointer passed in as argument vp. There
2178 * are potential race conditions which can result in
2179 * the pointers having different values. It is up to
2180 * the caller to make sure that references are handled
2181 * properly in this case.
2183 * @note If there is already a volume object registered with
2184 * the same volume id, its pointer MUST be passed as
2185 * argument vp. Failure to do so will result in a silent
2186 * failure to preattach.
2188 * @internal volume package internal use only.
2191 VPreAttachVolumeByVp_r(Error * ec,
2192 struct DiskPartition64 * partp,
2200 /* check to see if pre-attach already happened */
2202 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2203 (V_attachState(vp) != VOL_STATE_DELETED) &&
2204 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2205 !VIsErrorState(V_attachState(vp))) {
2207 * pre-attach is a no-op in all but the following cases:
2209 * - volume is unattached
2210 * - volume is in an error state
2211 * - volume is pre-attached
2213 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state (state %u flags 0x%x)\n",
2214 vid, V_attachState(vp), V_attachFlags(vp));
2217 /* we're re-attaching a volume; clear out some old state */
2218 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2220 if (V_partition(vp) != partp) {
2221 /* XXX potential race */
2222 DeleteVolumeFromVByPList_r(vp);
2225 /* if we need to allocate a new Volume struct,
2226 * go ahead and drop the vol glock, otherwise
2227 * do the basic setup synchronised, as it's
2228 * probably not worth dropping the lock */
2231 /* allocate the volume structure */
2232 vp = nvp = calloc(1, sizeof(Volume));
2233 opr_Assert(vp != NULL);
2234 queue_Init(&vp->vnode_list);
2235 queue_Init(&vp->rx_call_list);
2236 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2239 /* link the volume with its associated vice partition */
2240 vp->device = partp->device;
2241 vp->partition = partp;
2244 vp->specialStatus = 0;
2246 /* if we dropped the lock, reacquire the lock,
2247 * check for pre-attach races, and then add
2248 * the volume to the hash table */
2251 nvp = VLookupVolume_r(ec, vid, NULL);
2256 } else if (nvp) { /* race detected */
2261 /* hack to make up for VChangeState_r() decrementing
2262 * the old state counter */
2263 VStats.state_levels[0]++;
2267 /* put pre-attached volume onto the hash table
2268 * and bring it up to the pre-attached state */
2269 AddVolumeToHashTable(vp, vp->hashid);
2270 AddVolumeToVByPList_r(vp);
2271 VLRU_Init_Node_r(vp);
2272 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2275 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2283 #endif /* AFS_DEMAND_ATTACH_FS */
2285 /* Attach an existing volume, given its pathname, and return a
2286 pointer to the volume header information. The volume also
2287 normally goes online at this time. An offline volume
2288 must be reattached to make it go online */
2290 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2294 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2300 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2303 struct DiskPartition64 *partp;
2308 #ifdef AFS_DEMAND_ATTACH_FS
2309 VolumeStats stats_save;
2311 #endif /* AFS_DEMAND_ATTACH_FS */
2315 volumeId = VolumeNumber(name);
2317 if (!(partp = VGetPartition_r(partition, 0))) {
2319 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2323 if (VRequiresPartLock()) {
2324 opr_Assert(VInit == 3);
2325 VLockPartition_r(partition);
2326 } else if (programType == fileServer) {
2327 #ifdef AFS_DEMAND_ATTACH_FS
2328 /* lookup the volume in the hash table */
2329 vp = VLookupVolume_r(ec, volumeId, NULL);
2335 /* save any counters that are supposed to
2336 * be monotonically increasing over the
2337 * lifetime of the fileserver */
2338 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2340 memset(&stats_save, 0, sizeof(VolumeStats));
2343 /* if there's something in the hash table, and it's not
2344 * in the pre-attach state, then we may need to detach
2345 * it before proceeding */
2346 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2347 VCreateReservation_r(vp);
2348 VWaitExclusiveState_r(vp);
2350 /* at this point state must be one of:
2360 if (vp->specialStatus == VBUSY)
2363 /* if it's already attached, see if we can return it */
2364 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2365 VGetVolumeByVp_r(ec, vp);
2366 if (V_inUse(vp) == fileServer) {
2367 VCancelReservation_r(vp);
2371 /* otherwise, we need to detach, and attempt to re-attach */
2372 VDetachVolume_r(ec, vp);
2374 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2377 /* if it isn't fully attached, delete from the hash tables,
2378 and let the refcounter handle the rest */
2379 DeleteVolumeFromHashTable(vp);
2380 DeleteVolumeFromVByPList_r(vp);
2383 VCancelReservation_r(vp);
2387 /* pre-attach volume if it hasn't been done yet */
2389 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2390 (V_attachState(vp) == VOL_STATE_DELETED) ||
2391 (V_attachState(vp) == VOL_STATE_ERROR)) {
2393 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2399 opr_Assert(vp != NULL);
2401 /* handle pre-attach races
2403 * multiple threads can race to pre-attach a volume,
2404 * but we can't let them race beyond that
2406 * our solution is to let the first thread to bring
2407 * the volume into an exclusive state win; the other
2408 * threads just wait until it finishes bringing the
2409 * volume online, and then they do a vgetvolumebyvp
2411 if (svp && (svp != vp)) {
2412 /* wait for other exclusive ops to finish */
2413 VCreateReservation_r(vp);
2414 VWaitExclusiveState_r(vp);
2416 /* get a heavyweight ref, kill the lightweight ref, and return */
2417 VGetVolumeByVp_r(ec, vp);
2418 VCancelReservation_r(vp);
2422 /* at this point, we are chosen as the thread to do
2423 * demand attachment for this volume. all other threads
2424 * doing a getvolume on vp->hashid will block until we finish */
2426 /* make sure any old header cache entries are invalidated
2427 * before proceeding */
2428 FreeVolumeHeader(vp);
2430 VChangeState_r(vp, VOL_STATE_ATTACHING);
2432 /* restore any saved counters */
2433 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2434 #else /* AFS_DEMAND_ATTACH_FS */
2435 vp = VGetVolume_r(ec, volumeId);
2437 if (V_inUse(vp) == fileServer)
2439 if (vp->specialStatus == VBUSY)
2441 VDetachVolume_r(ec, vp);
2443 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2447 #endif /* AFS_DEMAND_ATTACH_FS */
2451 strcpy(path, VPartitionPath(partp));
2455 strcat(path, OS_DIRSEP);
2459 vp = (Volume *) calloc(1, sizeof(Volume));
2460 opr_Assert(vp != NULL);
2461 vp->hashid = volumeId;
2462 vp->device = partp->device;
2463 vp->partition = partp;
2464 queue_Init(&vp->vnode_list);
2465 queue_Init(&vp->rx_call_list);
2466 #ifdef AFS_DEMAND_ATTACH_FS
2467 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2468 #endif /* AFS_DEMAND_ATTACH_FS */
2471 /* attach2 is entered without any locks, and returns
2472 * with vol_glock_mutex held */
2473 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2475 if (VCanUseFSSYNC() && vp) {
2476 #ifdef AFS_DEMAND_ATTACH_FS
2477 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2478 /* mark volume header as in use so that volser crashes lead to a
2479 * salvage attempt */
2480 VUpdateVolume_r(ec, vp, 0);
2482 /* for dafs, we should tell the fileserver, except for V_PEEK
2483 * where we know it is not necessary */
2484 if (mode == V_PEEK) {
2485 vp->needsPutBack = 0;
2487 vp->needsPutBack = VOL_PUTBACK;
2489 #else /* !AFS_DEMAND_ATTACH_FS */
2490 /* duplicate computation in fssync.c about whether the server
2491 * takes the volume offline or not. If the volume isn't
2492 * offline, we must not return it when we detach the volume,
2493 * or the server will abort */
2494 if (mode == V_READONLY || mode == V_PEEK
2495 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2496 vp->needsPutBack = 0;
2498 vp->needsPutBack = VOL_PUTBACK;
2499 #endif /* !AFS_DEMAND_ATTACH_FS */
2501 #ifdef FSSYNC_BUILD_CLIENT
2502 /* Only give back the vol to the fileserver if we checked it out; attach2
2503 * will set checkedOut only if we successfully checked it out from the
2505 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2507 #ifdef AFS_DEMAND_ATTACH_FS
2508 /* If we couldn't attach but we scheduled a salvage, we already
2509 * notified the fileserver; don't online it now */
2510 if (*ec != VSALVAGING)
2511 #endif /* AFS_DEMAND_ATTACH_FS */
2512 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2515 if (programType == fileServer && vp) {
2516 #ifdef AFS_DEMAND_ATTACH_FS
2518 * we can get here in cases where we don't "own"
2519 * the volume (e.g. volume owned by a utility).
2520 * short circuit around potential disk header races.
2522 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2526 VUpdateVolume_r(ec, vp, 0);
2528 Log("VAttachVolume: Error updating volume\n");
2533 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2534 #ifndef AFS_DEMAND_ATTACH_FS
2535 /* This is a hack: by temporarily setting the incore
2536 * dontSalvage flag ON, the volume will be put back on the
2537 * Update list (with dontSalvage OFF again). It will then
2538 * come back in N minutes with DONT_SALVAGE eventually
2539 * set. This is the way that volumes that have never had
2540 * it set get it set; or that volumes that have been
2541 * offline without DONT SALVAGE having been set also
2542 * eventually get it set */
2543 V_dontSalvage(vp) = DONT_SALVAGE;
2544 #endif /* !AFS_DEMAND_ATTACH_FS */
2545 VAddToVolumeUpdateList_r(ec, vp);
2547 Log("VAttachVolume: Error adding volume to update list\n");
2554 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2559 if (VRequiresPartLock()) {
2560 VUnlockPartition_r(partition);
2563 #ifdef AFS_DEMAND_ATTACH_FS
2564 /* attach failed; make sure we're in error state */
2565 if (vp && !VIsErrorState(V_attachState(vp))) {
2566 VChangeState_r(vp, VOL_STATE_ERROR);
2568 #endif /* AFS_DEMAND_ATTACH_FS */
2575 #ifdef AFS_DEMAND_ATTACH_FS
2576 /* VAttachVolumeByVp_r
2578 * finish attaching a volume that is
2579 * in a less than fully attached state
2581 /* caller MUST hold a ref count on vp */
2583 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2585 char name[VMAXPATHLEN];
2587 struct DiskPartition64 *partp;
2591 Volume * nvp = NULL;
2592 VolumeStats stats_save;
2596 /* volume utility should never call AttachByVp */
2597 opr_Assert(programType == fileServer);
2599 volumeId = vp->hashid;
2600 partp = vp->partition;
2601 VolumeExternalName_r(volumeId, name, sizeof(name));
2604 /* if another thread is performing a blocking op, wait */
2605 VWaitExclusiveState_r(vp);
2607 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2609 /* if it's already attached, see if we can return it */
2610 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2611 VGetVolumeByVp_r(ec, vp);
2612 if (V_inUse(vp) == fileServer) {
2615 if (vp->specialStatus == VBUSY)
2617 VDetachVolume_r(ec, vp);
2619 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2625 /* pre-attach volume if it hasn't been done yet */
2627 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2628 (V_attachState(vp) == VOL_STATE_DELETED) ||
2629 (V_attachState(vp) == VOL_STATE_ERROR)) {
2630 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2636 VCreateReservation_r(nvp);
2641 opr_Assert(vp != NULL);
2642 VChangeState_r(vp, VOL_STATE_ATTACHING);
2644 /* restore monotonically increasing stats */
2645 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2649 /* compute path to disk header */
2650 strcpy(path, VPartitionPath(partp));
2654 strcat(path, OS_DIRSEP);
2659 * NOTE: attach2 is entered without any locks, and returns
2660 * with vol_glock_mutex held */
2661 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2664 * the event that an error was encountered, or
2665 * the volume was not brought to an attached state
2666 * for any reason, skip to the end. We cannot
2667 * safely call VUpdateVolume unless we "own" it.
2671 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2675 VUpdateVolume_r(ec, vp, 0);
2677 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2681 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2682 #ifndef AFS_DEMAND_ATTACH_FS
2683 /* This is a hack: by temporarily setting the incore
2684 * dontSalvage flag ON, the volume will be put back on the
2685 * Update list (with dontSalvage OFF again). It will then
2686 * come back in N minutes with DONT_SALVAGE eventually
2687 * set. This is the way that volumes that have never had
2688 * it set get it set; or that volumes that have been
2689 * offline without DONT SALVAGE having been set also
2690 * eventually get it set */
2691 V_dontSalvage(vp) = DONT_SALVAGE;
2692 #endif /* !AFS_DEMAND_ATTACH_FS */
2693 VAddToVolumeUpdateList_r(ec, vp);
2695 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2702 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2706 VCancelReservation_r(nvp);
2709 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2710 if (vp && !VIsErrorState(V_attachState(vp))) {
2711 VChangeState_r(vp, VOL_STATE_ERROR);
2720 * lock a volume on disk (non-blocking).
2722 * @param[in] vp The volume to lock
2723 * @param[in] locktype READ_LOCK or WRITE_LOCK
2725 * @return operation status
2726 * @retval 0 success, lock was obtained
2727 * @retval EBUSY a conflicting lock was held by another process
2728 * @retval EIO error acquiring lock
2730 * @pre If we're in the fileserver, vp is in an exclusive state
2732 * @pre vp is not already locked
2735 VLockVolumeNB(Volume *vp, int locktype)
2739 opr_Assert(programType != fileServer
2740 || VIsExclusiveState(V_attachState(vp)));
2741 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2743 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2745 V_attachFlags(vp) |= VOL_LOCKED;
2752 * unlock a volume on disk that was locked with VLockVolumeNB.
2754 * @param[in] vp volume to unlock
2756 * @pre If we're in the fileserver, vp is in an exclusive state
2758 * @pre vp has already been locked
2761 VUnlockVolume(Volume *vp)
2763 opr_Assert(programType != fileServer
2764 || VIsExclusiveState(V_attachState(vp)));
2765 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2767 VUnlockVolumeById(vp->hashid, vp->partition);
2769 V_attachFlags(vp) &= ~VOL_LOCKED;
2771 #endif /* AFS_DEMAND_ATTACH_FS */
2774 * read in a vol header, possibly lock the vol header, and possibly check out
2775 * the vol header from the fileserver, as part of volume attachment.
2777 * @param[out] ec error code
2778 * @param[in] vp volume pointer object
2779 * @param[in] partp disk partition object of the attaching partition
2780 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2782 * @param[in] peek 1 to just try to read in the volume header and make sure
2783 * we don't try to lock the vol, or check it out from
2784 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2786 * @param[out] acheckedOut If we successfully checked-out the volume from
2787 * the fileserver (if we needed to), this is set
2788 * to 1, otherwise it is untouched.
2790 * @note As part of DAFS volume attachment, the volume header may be either
2791 * read- or write-locked to ensure mutual exclusion of certain volume
2792 * operations. In some cases in order to determine whether we need to
2793 * read- or write-lock the header, we need to read in the header to see
2794 * if the volume is RW or not. So, if we read in the header under a
2795 * read-lock and determine that we actually need a write-lock on the
2796 * volume header, this function will drop the read lock, acquire a write
2797 * lock, and read the header in again.
2800 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2801 int mode, int peek, int *acheckedOut)
2803 struct VolumeDiskHeader diskHeader;
2804 struct VolumeHeader header;
2807 int lock_tries = 0, checkout_tries = 0;
2809 VolumeId volid = vp->hashid;
2810 #ifdef FSSYNC_BUILD_CLIENT
2811 int checkout, done_checkout = 0;
2812 #endif /* FSSYNC_BUILD_CLIENT */
2813 #ifdef AFS_DEMAND_ATTACH_FS
2814 int locktype = 0, use_locktype = -1;
2815 #endif /* AFS_DEMAND_ATTACH_FS */
2821 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2822 Log("VAttachVolume: retried too many times trying to lock header for "
2823 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2824 VPartitionPath(partp));
2828 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2829 Log("VAttachVolume: retried too many times trying to checkout "
2830 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2831 VPartitionPath(partp));
2836 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2837 /* short-circuit the 'volume does not exist' case */
2842 #ifdef FSSYNC_BUILD_CLIENT
2843 checkout = !done_checkout;
2845 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2847 memset(&res, 0, sizeof(res));
2849 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2852 if (res.hdr.reason == FSYNC_SALVAGE) {
2853 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2854 afs_printable_uint32_lu(volid));
2857 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2858 afs_printable_uint32_lu(volid));
2859 *ec = VNOVOL; /* XXXX */
2867 #ifdef AFS_DEMAND_ATTACH_FS
2868 if (use_locktype < 0) {
2869 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2870 * if it turns out to be RW */
2871 locktype = VVolLockType(mode, 0);
2874 /* a previous try says we should use use_locktype to lock the volume,
2876 locktype = use_locktype;
2879 if (!peek && locktype) {
2880 code = VLockVolumeNB(vp, locktype);
2882 if (code == EBUSY) {
2883 Log("VAttachVolume: another program has vol %lu locked\n",
2884 afs_printable_uint32_lu(volid));
2886 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2887 code, afs_printable_uint32_lu(volid));
2894 #endif /* AFS_DEMAND_ATTACH_FS */
2896 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2906 DiskToVolumeHeader(&header, &diskHeader);
2908 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2909 header.largeVnodeIndex);
2910 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2911 header.smallVnodeIndex);
2912 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2914 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2917 /* only need to do this once */
2919 GetVolumeHeader(vp);
2923 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2924 /* demand attach changes the V_PEEK mechanism
2926 * we can now suck the current disk data structure over
2927 * the fssync interface without going to disk
2929 * (technically, we don't need to restrict this feature
2930 * to demand attach fileservers. However, I'm trying
2931 * to limit the number of common code changes)
2933 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2935 res.payload.len = sizeof(VolumeDiskData);
2936 res.payload.buf = &vp->header->diskstuff;
2938 if (FSYNC_VolOp(vp->hashid,
2940 FSYNC_VOL_QUERY_HDR,
2943 goto disk_header_loaded;
2946 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2947 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2948 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2950 #ifdef AFS_DEMAND_ATTACH_FS
2953 IncUInt64(&VStats.hdr_loads);
2954 IncUInt64(&vp->stats.hdr_loads);
2956 #endif /* AFS_DEMAND_ATTACH_FS */
2959 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2960 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2964 #ifdef AFS_DEMAND_ATTACH_FS
2965 # ifdef FSSYNC_BUILD_CLIENT
2967 # endif /* FSSYNC_BUILD_CLIENT */
2969 /* if the lock type we actually used to lock the volume is different than
2970 * the lock type we should have used, retry with the lock type we should
2972 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2973 if (locktype != use_locktype) {
2977 #endif /* AFS_DEMAND_ATTACH_FS */
2982 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2983 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2985 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2987 if (code == SYNC_DENIED) {
2988 /* must retry checkout; fileserver no longer thinks we have
2994 } else if (code != SYNC_OK) {
2998 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3001 /* either we are going to be called again for a second pass, or we
3002 * encountered an error; clean up in either case */
3004 #ifdef AFS_DEMAND_ATTACH_FS
3005 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3008 #endif /* AFS_DEMAND_ATTACH_FS */
3009 if (vp->linkHandle) {
3010 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3011 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3012 IH_RELEASE(vp->diskDataHandle);
3013 IH_RELEASE(vp->linkHandle);
3019 FreeVolumeHeader(vp);
3029 #ifdef AFS_DEMAND_ATTACH_FS
3031 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3032 Volume *vp, int *acheckedOut)
3036 if (vp->pending_vol_op) {
3040 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3042 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3044 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3045 } else if (code == 0) {
3046 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3049 /* we need the vol header to determine if the volume can be
3050 * left online for the vop, so... get the header */
3054 /* attach header with peek=1 to avoid checking out the volume
3055 * or locking it; we just want the header info, we're not
3056 * messing with the volume itself at all */
3057 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3064 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3065 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3067 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3070 /* make sure we grab a new vol header and re-open stuff on
3071 * actual attachment; we can't keep the data we grabbed, since
3072 * it was not done under a lock and thus not safe */
3073 FreeVolumeHeader(vp);
3074 VReleaseVolumeHandles_r(vp);
3077 /* see if the pending volume op requires exclusive access */
3078 switch (vp->pending_vol_op->vol_op_state) {
3079 case FSSYNC_VolOpPending:
3080 /* this should never happen */
3081 opr_Assert(vp->pending_vol_op->vol_op_state
3082 != FSSYNC_VolOpPending);
3085 case FSSYNC_VolOpRunningUnknown:
3086 /* this should never happen; we resolved 'unknown' above */
3087 opr_Assert(vp->pending_vol_op->vol_op_state
3088 != FSSYNC_VolOpRunningUnknown);
3091 case FSSYNC_VolOpRunningOffline:
3092 /* mark the volume down */
3094 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3096 /* do not set V_offlineMessage here; we don't have ownership of
3097 * the volume (and probably do not have the header loaded), so we
3098 * can't alter the disk header */
3100 /* check to see if we should set the specialStatus flag */
3101 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3102 /* don't overwrite specialStatus if it was already set to
3103 * something else (e.g. VMOVED) */
3104 if (!vp->specialStatus) {
3105 vp->specialStatus = VBUSY;
3117 #endif /* AFS_DEMAND_ATTACH_FS */
3120 * volume attachment helper function.
3122 * @param[out] ec error code
3123 * @param[in] volumeId volume ID of the attaching volume
3124 * @param[in] path full path to the volume header .vol file
3125 * @param[in] partp disk partition object for the attaching partition
3126 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3127 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3128 * DAFS) should already be initialized
3129 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3130 * if there is a volume operation running for this volume
3131 * that should set the volume to VBUSY during its run. 0
3132 * otherwise. (see VVolOpSetVBusy_r)
3133 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3135 * @param[out] acheckedOut If we successfully checked-out the volume from
3136 * the fileserver (if we needed to), this is set
3137 * to 1, otherwise it is 0.
3139 * @return pointer to the semi-attached volume pointer
3140 * @retval NULL an error occurred (check value of *ec)
3141 * @retval vp volume successfully attaching
3143 * @pre no locks held
3145 * @post VOL_LOCK held
3148 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3149 Volume * vp, int isbusy, int mode, int *acheckedOut)
3151 /* have we read in the header successfully? */
3152 int read_header = 0;
3154 #ifdef AFS_DEMAND_ATTACH_FS
3155 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3159 /* in the case of an error, to what state should the volume be
3161 VolState error_state = VOL_STATE_ERROR;
3162 #endif /* AFS_DEMAND_ATTACH_FS */
3166 vp->vnodeIndex[vLarge].handle = NULL;
3167 vp->vnodeIndex[vSmall].handle = NULL;
3168 vp->diskDataHandle = NULL;
3169 vp->linkHandle = NULL;
3173 #ifdef AFS_DEMAND_ATTACH_FS
3174 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3176 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3179 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3180 #endif /* !AFS_DEMAND_ATTACH_FS */
3182 if (*ec == VNOVOL) {
3183 /* if the volume doesn't exist, skip straight to 'error' so we don't
3184 * request a salvage */
3185 goto unlocked_error;
3191 /* ensure that we don't override specialStatus if it was set to
3192 * something else (e.g. VMOVED) */
3193 if (isbusy && !vp->specialStatus) {
3194 vp->specialStatus = VBUSY;
3196 vp->shuttingDown = 0;
3197 vp->goingOffline = 0;
3199 #ifdef AFS_DEMAND_ATTACH_FS
3200 vp->stats.last_attach = FT_ApproxTime();
3201 vp->stats.attaches++;
3205 IncUInt64(&VStats.attaches);
3206 vp->cacheCheck = ++VolumeCacheCheck;
3207 /* just in case this ever rolls over */
3208 if (!vp->cacheCheck)
3209 vp->cacheCheck = ++VolumeCacheCheck;
3212 #ifdef AFS_DEMAND_ATTACH_FS
3213 V_attachFlags(vp) |= VOL_HDR_LOADED;
3214 vp->stats.last_hdr_load = vp->stats.last_attach;
3215 #endif /* AFS_DEMAND_ATTACH_FS */
3219 struct IndexFileHeader iHead;
3222 * We just read in the diskstuff part of the header. If the detailed
3223 * volume stats area has not yet been initialized, we should bzero the
3224 * area and mark it as initialized.
3226 if (!(V_stat_initialized(vp))) {
3227 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3228 V_stat_initialized(vp) = 1;
3231 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3232 (char *)&iHead, sizeof(iHead),
3233 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3236 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3241 struct IndexFileHeader iHead;
3243 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3244 (char *)&iHead, sizeof(iHead),
3245 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3248 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3252 #ifdef AFS_NAMEI_ENV
3254 struct versionStamp stamp;
3256 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3257 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3260 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3263 #endif /* AFS_NAMEI_ENV */
3265 #if defined(AFS_DEMAND_ATTACH_FS)
3266 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3268 if (!VCanScheduleSalvage()) {
3269 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3271 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3276 /* volume operation in progress */
3278 /* we have already transitioned the vp away from ATTACHING state, so we
3279 * can go right to the end of attach2, and we do not need to transition
3281 goto error_notbroken;
3283 #else /* AFS_DEMAND_ATTACH_FS */
3285 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3286 goto unlocked_error;
3288 #endif /* AFS_DEMAND_ATTACH_FS */
3290 if (V_needsSalvaged(vp)) {
3291 if (vp->specialStatus)
3292 vp->specialStatus = 0;
3294 #if defined(AFS_DEMAND_ATTACH_FS)
3295 if (!VCanScheduleSalvage()) {
3296 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3298 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3301 #else /* AFS_DEMAND_ATTACH_FS */
3303 #endif /* AFS_DEMAND_ATTACH_FS */
3309 vp->nextVnodeUnique = V_uniquifier(vp);
3311 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3312 if (!V_needsSalvaged(vp)) {
3313 V_needsSalvaged(vp) = 1;
3314 VUpdateVolume_r(ec, vp, 0);
3316 #if defined(AFS_DEMAND_ATTACH_FS)
3317 if (!VCanScheduleSalvage()) {
3318 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3320 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3323 #else /* AFS_DEMAND_ATTACH_FS */
3324 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3326 #endif /* AFS_DEMAND_ATTACH_FS */
3331 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3332 /* Only check destroyMe if we are the fileserver, since the
3333 * volserver et al sometimes need to work with volumes with
3334 * destroyMe set. Examples are 'temporary' volumes the
3335 * volserver creates, and when we create a volume (destroyMe
3336 * is set on creation; sometimes a separate volserver
3337 * transaction is created to clear destroyMe).
3340 #if defined(AFS_DEMAND_ATTACH_FS)
3341 /* schedule a salvage so the volume goes away on disk */
3342 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3343 VChangeState_r(vp, VOL_STATE_ERROR);
3346 #endif /* AFS_DEMAND_ATTACH_FS */
3347 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3352 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3353 #ifndef BITMAP_LATER
3354 if (programType == fileServer && VolumeWriteable(vp)) {
3356 for (i = 0; i < nVNODECLASSES; i++) {
3357 VGetBitmap_r(ec, vp, i);
3359 #ifdef AFS_DEMAND_ATTACH_FS
3360 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3362 #endif /* AFS_DEMAND_ATTACH_FS */
3363 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3369 #endif /* BITMAP_LATER */
3371 if (VInit >= 2 && V_needsCallback(vp)) {
3372 if (V_BreakVolumeCallbacks) {
3373 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3374 afs_printable_uint32_lu(V_id(vp)));
3375 V_needsCallback(vp) = 0;
3377 (*V_BreakVolumeCallbacks) (V_id(vp));
3380 VUpdateVolume_r(ec, vp, 0);
3382 #ifdef FSSYNC_BUILD_CLIENT
3383 else if (VCanUseFSSYNC()) {
3384 afs_int32 fsync_code;
3386 V_needsCallback(vp) = 0;
3388 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3392 V_needsCallback(vp) = 1;
3393 Log("Error trying to tell the fileserver to break callbacks for "
3394 "changed volume %lu; error code %ld\n",
3395 afs_printable_uint32_lu(V_id(vp)),
3396 afs_printable_int32_ld(fsync_code));
3398 VUpdateVolume_r(ec, vp, 0);
3401 #endif /* FSSYNC_BUILD_CLIENT */
3404 Log("VAttachVolume: error %d clearing needsCallback on volume "
3405 "%lu; needs salvage\n", (int)*ec,
3406 afs_printable_uint32_lu(V_id(vp)));
3407 #ifdef AFS_DEMAND_ATTACH_FS
3408 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3410 #else /* !AFS_DEMAND_ATTACH_FS */
3412 #endif /* !AFS_DEMAND_ATTACh_FS */
3417 if (programType == fileServer) {
3418 if (vp->specialStatus)
3419 vp->specialStatus = 0;
3420 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3421 V_inUse(vp) = fileServer;
3422 V_offlineMessage(vp)[0] = '\0';
3426 #ifdef AFS_DEMAND_ATTACH_FS
3427 /* Put the vol into PREATTACHED state, so if someone tries to
3428 * access it again, we try to attach, see that we're not blessed,
3429 * and give a VNOVOL error again. Putting it into UNATTACHED state
3430 * would result in a VOFFLINE error instead. */
3431 error_state = VOL_STATE_PREATTACHED;
3432 #endif /* AFS_DEMAND_ATTACH_FS */
3434 /* mimic e.g. GetVolume errors */
3435 if (!V_blessed(vp)) {
3436 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3437 FreeVolumeHeader(vp);
3438 } else if (!V_inService(vp)) {
3439 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3440 FreeVolumeHeader(vp);
3442 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3444 #ifdef AFS_DEMAND_ATTACH_FS
3445 error_state = VOL_STATE_ERROR;
3446 /* see if we can recover */
3447 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0 /*flags*/);
3450 #ifdef AFS_DEMAND_ATTACH_FS
3456 #ifdef AFS_DEMAND_ATTACH_FS
3457 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3458 V_inUse(vp) = programType;
3459 #endif /* AFS_DEMAND_ATTACH_FS */
3460 V_checkoutMode(vp) = mode;
3463 AddVolumeToHashTable(vp, V_id(vp));
3464 #ifdef AFS_DEMAND_ATTACH_FS
3465 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3468 if ((programType != fileServer) ||
3469 (V_inUse(vp) == fileServer)) {
3470 AddVolumeToVByPList_r(vp);
3472 VChangeState_r(vp, VOL_STATE_ATTACHED);
3474 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3483 #ifdef AFS_DEMAND_ATTACH_FS
3484 if (!VIsErrorState(V_attachState(vp))) {
3485 if (VIsErrorState(error_state)) {
3486 Log("attach2: forcing vol %u to error state (state %u flags 0x%x ec %d)\n",
3487 vp->hashid, V_attachState(vp), V_attachFlags(vp), *ec);
3489 VChangeState_r(vp, error_state);
3491 #endif /* AFS_DEMAND_ATTACH_FS */
3494 VReleaseVolumeHandles_r(vp);
3497 #ifdef AFS_DEMAND_ATTACH_FS
3499 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3500 /* The salvage could not be scheduled with the salvage server
3501 * due to a hard error. Reset the error code to prevent retry loops by
3503 if (*ec == VSALVAGING) {
3512 #else /* !AFS_DEMAND_ATTACH_FS */
3514 #endif /* !AFS_DEMAND_ATTACH_FS */
3518 /* Attach an existing volume.
3519 The volume also normally goes online at this time.
3520 An offline volume must be reattached to make it go online.
3524 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3528 retVal = VAttachVolume_r(ec, volumeId, mode);
3534 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3537 VGetVolumePath(ec, volumeId, &part, &name);
3541 vp = VGetVolume_r(&error, volumeId);
3543 opr_Assert(V_inUse(vp) == 0);
3544 VDetachVolume_r(ec, vp);
3548 return VAttachVolumeByName_r(ec, part, name, mode);
3551 /* Increment a reference count to a volume, sans context swaps. Requires
3552 * possibly reading the volume header in from the disk, since there's
3553 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3555 * N.B. This call can fail if we can't read in the header!! In this case
3556 * we still guarantee we won't context swap, but the ref count won't be
3557 * incremented (otherwise we'd violate the invariant).
3559 /* NOTE: with the demand attach fileserver extensions, the global lock
3560 * is dropped within VHold */
3561 #ifdef AFS_DEMAND_ATTACH_FS
3563 VHold_r(Volume * vp)
3567 VCreateReservation_r(vp);
3568 VWaitExclusiveState_r(vp);
3570 LoadVolumeHeader(&error, vp);
3572 VCancelReservation_r(vp);
3576 VCancelReservation_r(vp);
3579 #else /* AFS_DEMAND_ATTACH_FS */
3581 VHold_r(Volume * vp)
3585 LoadVolumeHeader(&error, vp);
3591 #endif /* AFS_DEMAND_ATTACH_FS */
3593 /**** volume timeout-related stuff ****/
3595 #ifdef AFS_PTHREAD_ENV
3597 static struct timespec *shutdown_timeout;
3598 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3601 VTimedOut(const struct timespec *ts)
3606 if (ts->tv_sec == 0) {
3607 /* short-circuit; this will have always timed out */
3611 code = gettimeofday(&tv, NULL);
3613 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3614 /* assume no timeout; failure mode is we just wait longer than normal
3615 * instead of returning errors when we shouldn't */
3619 if (tv.tv_sec < ts->tv_sec ||
3620 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3629 * Calculate an absolute timeout.
3631 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3632 * NULL, the memory is not touched
3633 * @param[in] timeout How long the timeout should be from now
3635 * @return timeout to use
3636 * @retval NULL no timeout; wait forever
3637 * @retval non-NULL the given value for "ts"
3641 static struct timespec *
3642 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3652 ts->tv_sec = ts->tv_nsec = 0;
3656 code = gettimeofday(&now, NULL);
3658 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3662 ts->tv_sec = now.tv_sec + timeout;
3663 ts->tv_nsec = now.tv_usec * 1000;
3669 * Initialize the shutdown_timeout global.
3672 VShutdownTimeoutInit(void)
3674 struct timespec *ts;
3676 ts = malloc(sizeof(*ts));
3678 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3680 if (!shutdown_timeout) {
3686 * Figure out the timeout that should be used for waiting for offline volumes.
3688 * @param[out] ats Storage space for a local timeout value if needed
3690 * @return The timeout value that should be used
3691 * @retval NULL No timeout; wait forever for offlining volumes
3692 * @retval non-NULL A pointer to the absolute time that should be used as
3693 * the deadline for waiting for offlining volumes.
3695 * @note If we return non-NULL, the pointer we return may or may not be the
3698 static const struct timespec *
3699 VOfflineTimeout(struct timespec *ats)
3701 if (vol_shutting_down) {
3702 opr_Verify(pthread_once(&shutdown_timeout_once,
3703 VShutdownTimeoutInit) == 0);
3704 return shutdown_timeout;
3706 return VCalcTimeout(ats, vol_opts.offline_timeout);
3710 #else /* AFS_PTHREAD_ENV */
3712 /* Waiting a certain amount of time for offlining volumes is not supported
3713 * for LWP due to a lack of primitives. So, we never time out */
3714 # define VTimedOut(x) (0)
3715 # define VOfflineTimeout(x) (NULL)
3717 #endif /* !AFS_PTHREAD_ENV */
3725 retVal = VHold_r(vp);
3732 VIsGoingOffline_r(struct Volume *vp)
3736 if (vp->goingOffline) {
3737 if (vp->specialStatus) {
3738 code = vp->specialStatus;
3739 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3750 * Tell the caller if a volume is waiting to go offline.
3752 * @param[in] vp The volume we want to know about
3754 * @return volume status
3755 * @retval 0 volume is not waiting to go offline, go ahead and use it
3756 * @retval nonzero volume is waiting to offline, and give the returned code
3757 * as an error to anyone accessing the volume
3759 * @pre VOL_LOCK is NOT held
3760 * @pre caller holds a heavyweight reference on vp
3763 VIsGoingOffline(struct Volume *vp)
3768 code = VIsGoingOffline_r(vp);
3775 * Register an RX call with a volume.
3777 * @param[inout] ec Error code; if unset when passed in, may be set if
3778 * the volume starts going offline
3779 * @param[out] client_ec @see GetVolume
3780 * @param[in] vp Volume struct
3781 * @param[in] cbv VCallByVol struct containing the RX call to register
3783 * @pre VOL_LOCK held
3784 * @pre caller holds heavy ref on vp
3789 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3792 #ifdef AFS_DEMAND_ATTACH_FS
3794 /* just in case the volume started going offline after we got the
3795 * reference to it... otherwise, if the volume started going
3796 * offline right at the end of GetVolume(), we might race with the
3797 * RX call scanner, and return success and add our cbv to the
3798 * rx_call_list _after_ the scanner has scanned the list. */
3799 *ec = VIsGoingOffline_r(vp);
3805 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3806 VWaitStateChange_r(vp);
3808 #endif /* AFS_DEMAND_ATTACH_FS */
3810 queue_Prepend(&vp->rx_call_list, cbv);
3815 * Deregister an RX call with a volume.
3817 * @param[in] vp Volume struct
3818 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3820 * @pre VOL_LOCK held
3821 * @pre caller holds heavy ref on vp
3826 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3828 if (cbv && queue_IsOnQueue(cbv)) {
3829 #ifdef AFS_DEMAND_ATTACH_FS
3830 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3831 VWaitStateChange_r(vp);
3833 #endif /* AFS_DEMAND_ATTACH_FS */
3839 /***************************************************/
3840 /* get and put volume routines */
3841 /***************************************************/
3844 * put back a heavyweight reference to a volume object.
3846 * @param[in] vp volume object pointer
3848 * @pre VOL_LOCK held
3850 * @post heavyweight volume reference put back.
3851 * depending on state, volume may have been taken offline,
3852 * detached, salvaged, freed, etc.
3854 * @internal volume package internal use only
3857 VPutVolume_r(Volume * vp)
3859 opr_Verify(--vp->nUsers >= 0);
3860 if (vp->nUsers == 0) {
3862 ReleaseVolumeHeader(vp->header);
3863 #ifdef AFS_DEMAND_ATTACH_FS
3864 if (!VCheckDetach(vp)) {
3868 #else /* AFS_DEMAND_ATTACH_FS */
3870 #endif /* AFS_DEMAND_ATTACH_FS */
3875 VPutVolume(Volume * vp)
3883 * Puts a volume reference obtained with VGetVolumeWithCall.
3885 * @param[in] vp Volume struct
3886 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3888 * @pre VOL_LOCK is NOT held
3891 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3894 VDeregisterCall_r(vp, cbv);
3899 /* Get a pointer to an attached volume. The pointer is returned regardless
3900 of whether or not the volume is in service or on/off line. An error
3901 code, however, is returned with an indication of the volume's status */
3903 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3907 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3913 * Get a volume reference associated with an RX call.
3915 * @param[out] ec @see GetVolume
3916 * @param[out] client_ec @see GetVolume
3917 * @param[in] volumeId @see GetVolume
3918 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3919 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3920 * with an error if the volume is going offline.
3921 * @param[in] cbv Contains an RX call to be associated with this volume
3922 * reference. This call may be interrupted if the volume is
3923 * requested to go offline while we hold a ref on it. Give NULL
3924 * to not associate an RX call with this reference.
3926 * @return @see GetVolume
3928 * @note for LWP builds, ts must be NULL
3930 * @note A reference obtained with this function MUST be put back with
3931 * VPutVolumeWithCall
3934 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3935 const struct timespec *ts, struct VCallByVol *cbv)
3939 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3940 VRegisterCall_r(ec, client_ec, retVal, cbv);
3946 VGetVolume_r(Error * ec, VolId volumeId)
3948 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3951 /* try to get a volume we've previously looked up */
3952 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3954 VGetVolumeByVp_r(Error * ec, Volume * vp)
3956 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3960 * private interface for getting a volume handle
3962 * @param[out] ec error code (0 if no error)
3963 * @param[out] client_ec wire error code to be given to clients
3964 * @param[in] volumeId ID of the volume we want
3965 * @param[in] hint optional hint for hash lookups, or NULL
3966 * @param[in] timeout absolute deadline for waiting for the volume to go
3967 * offline, if it is going offline. NULL to wait forever.
3969 * @return a volume handle for the specified volume
3970 * @retval NULL an error occurred, or the volume is in such a state that
3971 * we cannot load a header or return any volume struct
3973 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3975 * @note 'timeout' is only checked if the volume is actually going offline; so
3976 * if you pass timeout->tv_sec = 0, this will exhibit typical
3977 * nonblocking behavior.
3979 * @note for LWP builds, 'timeout' must be NULL
3982 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3983 const struct timespec *timeout)
3986 /* pull this profiling/debugging code out of regular builds */
3988 #define VGET_CTR_INC(x) x++
3989 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3990 0, V7 = 0, V8 = 0, V9 = 0;
3991 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3993 #define VGET_CTR_INC(x)
3995 #ifdef AFS_DEMAND_ATTACH_FS
3996 Volume *avp, * rvp = hint;
4000 * if VInit is zero, the volume package dynamic
4001 * data structures have not been initialized yet,
4002 * and we must immediately return an error
4008 *client_ec = VOFFLINE;
4013 #ifdef AFS_DEMAND_ATTACH_FS
4015 VCreateReservation_r(rvp);
4017 #endif /* AFS_DEMAND_ATTACH_FS */
4025 vp = VLookupVolume_r(ec, volumeId, vp);
4031 #ifdef AFS_DEMAND_ATTACH_FS
4032 if (rvp && (rvp != vp)) {
4033 /* break reservation on old vp */
4034 VCancelReservation_r(rvp);
4037 #endif /* AFS_DEMAND_ATTACH_FS */
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. */
4058 IncUInt64(&VStats.hdr_gets);
4060 #ifdef AFS_DEMAND_ATTACH_FS
4061 /* block if someone else is performing an exclusive op on this volume */
4064 VCreateReservation_r(rvp);
4066 VWaitExclusiveState_r(vp);
4068 /* short circuit with VNOVOL in the following circumstances:
4071 * - VOL_STATE_SHUTTING_DOWN
4073 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4074 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4081 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4082 * VNOVOL for VOL_STATE_DELETED
4084 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4085 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4086 (V_attachState(vp) == VOL_STATE_DELETED)) {
4087 if (vp->specialStatus) {
4088 *ec = vp->specialStatus;
4089 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4098 /* allowable states:
4105 if (vp->salvage.requested) {
4106 VUpdateSalvagePriority_r(vp);
4109 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4110 if (vp->specialStatus) {
4111 *ec = vp->specialStatus;
4115 avp = VAttachVolumeByVp_r(ec, vp, 0);
4118 /* VAttachVolumeByVp_r can return a pointer
4119 * != the vp passed to it under certain
4120 * conditions; make sure we don't leak
4121 * reservations if that happens */
4123 VCancelReservation_r(rvp);
4125 VCreateReservation_r(rvp);
4136 if (vp->specialStatus) {
4137 *ec = vp->specialStatus;
4142 if (vp->specialStatus) {
4143 *ec = vp->specialStatus;
4156 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4158 /* see CheckVnode() in afsfileprocs.c for an explanation
4159 * of this error code logic */
4160 afs_uint32 now = FT_ApproxTime();
4161 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4164 *client_ec = VRESTARTING;
4172 if (VIsErrorState(V_attachState(vp))) {
4173 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4174 * it, or transition it out of that state */
4183 * this test MUST happen after VAttachVolymeByVp, so we have no
4184 * conflicting vol op. (attach2 would have errored out if we had one;
4185 * specifically attach_check_vop must have detected a conflicting vop)
4187 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4189 #endif /* AFS_DEMAND_ATTACH_FS */
4191 LoadVolumeHeader(ec, vp);
4194 /* Only log the error if it was a totally unexpected error. Simply
4195 * a missing inode is likely to be caused by the volume being deleted */
4196 if (errno != ENXIO || LogLevel)
4197 Log("Volume %u: couldn't reread volume header\n",
4199 #ifdef AFS_DEMAND_ATTACH_FS
4200 if (VCanScheduleSalvage()) {
4201 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4206 #else /* AFS_DEMAND_ATTACH_FS */
4209 #endif /* AFS_DEMAND_ATTACH_FS */
4214 if (vp->shuttingDown) {
4221 if (programType == fileServer) {
4223 if (vp->goingOffline) {
4224 if (timeout && VTimedOut(timeout)) {
4225 /* we've timed out; don't wait for the vol */
4228 #ifdef AFS_DEMAND_ATTACH_FS
4229 /* wait for the volume to go offline */
4230 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4231 VTimedWaitStateChange_r(vp, timeout, NULL);
4233 #elif defined(AFS_PTHREAD_ENV)
4234 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4235 #else /* AFS_PTHREAD_ENV */
4236 /* LWP has no timed wait, so the caller better not be
4238 opr_Assert(!timeout);
4239 LWP_WaitProcess(VPutVolume);
4240 #endif /* AFS_PTHREAD_ENV */
4244 if (vp->specialStatus) {
4246 *ec = vp->specialStatus;
4247 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4250 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4261 #ifdef AFS_DEMAND_ATTACH_FS
4262 /* if no error, bump nUsers */
4265 VLRU_UpdateAccess_r(vp);
4268 VCancelReservation_r(rvp);
4271 if (client_ec && !*client_ec) {
4274 #else /* AFS_DEMAND_ATTACH_FS */
4275 /* if no error, bump nUsers */
4282 #endif /* AFS_DEMAND_ATTACH_FS */
4285 opr_Assert(vp || *ec);
4290 /***************************************************/
4291 /* Volume offline/detach routines */
4292 /***************************************************/
4294 /* caller MUST hold a heavyweight ref on vp */
4295 #ifdef AFS_DEMAND_ATTACH_FS
4297 VTakeOffline_r(Volume * vp)
4301 opr_Assert(vp->nUsers > 0);
4302 opr_Assert(programType == fileServer);
4304 VCreateReservation_r(vp);
4305 VWaitExclusiveState_r(vp);
4307 vp->goingOffline = 1;
4308 V_needsSalvaged(vp) = 1;
4310 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4311 VCancelReservation_r(vp);
4313 #else /* AFS_DEMAND_ATTACH_FS */
4315 VTakeOffline_r(Volume * vp)
4317 opr_Assert(vp->nUsers > 0);
4318 opr_Assert(programType == fileServer);
4320 vp->goingOffline = 1;
4321 V_needsSalvaged(vp) = 1;
4323 #endif /* AFS_DEMAND_ATTACH_FS */
4326 VTakeOffline(Volume * vp)
4334 * force a volume offline.
4336 * @param[in] vp volume object pointer
4337 * @param[in] flags flags (see note below)
4339 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4340 * used when VUpdateVolume_r needs to call VForceOffline_r
4341 * (which in turn would normally call VUpdateVolume_r)
4343 * @see VUpdateVolume_r
4345 * @pre VOL_LOCK must be held.
4346 * for DAFS, caller must hold ref.
4348 * @note for DAFS, it _is safe_ to call this function from an
4351 * @post needsSalvaged flag is set.
4352 * for DAFS, salvage is requested.
4353 * no further references to the volume through the volume
4354 * package will be honored.
4355 * all file descriptor and vnode caches are invalidated.
4357 * @warning this is a heavy-handed interface. it results in
4358 * a volume going offline regardless of the current
4359 * reference count state.
4361 * @internal volume package internal use only
4364 VForceOffline_r(Volume * vp, int flags)
4368 #ifdef AFS_DEMAND_ATTACH_FS
4369 VChangeState_r(vp, VOL_STATE_ERROR);
4374 strcpy(V_offlineMessage(vp),
4375 "Forced offline due to internal error: volume needs to be salvaged");
4376 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4379 vp->goingOffline = 0;
4380 V_needsSalvaged(vp) = 1;
4381 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4382 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4385 #ifdef AFS_DEMAND_ATTACH_FS
4386 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4387 #endif /* AFS_DEMAND_ATTACH_FS */
4389 #ifdef AFS_PTHREAD_ENV
4390 CV_BROADCAST(&vol_put_volume_cond);
4391 #else /* AFS_PTHREAD_ENV */
4392 LWP_NoYieldSignal(VPutVolume);
4393 #endif /* AFS_PTHREAD_ENV */
4395 VReleaseVolumeHandles_r(vp);
4399 * force a volume offline.
4401 * @param[in] vp volume object pointer
4403 * @see VForceOffline_r
4406 VForceOffline(Volume * vp)
4409 VForceOffline_r(vp, 0);
4414 * Iterate over the RX calls associated with a volume, and interrupt them.
4416 * @param[in] vp The volume whose RX calls we want to scan
4418 * @pre VOL_LOCK held
4421 VScanCalls_r(struct Volume *vp)
4423 struct VCallByVol *cbv, *ncbv;
4425 #ifdef AFS_DEMAND_ATTACH_FS
4426 VolState state_save;
4429 if (queue_IsEmpty(&vp->rx_call_list))
4430 return; /* no calls to interrupt */
4431 if (!vol_opts.interrupt_rxcall)
4432 return; /* we have no function with which to interrupt calls */
4433 err = VIsGoingOffline_r(vp);
4435 return; /* we're not going offline anymore */
4437 #ifdef AFS_DEMAND_ATTACH_FS
4438 VWaitExclusiveState_r(vp);
4439 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4441 #endif /* AFS_DEMAND_ATTACH_FS */
4443 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4445 struct rx_peer *peer;
4447 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4449 Log("Offlining volume %lu while client %s:%u is trying to read "
4450 "from it; kicking client off with error %ld\n",
4451 (long unsigned) vp->hashid,
4452 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4453 (unsigned) ntohs(rx_PortOf(peer)),
4456 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4459 #ifdef AFS_DEMAND_ATTACH_FS
4461 VChangeState_r(vp, state_save);
4462 #endif /* AFS_DEMAND_ATTACH_FS */
4465 #ifdef AFS_DEMAND_ATTACH_FS
4467 * Wait for a vp to go offline.
4469 * @param[out] ec 1 if a salvage on the volume has been requested and
4470 * salvok == 0, 0 otherwise
4471 * @param[in] vp The volume to wait for
4472 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4473 * has been requested to salvage. Otherwise we keep waiting
4474 * until the volume has gone offline.
4476 * @pre VOL_LOCK held
4477 * @pre caller holds a lightweight ref on vp
4482 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4484 struct timespec timeout_ts;
4485 const struct timespec *ts;
4488 ts = VOfflineTimeout(&timeout_ts);
4492 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4493 if (!salvok && vp->salvage.requested) {
4497 VTimedWaitStateChange_r(vp, ts, &timedout);
4500 /* we didn't time out, so the volume must be offline, so we're done */
4504 /* If we got here, we timed out waiting for the volume to go offline.
4505 * Kick off the accessing RX calls and wait again */
4509 while (!VIsOfflineState(V_attachState(vp))) {
4510 if (!salvok && vp->salvage.requested) {
4515 VWaitStateChange_r(vp);
4519 #else /* AFS_DEMAND_ATTACH_FS */
4522 * Wait for a volume to go offline.
4524 * @pre VOL_LOCK held
4526 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4529 VWaitForOffline_r(Error *ec, VolumeId volid)
4532 const struct timespec *ts;
4533 #ifdef AFS_PTHREAD_ENV
4534 struct timespec timeout_ts;
4537 ts = VOfflineTimeout(&timeout_ts);
4539 vp = GetVolume(ec, NULL, volid, NULL, ts);
4541 /* error occurred so bad that we can't even get a vp; we have no
4542 * information on the vol so we don't know whether to wait, so just
4546 if (!VIsGoingOffline_r(vp)) {
4547 /* volume is no longer going offline, so we're done */
4552 /* If we got here, we timed out waiting for the volume to go offline.
4553 * Kick off the accessing RX calls and wait again */
4559 vp = VGetVolume_r(ec, volid);
4561 /* In case it was reattached... */
4565 #endif /* !AFS_DEMAND_ATTACH_FS */
4567 /* The opposite of VAttachVolume. The volume header is written to disk, with
4568 the inUse bit turned off. A copy of the header is maintained in memory,
4569 however (which is why this is VOffline, not VDetach).
4572 VOffline_r(Volume * vp, char *message)
4575 #ifndef AFS_DEMAND_ATTACH_FS
4576 VolumeId vid = V_id(vp);
4579 opr_Assert(programType != volumeUtility && programType != volumeServer);
4584 if (V_offlineMessage(vp)[0] == '\0')
4585 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4586 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4588 vp->goingOffline = 1;
4589 #ifdef AFS_DEMAND_ATTACH_FS
4590 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4591 VCreateReservation_r(vp);
4593 VWaitForOfflineByVp_r(&error, vp, 1);
4594 VCancelReservation_r(vp);
4595 #else /* AFS_DEMAND_ATTACH_FS */
4597 VWaitForOffline_r(&error, vid);
4598 #endif /* AFS_DEMAND_ATTACH_FS */
4601 #ifdef AFS_DEMAND_ATTACH_FS
4603 * Take a volume offline in order to perform a volume operation.
4605 * @param[inout] ec address in which to store error code
4606 * @param[in] vp volume object pointer
4607 * @param[in] message volume offline status message
4610 * - VOL_LOCK is held
4611 * - caller MUST hold a heavyweight ref on vp
4614 * - volume is taken offline
4615 * - if possible, volume operation is promoted to running state
4616 * - on failure, *ec is set to nonzero
4618 * @note Although this function does not return any value, it may
4619 * still fail to promote our pending volume operation to
4620 * a running state. Any caller MUST check the value of *ec,
4621 * and MUST NOT blindly assume success.
4623 * @warning if the caller does not hold a lightweight ref on vp,
4624 * then it MUST NOT reference vp after this function
4625 * returns to the caller.
4627 * @internal volume package internal use only
4630 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4633 opr_Assert(vp->pending_vol_op);
4639 if (V_offlineMessage(vp)[0] == '\0')
4640 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4641 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4643 vp->goingOffline = 1;
4644 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4645 VCreateReservation_r(vp);
4648 if (vp->pending_vol_op->com.programType != salvageServer) {
4649 /* do not give corrupted volumes to the volserver */
4654 VWaitForOfflineByVp_r(ec, vp, salvok);
4656 VCancelReservation_r(vp);
4658 #endif /* AFS_DEMAND_ATTACH_FS */
4661 VOffline(Volume * vp, char *message)
4664 VOffline_r(vp, message);
4668 /* This gets used for the most part by utility routines that don't want
4669 * to keep all the volume headers around. Generally, the file server won't
4670 * call this routine, because then the offline message in the volume header
4671 * (or other information) won't be available to clients. For NAMEI, also
4672 * close the file handles. However, the fileserver does call this during
4673 * an attach following a volume operation.
4676 VDetachVolume_r(Error * ec, Volume * vp)
4678 #ifdef FSSYNC_BUILD_CLIENT
4680 struct DiskPartition64 *tpartp;
4681 int notifyServer = 0;
4682 int useDone = FSYNC_VOL_ON;
4684 if (VCanUseFSSYNC()) {
4685 notifyServer = vp->needsPutBack;
4686 if (V_destroyMe(vp) == DESTROY_ME)
4687 useDone = FSYNC_VOL_LEAVE_OFF;
4688 # ifdef AFS_DEMAND_ATTACH_FS
4689 else if (!V_blessed(vp) || !V_inService(vp))
4690 useDone = FSYNC_VOL_LEAVE_OFF;
4693 # ifdef AFS_DEMAND_ATTACH_FS
4694 if (V_needsSalvaged(vp)) {
4696 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4699 tpartp = vp->partition;
4701 #endif /* FSSYNC_BUILD_CLIENT */
4703 *ec = 0; /* always "succeeds" */
4704 DeleteVolumeFromHashTable(vp);
4705 vp->shuttingDown = 1;
4706 #ifdef AFS_DEMAND_ATTACH_FS
4707 DeleteVolumeFromVByPList_r(vp);
4709 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4711 if (programType != fileServer)
4713 #endif /* AFS_DEMAND_ATTACH_FS */
4715 /* Will be detached sometime in the future--this is OK since volume is offline */
4717 /* XXX the following code should really be moved to VCheckDetach() since the volume
4718 * is not technically detached until the refcounts reach zero
4720 #ifdef FSSYNC_BUILD_CLIENT
4721 if (VCanUseFSSYNC() && notifyServer) {
4722 if (notifyServer == VOL_PUTBACK_DELETE) {
4723 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4724 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4725 * to signify a deleted volume. */
4726 useDone = FSYNC_VOL_DONE;
4729 * Note: The server is not notified in the case of a bogus volume
4730 * explicitly to make it possible to create a volume, do a partial
4731 * restore, then abort the operation without ever putting the volume
4732 * online. This is essential in the case of a volume move operation
4733 * between two partitions on the same server. In that case, there
4734 * would be two instances of the same volume, one of them bogus,
4735 * which the file server would attempt to put on line
4737 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4738 /* XXX this code path is only hit by volume utilities, thus
4739 * V_BreakVolumeCallbacks will always be NULL. if we really
4740 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4742 /* Dettaching it so break all callbacks on it */
4743 if (V_BreakVolumeCallbacks) {
4744 Log("volume %u detached; breaking all call backs\n", volume);
4745 (*V_BreakVolumeCallbacks) (volume);
4749 #endif /* FSSYNC_BUILD_CLIENT */
4753 VDetachVolume(Error * ec, Volume * vp)
4756 VDetachVolume_r(ec, vp);
4761 /***************************************************/
4762 /* Volume fd/inode handle closing routines */
4763 /***************************************************/
4765 /* For VDetachVolume, we close all cached file descriptors, but keep
4766 * the Inode handles in case we need to read from a busy volume.
4768 /* for demand attach, caller MUST hold ref count on vp */
4770 VCloseVolumeHandles_r(Volume * vp)
4772 #ifdef AFS_DEMAND_ATTACH_FS
4773 VolState state_save;
4775 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4780 DFlushVolume(vp->hashid);
4782 #ifdef AFS_DEMAND_ATTACH_FS
4786 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4787 VCloseVnodeFiles_r(vp);
4789 #ifdef AFS_DEMAND_ATTACH_FS
4793 /* Too time consuming and unnecessary for the volserver */
4794 if (programType == fileServer) {
4795 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4796 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4797 IH_CONDSYNC(vp->diskDataHandle);
4799 IH_CONDSYNC(vp->linkHandle);
4800 #endif /* AFS_NT40_ENV */
4803 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4804 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4805 IH_REALLYCLOSE(vp->diskDataHandle);
4806 IH_REALLYCLOSE(vp->linkHandle);
4808 #ifdef AFS_DEMAND_ATTACH_FS
4809 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4814 VChangeState_r(vp, state_save);
4818 /* For both VForceOffline and VOffline, we close all relevant handles.
4819 * For VOffline, if we re-attach the volume, the files may possible be
4820 * different than before.
4822 /* for demand attach, caller MUST hold a ref count on vp */
4824 VReleaseVolumeHandles_r(Volume * vp)
4826 #ifdef AFS_DEMAND_ATTACH_FS
4827 VolState state_save;
4829 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4834 DFlushVolume(vp->hashid);
4836 #ifdef AFS_DEMAND_ATTACH_FS
4840 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4842 #ifdef AFS_DEMAND_ATTACH_FS
4846 /* Too time consuming and unnecessary for the volserver */
4847 if (programType == fileServer) {
4848 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4849 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4850 IH_CONDSYNC(vp->diskDataHandle);
4852 IH_CONDSYNC(vp->linkHandle);
4853 #endif /* AFS_NT40_ENV */
4856 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4857 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4858 IH_RELEASE(vp->diskDataHandle);
4859 IH_RELEASE(vp->linkHandle);
4861 #ifdef AFS_DEMAND_ATTACH_FS
4862 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4867 VChangeState_r(vp, state_save);
4872 /***************************************************/
4873 /* Volume write and fsync routines */
4874 /***************************************************/
4877 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4879 #ifdef AFS_DEMAND_ATTACH_FS
4880 VolState state_save;
4882 if (flags & VOL_UPDATE_WAIT) {
4883 VCreateReservation_r(vp);
4884 VWaitExclusiveState_r(vp);
4889 if (programType == fileServer)
4891 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4892 200 : V_nextVnodeUnique(vp));
4894 #ifdef AFS_DEMAND_ATTACH_FS
4895 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4899 WriteVolumeHeader_r(ec, vp);
4901 #ifdef AFS_DEMAND_ATTACH_FS
4903 VChangeState_r(vp, state_save);
4904 if (flags & VOL_UPDATE_WAIT) {
4905 VCancelReservation_r(vp);
4910 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4911 V_id(vp), V_name(vp));
4912 /* try to update on-disk header,
4913 * while preventing infinite recursion */
4914 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4915 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4921 VUpdateVolume(Error * ec, Volume * vp)
4924 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4929 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4933 #ifdef AFS_DEMAND_ATTACH_FS
4934 VolState state_save;
4937 if (flags & VOL_SYNC_WAIT) {
4938 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4940 VUpdateVolume_r(ec, vp, 0);
4943 #ifdef AFS_DEMAND_ATTACH_FS
4944 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4947 fdP = IH_OPEN(V_diskDataHandle(vp));
4948 opr_Assert(fdP != NULL);
4949 code = FDH_SYNC(fdP);
4950 opr_Assert(code == 0);
4952 #ifdef AFS_DEMAND_ATTACH_FS
4954 VChangeState_r(vp, state_save);
4960 VSyncVolume(Error * ec, Volume * vp)
4963 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4968 /***************************************************/
4969 /* Volume dealloaction routines */
4970 /***************************************************/
4972 #ifdef AFS_DEMAND_ATTACH_FS
4974 FreeVolume(Volume * vp)
4976 /* free the heap space, iff it's safe.
4977 * otherwise, pull it out of the hash table, so it
4978 * will get deallocated when all refs to it go away */
4979 if (!VCheckFree(vp)) {
4980 DeleteVolumeFromHashTable(vp);
4981 DeleteVolumeFromVByPList_r(vp);
4983 /* make sure we invalidate the header cache entry */
4984 FreeVolumeHeader(vp);
4987 #endif /* AFS_DEMAND_ATTACH_FS */
4990 ReallyFreeVolume(Volume * vp)
4995 #ifdef AFS_DEMAND_ATTACH_FS
4997 VChangeState_r(vp, VOL_STATE_FREED);
4998 if (vp->pending_vol_op)
4999 free(vp->pending_vol_op);
5000 #endif /* AFS_DEMAND_ATTACH_FS */
5001 for (i = 0; i < nVNODECLASSES; i++)
5002 if (vp->vnodeIndex[i].bitmap)
5003 free(vp->vnodeIndex[i].bitmap);
5004 FreeVolumeHeader(vp);
5005 #ifndef AFS_DEMAND_ATTACH_FS
5006 DeleteVolumeFromHashTable(vp);
5007 #endif /* AFS_DEMAND_ATTACH_FS */
5011 /* check to see if we should shutdown this volume
5012 * returns 1 if volume was freed, 0 otherwise */
5013 #ifdef AFS_DEMAND_ATTACH_FS
5015 VCheckDetach(Volume * vp)
5020 if (vp->nUsers || vp->nWaiters)
5023 if (vp->shuttingDown) {
5025 if ((programType != fileServer) &&
5026 (V_inUse(vp) == programType) &&
5027 ((V_checkoutMode(vp) == V_VOLUPD) ||
5028 (V_checkoutMode(vp) == V_SECRETLY) ||
5029 ((V_checkoutMode(vp) == V_CLONE) &&
5030 (VolumeWriteable(vp))))) {
5032 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5034 Log("VCheckDetach: volume header update for volume %u "
5035 "failed with errno %d\n", vp->hashid, errno);
5038 VReleaseVolumeHandles_r(vp);
5040 ReallyFreeVolume(vp);
5041 if (programType == fileServer) {
5042 CV_BROADCAST(&vol_put_volume_cond);
5047 #else /* AFS_DEMAND_ATTACH_FS */
5049 VCheckDetach(Volume * vp)
5057 if (vp->shuttingDown) {
5059 if ((programType != fileServer) &&
5060 (V_inUse(vp) == programType) &&
5061 ((V_checkoutMode(vp) == V_VOLUPD) ||
5062 (V_checkoutMode(vp) == V_SECRETLY) ||
5063 ((V_checkoutMode(vp) == V_CLONE) &&
5064 (VolumeWriteable(vp))))) {
5066 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5068 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5072 VReleaseVolumeHandles_r(vp);
5073 ReallyFreeVolume(vp);
5074 if (programType == fileServer) {
5075 #if defined(AFS_PTHREAD_ENV)
5076 CV_BROADCAST(&vol_put_volume_cond);
5077 #else /* AFS_PTHREAD_ENV */
5078 LWP_NoYieldSignal(VPutVolume);
5079 #endif /* AFS_PTHREAD_ENV */
5084 #endif /* AFS_DEMAND_ATTACH_FS */
5086 /* check to see if we should offline this volume
5087 * return 1 if volume went offline, 0 otherwise */
5088 #ifdef AFS_DEMAND_ATTACH_FS
5090 VCheckOffline(Volume * vp)
5094 if (vp->goingOffline && !vp->nUsers) {
5096 opr_Assert(programType == fileServer);
5097 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5098 (V_attachState(vp) != VOL_STATE_FREED) &&
5099 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5100 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5101 (V_attachState(vp) != VOL_STATE_DELETED));
5105 * VOL_STATE_GOING_OFFLINE
5106 * VOL_STATE_SHUTTING_DOWN
5107 * VIsErrorState(V_attachState(vp))
5108 * VIsExclusiveState(V_attachState(vp))
5111 VCreateReservation_r(vp);
5112 VChangeState_r(vp, VOL_STATE_OFFLINING);
5115 /* must clear the goingOffline flag before we drop the glock */
5116 vp->goingOffline = 0;
5121 /* perform async operations */
5122 VUpdateVolume_r(&error, vp, 0);
5123 VCloseVolumeHandles_r(vp);
5126 if (V_offlineMessage(vp)[0]) {
5127 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5128 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5129 V_offlineMessage(vp));
5131 Log("VOffline: Volume %lu (%s) is now offline\n",
5132 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5136 /* invalidate the volume header cache entry */
5137 FreeVolumeHeader(vp);
5139 /* if nothing changed state to error or salvaging,
5140 * drop state to unattached */
5141 if (!VIsErrorState(V_attachState(vp))) {
5142 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5144 VCancelReservation_r(vp);
5145 /* no usage of vp is safe beyond this point */
5149 #else /* AFS_DEMAND_ATTACH_FS */
5151 VCheckOffline(Volume * vp)
5155 if (vp->goingOffline && !vp->nUsers) {
5157 opr_Assert(programType == fileServer);
5160 vp->goingOffline = 0;
5162 VUpdateVolume_r(&error, vp, 0);
5163 VCloseVolumeHandles_r(vp);
5165 if (V_offlineMessage(vp)[0]) {
5166 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5167 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5168 V_offlineMessage(vp));
5170 Log("VOffline: Volume %lu (%s) is now offline\n",
5171 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5174 FreeVolumeHeader(vp);
5175 #ifdef AFS_PTHREAD_ENV
5176 CV_BROADCAST(&vol_put_volume_cond);
5177 #else /* AFS_PTHREAD_ENV */
5178 LWP_NoYieldSignal(VPutVolume);
5179 #endif /* AFS_PTHREAD_ENV */
5183 #endif /* AFS_DEMAND_ATTACH_FS */
5185 /***************************************************/
5186 /* demand attach fs ref counting routines */
5187 /***************************************************/
5189 #ifdef AFS_DEMAND_ATTACH_FS
5190 /* the following two functions handle reference counting for
5191 * asynchronous operations on volume structs.
5193 * their purpose is to prevent a VDetachVolume or VShutdown
5194 * from free()ing the Volume struct during an async i/o op */
5196 /* register with the async volume op ref counter */
5197 /* VCreateReservation_r moved into inline code header because it
5198 * is now needed in vnode.c -- tkeiser 11/20/2007
5202 * decrement volume-package internal refcount.
5204 * @param vp volume object pointer
5206 * @internal volume package internal use only
5209 * @arg VOL_LOCK is held
5210 * @arg lightweight refcount held
5212 * @post volume waiters refcount is decremented; volume may
5213 * have been deallocated/shutdown/offlined/salvaged/
5214 * whatever during the process
5216 * @warning once you have tossed your last reference (you can acquire
5217 * lightweight refs recursively) it is NOT SAFE to reference
5218 * a volume object pointer ever again
5220 * @see VCreateReservation_r
5222 * @note DEMAND_ATTACH_FS only
5225 VCancelReservation_r(Volume * vp)
5227 opr_Verify(--vp->nWaiters >= 0);
5228 if (vp->nWaiters == 0) {
5230 if (!VCheckDetach(vp)) {
5237 /* check to see if we should free this volume now
5238 * return 1 if volume was freed, 0 otherwise */
5240 VCheckFree(Volume * vp)
5243 if ((vp->nUsers == 0) &&
5244 (vp->nWaiters == 0) &&
5245 !(V_attachFlags(vp) & (VOL_IN_HASH |
5249 ReallyFreeVolume(vp);
5254 #endif /* AFS_DEMAND_ATTACH_FS */
5257 /***************************************************/
5258 /* online volume operations routines */
5259 /***************************************************/
5261 #ifdef AFS_DEMAND_ATTACH_FS
5263 * register a volume operation on a given volume.
5265 * @param[in] vp volume object
5266 * @param[in] vopinfo volume operation info object
5268 * @pre VOL_LOCK is held
5270 * @post volume operation info object attached to volume object.
5271 * volume operation statistics updated.
5273 * @note by "attached" we mean a copy of the passed in object is made
5275 * @internal volume package internal use only
5278 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5280 FSSYNC_VolOp_info * info;
5282 /* attach a vol op info node to the volume struct */
5283 info = malloc(sizeof(FSSYNC_VolOp_info));
5284 opr_Assert(info != NULL);
5285 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5286 vp->pending_vol_op = info;
5289 vp->stats.last_vol_op = FT_ApproxTime();
5290 vp->stats.vol_ops++;
5291 IncUInt64(&VStats.vol_ops);
5297 * deregister the volume operation attached to this volume.
5299 * @param[in] vp volume object pointer
5301 * @pre VOL_LOCK is held
5303 * @post the volume operation info object is detached from the volume object
5305 * @internal volume package internal use only
5308 VDeregisterVolOp_r(Volume * vp)
5310 if (vp->pending_vol_op) {
5311 free(vp->pending_vol_op);
5312 vp->pending_vol_op = NULL;
5316 #endif /* AFS_DEMAND_ATTACH_FS */
5319 * determine whether it is safe to leave a volume online during
5320 * the volume operation described by the vopinfo object.
5322 * @param[in] vp volume object
5323 * @param[in] vopinfo volume operation info object
5325 * @return whether it is safe to leave volume online
5326 * @retval 0 it is NOT SAFE to leave the volume online
5327 * @retval 1 it is safe to leave the volume online during the operation
5330 * @arg VOL_LOCK is held
5331 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5332 * this condition is met)
5334 * @internal volume package internal use only
5337 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5339 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5340 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5341 (vopinfo->com.reason == V_READONLY ||
5342 (!VolumeWriteable(vp) &&
5343 (vopinfo->com.reason == V_CLONE ||
5344 vopinfo->com.reason == V_DUMP)))));
5348 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5351 * @param[in] vp volume object
5352 * @param[in] vopinfo volume operation info object
5354 * @return whether it is safe to leave volume online
5355 * @retval 0 it is NOT SAFE to leave the volume online
5356 * @retval 1 it is safe to leave the volume online during the operation
5357 * @retval -1 unsure; volume header is required in order to know whether or
5358 * not is is safe to leave the volume online
5360 * @pre VOL_LOCK is held
5362 * @internal volume package internal use only
5365 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5367 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5368 * assume that we don't know VolumeWriteable; return -1 if the answer
5369 * depends on VolumeWriteable */
5371 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5374 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5375 vopinfo->com.reason == V_READONLY) {
5379 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5380 (vopinfo->com.reason == V_CLONE ||
5381 vopinfo->com.reason == V_DUMP)) {
5383 /* must know VolumeWriteable */
5390 * determine whether VBUSY should be set during this volume operation.
5392 * @param[in] vp volume object
5393 * @param[in] vopinfo volume operation info object
5395 * @return whether VBUSY should be set
5396 * @retval 0 VBUSY does NOT need to be set
5397 * @retval 1 VBUSY SHOULD be set
5399 * @pre VOL_LOCK is held
5401 * @internal volume package internal use only
5404 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5406 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5407 vopinfo->com.reason == FSYNC_SALVAGE) ||
5408 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5409 (vopinfo->com.reason == V_CLONE ||
5410 vopinfo->com.reason == V_DUMP)));
5414 /***************************************************/
5415 /* online salvager routines */
5416 /***************************************************/
5417 #if defined(AFS_DEMAND_ATTACH_FS)
5420 * offline a volume to let it be salvaged.
5422 * @param[in] vp Volume to offline
5424 * @return whether we offlined the volume successfully
5425 * @retval 0 volume was not offlined
5426 * @retval 1 volume is now offline
5428 * @note This is similar to VCheckOffline, but slightly different. We do not
5429 * deal with vp->goingOffline, and we try to avoid touching the volume
5430 * header except just to set needsSalvaged
5432 * @pre VOL_LOCK held
5433 * @pre vp->nUsers == 0
5434 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5437 VOfflineForSalvage_r(struct Volume *vp)
5441 VCreateReservation_r(vp);
5442 VWaitExclusiveState_r(vp);
5444 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5445 /* Someone's using the volume, or someone got to scheduling the salvage
5446 * before us. I don't think either of these should be possible, as we
5447 * should gain no new heavyweight references while we're trying to
5448 * salvage, but just to be sure... */
5449 VCancelReservation_r(vp);
5453 VChangeState_r(vp, VOL_STATE_OFFLINING);
5457 V_needsSalvaged(vp) = 1;
5458 /* ignore error; updating needsSalvaged is just best effort */
5459 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5461 VCloseVolumeHandles_r(vp);
5463 FreeVolumeHeader(vp);
5465 /* volume has been effectively offlined; we can mark it in the SALVAGING
5466 * state now, which lets FSSYNC give it away */
5467 VChangeState_r(vp, VOL_STATE_SALVAGING);
5469 VCancelReservation_r(vp);
5475 * check whether a salvage needs to be performed on this volume.
5477 * @param[in] vp pointer to volume object
5479 * @return status code
5480 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5481 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5482 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5483 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5484 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5486 * @pre VOL_LOCK is held
5488 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5489 * then a salvage will be requested
5491 * @note this is one of the event handlers called by VCancelReservation_r
5493 * @note the caller must check if the volume needs to be freed after calling
5494 * this; the volume may not have any references or be on any lists after
5495 * we return, and we do not free it
5497 * @see VCancelReservation_r
5499 * @internal volume package internal use only.
5502 VCheckSalvage(Volume * vp)
5504 int ret = VCHECK_SALVAGE_OK;
5506 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5507 if (!vp->salvage.requested) {
5508 return VCHECK_SALVAGE_OK;
5511 return VCHECK_SALVAGE_ASYNC;
5514 /* prevent recursion; some of the code below creates and removes
5515 * lightweight refs, which can call VCheckSalvage */
5516 if (vp->salvage.scheduling) {
5517 return VCHECK_SALVAGE_ASYNC;
5519 vp->salvage.scheduling = 1;
5521 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5522 if (!VOfflineForSalvage_r(vp)) {
5523 vp->salvage.scheduling = 0;
5524 return VCHECK_SALVAGE_FAIL;
5528 if (vp->salvage.requested) {
5529 ret = VScheduleSalvage_r(vp);
5531 vp->salvage.scheduling = 0;
5532 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5537 * request volume salvage.
5539 * @param[out] ec computed client error code
5540 * @param[in] vp volume object pointer
5541 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5542 * @param[in] flags see flags note below
5545 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5546 * not been fully attached
5548 * @pre VOL_LOCK is held.
5550 * @post volume state is changed.
5551 * for fileserver, salvage will be requested once refcount reaches zero.
5553 * @return operation status code
5554 * @retval 0 volume salvage will occur
5555 * @retval 1 volume salvage could not be scheduled
5559 * @note in the fileserver, this call does not synchronously schedule a volume
5560 * salvage. rather, it sets volume state so that when volume refcounts
5561 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5562 * nUsers and nWaiters must be zero.
5564 * @internal volume package internal use only.
5567 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5571 * for DAFS volume utilities that are not supposed to schedule salvages,
5572 * just transition to error state instead
5574 if (!VCanScheduleSalvage()) {
5575 VChangeState_r(vp, VOL_STATE_ERROR);
5580 if (programType != fileServer && !VCanUseFSSYNC()) {
5581 VChangeState_r(vp, VOL_STATE_ERROR);
5586 if (!vp->salvage.requested) {
5587 vp->salvage.requested = 1;
5588 vp->salvage.reason = reason;
5589 vp->stats.last_salvage = FT_ApproxTime();
5591 /* Note that it is not possible for us to reach this point if a
5592 * salvage is already running on this volume (even if the fileserver
5593 * was restarted during the salvage). If a salvage were running, the
5594 * salvager would have write-locked the volume header file, so when
5595 * we tried to lock the volume header, the lock would have failed,
5596 * and we would have failed during attachment prior to calling
5597 * VRequestSalvage. So we know that we can schedule salvages without
5598 * fear of a salvage already running for this volume. */
5600 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5602 /* if we don't need to offline the volume, we can go directly
5603 * to SALVAGING. SALVAGING says the volume is offline and is
5604 * either salvaging or ready to be handed to the salvager.
5605 * SALVAGE_REQ says that we want to salvage the volume, but we
5606 * are waiting for it to go offline first. */
5607 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5608 VChangeState_r(vp, VOL_STATE_SALVAGING);
5610 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5611 if (vp->nUsers == 0) {
5612 /* normally VOfflineForSalvage_r would be called from
5613 * PutVolume et al when nUsers reaches 0, but if
5614 * it's already 0, just do it ourselves, since PutVolume
5615 * isn't going to get called */
5616 VOfflineForSalvage_r(vp);
5619 /* If we are non-fileserver, we're telling the fileserver to
5620 * salvage the vol, so we don't need to give it back separately. */
5621 vp->needsPutBack = 0;
5625 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5627 /* make sure neither VScheduleSalvage_r nor
5628 * VUpdateSalvagePriority_r try to schedule another salvage */
5629 vp->salvage.requested = vp->salvage.scheduled = 0;
5631 VChangeState_r(vp, VOL_STATE_ERROR);
5640 * update salvageserver scheduling priority for a volume.
5642 * @param[in] vp pointer to volume object
5644 * @return operation status
5646 * @retval 1 request denied, or SALVSYNC communications failure
5648 * @pre VOL_LOCK is held.
5650 * @post in-core salvage priority counter is incremented. if at least
5651 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5652 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5653 * to update its priority queue. if no salvage is scheduled,
5654 * this function is a no-op.
5656 * @note DAFS fileserver only
5658 * @note this should be called whenever a VGetVolume fails due to a
5659 * pending salvage request
5661 * @todo should set exclusive state and drop glock around salvsync call
5663 * @internal volume package internal use only.
5666 VUpdateSalvagePriority_r(Volume * vp)
5670 #ifdef SALVSYNC_BUILD_CLIENT
5675 now = FT_ApproxTime();
5677 /* update the salvageserver priority queue occasionally so that
5678 * frequently requested volumes get moved to the head of the queue
5680 if ((vp->salvage.scheduled) &&
5681 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5682 code = SALVSYNC_SalvageVolume(vp->hashid,
5683 VPartitionPath(vp->partition),
5688 vp->stats.last_salvage_req = now;
5689 if (code != SYNC_OK) {
5693 #endif /* SALVSYNC_BUILD_CLIENT */
5698 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5700 /* A couple of little helper functions. These return true if we tried to
5701 * use this mechanism to schedule a salvage, false if we haven't tried.
5702 * If we did try a salvage then the results are contained in code.
5706 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5707 #ifdef SALVSYNC_BUILD_CLIENT
5708 if (VCanUseSALVSYNC()) {
5709 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5710 afs_printable_uint32_lu(vp->hashid), partName);
5712 /* can't use V_id() since there's no guarantee
5713 * we have the disk data header at this point */
5714 *code = SALVSYNC_SalvageVolume(vp->hashid,
5727 try_FSSYNC(Volume *vp, char *partName, int *code) {
5728 #ifdef FSSYNC_BUILD_CLIENT
5729 if (VCanUseFSSYNC()) {
5730 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5731 afs_printable_uint32_lu(vp->hashid), partName);
5734 * If we aren't the fileserver, tell the fileserver the volume
5735 * needs to be salvaged. We could directly tell the
5736 * salvageserver, but the fileserver keeps track of some stats
5737 * related to salvages, and handles some other salvage-related
5738 * complications for us.
5740 *code = FSYNC_VolOp(vp->hashid, partName,
5741 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5744 #endif /* FSSYNC_BUILD_CLIENT */
5749 * schedule a salvage with the salvage server or fileserver.
5751 * @param[in] vp pointer to volume object
5753 * @return operation status
5754 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5755 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5756 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5757 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5758 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5761 * @arg VOL_LOCK is held.
5762 * @arg nUsers and nWaiters should be zero.
5764 * @post salvageserver or fileserver is sent a salvage request
5766 * @note If we are the fileserver, the request will be sent to the salvage
5767 * server over SALVSYNC. If we are not the fileserver, the request will be
5768 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5770 * @note the caller must check if the volume needs to be freed after calling
5771 * this; the volume may not have any references or be on any lists after
5772 * we return, and we do not free it
5776 * @internal volume package internal use only.
5779 VScheduleSalvage_r(Volume * vp)
5781 int ret = VCHECK_SALVAGE_SCHEDULED;
5783 VolState state_save;
5784 VThreadOptions_t * thread_opts;
5787 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5789 if (vp->nWaiters || vp->nUsers) {
5790 return VCHECK_SALVAGE_ASYNC;
5793 /* prevent endless salvage,attach,salvage,attach,... loops */
5794 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5795 return VCHECK_SALVAGE_FAIL;
5799 * don't perform salvsync ops on certain threads
5801 thread_opts = pthread_getspecific(VThread_key);
5802 if (thread_opts == NULL) {
5803 thread_opts = &VThread_defaults;
5805 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5806 return VCHECK_SALVAGE_ASYNC;
5809 if (vp->salvage.scheduled) {
5810 return VCHECK_SALVAGE_SCHEDULED;
5813 VCreateReservation_r(vp);
5814 VWaitExclusiveState_r(vp);
5817 * XXX the scheduling process should really be done asynchronously
5818 * to avoid fssync deadlocks
5820 if (vp->salvage.scheduled) {
5821 ret = VCHECK_SALVAGE_SCHEDULED;
5823 /* if we haven't previously scheduled a salvage, do so now
5825 * set the volume to an exclusive state and drop the lock
5826 * around the SALVSYNC call
5828 strlcpy(partName, vp->partition->name, sizeof(partName));
5829 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5832 opr_Verify(try_SALVSYNC(vp, partName, &code)
5833 || try_FSSYNC(vp, partName, &code));
5836 VChangeState_r(vp, state_save);
5838 if (code == SYNC_OK) {
5839 ret = VCHECK_SALVAGE_SCHEDULED;
5840 vp->salvage.scheduled = 1;
5841 vp->stats.last_salvage_req = FT_ApproxTime();
5842 if (VCanUseSALVSYNC()) {
5843 /* don't record these stats for non-fileservers; let the
5844 * fileserver take care of these */
5845 vp->stats.salvages++;
5846 IncUInt64(&VStats.salvages);
5850 case SYNC_BAD_COMMAND:
5851 case SYNC_COM_ERROR:
5852 ret = VCHECK_SALVAGE_FAIL;
5855 ret = VCHECK_SALVAGE_DENIED;
5856 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5857 "denied\n", afs_printable_uint32_lu(vp->hashid));
5860 ret = VCHECK_SALVAGE_FAIL;
5861 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5862 "failed\n", afs_printable_uint32_lu(vp->hashid));
5865 ret = VCHECK_SALVAGE_FAIL;
5866 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5867 "received unknown protocol error %d\n",
5868 afs_printable_uint32_lu(vp->hashid), code);
5872 if (VCanUseFSSYNC()) {
5873 VChangeState_r(vp, VOL_STATE_ERROR);
5878 /* NB: this is cancelling the reservation we obtained above, but we do
5879 * not call VCancelReservation_r, since that may trigger the vp dtor,
5880 * possibly free'ing the vp. We need to keep the vp around after
5881 * this, as the caller may reference vp without any refs. Instead, it
5882 * is the duty of the caller to inspect 'vp' after we return to see if
5883 * needs to be freed. */
5884 opr_Verify(--vp->nWaiters >= 0);
5887 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5889 #ifdef SALVSYNC_BUILD_CLIENT
5892 * connect to the salvageserver SYNC service.
5894 * @return operation status
5898 * @post connection to salvageserver SYNC service established
5900 * @see VConnectSALV_r
5901 * @see VDisconnectSALV
5902 * @see VReconnectSALV
5909 retVal = VConnectSALV_r();
5915 * connect to the salvageserver SYNC service.
5917 * @return operation status
5921 * @pre VOL_LOCK is held.
5923 * @post connection to salvageserver SYNC service established
5926 * @see VDisconnectSALV_r
5927 * @see VReconnectSALV_r
5928 * @see SALVSYNC_clientInit
5930 * @internal volume package internal use only.
5933 VConnectSALV_r(void)
5935 return SALVSYNC_clientInit();
5939 * disconnect from the salvageserver SYNC service.
5941 * @return operation status
5944 * @pre client should have a live connection to the salvageserver
5946 * @post connection to salvageserver SYNC service destroyed
5948 * @see VDisconnectSALV_r
5950 * @see VReconnectSALV
5953 VDisconnectSALV(void)
5956 VDisconnectSALV_r();
5962 * disconnect from the salvageserver SYNC service.
5964 * @return operation status
5968 * @arg VOL_LOCK is held.
5969 * @arg client should have a live connection to the salvageserver.
5971 * @post connection to salvageserver SYNC service destroyed
5973 * @see VDisconnectSALV
5974 * @see VConnectSALV_r
5975 * @see VReconnectSALV_r
5976 * @see SALVSYNC_clientFinis
5978 * @internal volume package internal use only.
5981 VDisconnectSALV_r(void)
5983 return SALVSYNC_clientFinis();
5987 * disconnect and then re-connect to the salvageserver SYNC service.
5989 * @return operation status
5993 * @pre client should have a live connection to the salvageserver
5995 * @post old connection is dropped, and a new one is established
5998 * @see VDisconnectSALV
5999 * @see VReconnectSALV_r
6002 VReconnectSALV(void)
6006 retVal = VReconnectSALV_r();
6012 * disconnect and then re-connect to the salvageserver SYNC service.
6014 * @return operation status
6019 * @arg VOL_LOCK is held.
6020 * @arg client should have a live connection to the salvageserver.
6022 * @post old connection is dropped, and a new one is established
6024 * @see VConnectSALV_r
6025 * @see VDisconnectSALV
6026 * @see VReconnectSALV
6027 * @see SALVSYNC_clientReconnect
6029 * @internal volume package internal use only.
6032 VReconnectSALV_r(void)
6034 return SALVSYNC_clientReconnect();
6036 #endif /* SALVSYNC_BUILD_CLIENT */
6037 #endif /* AFS_DEMAND_ATTACH_FS */
6040 /***************************************************/
6041 /* FSSYNC routines */
6042 /***************************************************/
6044 /* This must be called by any volume utility which needs to run while the
6045 file server is also running. This is separated from VInitVolumePackage2 so
6046 that a utility can fork--and each of the children can independently
6047 initialize communication with the file server */
6048 #ifdef FSSYNC_BUILD_CLIENT
6050 * connect to the fileserver SYNC service.
6052 * @return operation status
6057 * @arg VInit must equal 2.
6058 * @arg Program Type must not be fileserver or salvager.
6060 * @post connection to fileserver SYNC service established
6063 * @see VDisconnectFS
6064 * @see VChildProcReconnectFS
6071 retVal = VConnectFS_r();
6077 * connect to the fileserver SYNC service.
6079 * @return operation status
6084 * @arg VInit must equal 2.
6085 * @arg Program Type must not be fileserver or salvager.
6086 * @arg VOL_LOCK is held.
6088 * @post connection to fileserver SYNC service established
6091 * @see VDisconnectFS_r
6092 * @see VChildProcReconnectFS_r
6094 * @internal volume package internal use only.
6100 opr_Assert((VInit == 2) &&
6101 (programType != fileServer) &&
6102 (programType != salvager));
6103 rc = FSYNC_clientInit();
6111 * disconnect from the fileserver SYNC service.
6114 * @arg client should have a live connection to the fileserver.
6115 * @arg VOL_LOCK is held.
6116 * @arg Program Type must not be fileserver or salvager.
6118 * @post connection to fileserver SYNC service destroyed
6120 * @see VDisconnectFS
6122 * @see VChildProcReconnectFS_r
6124 * @internal volume package internal use only.
6127 VDisconnectFS_r(void)
6129 opr_Assert((programType != fileServer) &&
6130 (programType != salvager));
6131 FSYNC_clientFinis();
6136 * disconnect from the fileserver SYNC service.
6139 * @arg client should have a live connection to the fileserver.
6140 * @arg Program Type must not be fileserver or salvager.
6142 * @post connection to fileserver SYNC service destroyed
6144 * @see VDisconnectFS_r
6146 * @see VChildProcReconnectFS
6157 * connect to the fileserver SYNC service from a child process following a fork.
6159 * @return operation status
6164 * @arg VOL_LOCK is held.
6165 * @arg current FSYNC handle is shared with a parent process
6167 * @post current FSYNC handle is discarded and a new connection to the
6168 * fileserver SYNC service is established
6170 * @see VChildProcReconnectFS
6172 * @see VDisconnectFS_r
6174 * @internal volume package internal use only.
6177 VChildProcReconnectFS_r(void)
6179 return FSYNC_clientChildProcReconnect();
6183 * connect to the fileserver SYNC service from a child process following a fork.
6185 * @return operation status
6189 * @pre current FSYNC handle is shared with a parent process
6191 * @post current FSYNC handle is discarded and a new connection to the
6192 * fileserver SYNC service is established
6194 * @see VChildProcReconnectFS_r
6196 * @see VDisconnectFS
6199 VChildProcReconnectFS(void)
6203 ret = VChildProcReconnectFS_r();
6207 #endif /* FSSYNC_BUILD_CLIENT */
6210 /***************************************************/
6211 /* volume bitmap routines */
6212 /***************************************************/
6215 * Grow the bitmap by the defined increment
6218 VGrowBitmap(struct vnodeIndex *index)
6222 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6223 osi_Assert(bp != NULL);
6225 bp += index->bitmapSize;
6226 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6227 index->bitmapOffset = index->bitmapSize;
6228 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6234 * allocate a vnode bitmap number for the vnode
6236 * @param[out] ec error code
6237 * @param[in] vp volume object pointer
6238 * @param[in] index vnode index number for the vnode
6239 * @param[in] flags flag values described in note
6241 * @note for DAFS, flags parameter controls locking behavior.
6242 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6243 * will create a reservation and block on any other exclusive
6244 * operations. Otherwise, this function assumes the caller
6245 * already has exclusive access to vp, and we just change the
6248 * @pre VOL_LOCK held
6250 * @return bit number allocated
6256 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6257 struct vnodeIndex *index, int flags)
6261 #ifdef AFS_DEMAND_ATTACH_FS
6262 VolState state_save;
6263 #endif /* AFS_DEMAND_ATTACH_FS */
6267 /* This test is probably redundant */
6268 if (!VolumeWriteable(vp)) {
6269 *ec = (bit32) VREADONLY;
6273 #ifdef AFS_DEMAND_ATTACH_FS
6274 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6275 VCreateReservation_r(vp);
6276 VWaitExclusiveState_r(vp);
6278 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6279 #endif /* AFS_DEMAND_ATTACH_FS */
6282 if ((programType == fileServer) && !index->bitmap) {
6284 #ifndef AFS_DEMAND_ATTACH_FS
6285 /* demand attach fs uses the volume state to avoid races.
6286 * specialStatus field is not used at all */
6288 if (vp->specialStatus == VBUSY) {
6289 if (vp->goingOffline) { /* vos dump waiting for the volume to
6290 * go offline. We probably come here
6291 * from AddNewReadableResidency */
6294 while (vp->specialStatus == VBUSY) {
6295 #ifdef AFS_PTHREAD_ENV
6299 #else /* !AFS_PTHREAD_ENV */
6301 #endif /* !AFS_PTHREAD_ENV */
6305 #endif /* !AFS_DEMAND_ATTACH_FS */
6307 if (!index->bitmap) {
6308 #ifndef AFS_DEMAND_ATTACH_FS
6309 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6310 #endif /* AFS_DEMAND_ATTACH_FS */
6311 for (i = 0; i < nVNODECLASSES; i++) {
6312 VGetBitmap_r(ec, vp, i);
6314 #ifdef AFS_DEMAND_ATTACH_FS
6315 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6316 #else /* AFS_DEMAND_ATTACH_FS */
6317 DeleteVolumeFromHashTable(vp);
6318 vp->shuttingDown = 1; /* Let who has it free it. */
6319 vp->specialStatus = 0;
6320 #endif /* AFS_DEMAND_ATTACH_FS */
6324 #ifndef AFS_DEMAND_ATTACH_FS
6326 vp->specialStatus = 0; /* Allow others to have access. */
6327 #endif /* AFS_DEMAND_ATTACH_FS */
6330 #endif /* BITMAP_LATER */
6332 #ifdef AFS_DEMAND_ATTACH_FS
6334 #endif /* AFS_DEMAND_ATTACH_FS */
6335 bp = index->bitmap + index->bitmapOffset;
6336 ep = index->bitmap + index->bitmapSize;
6338 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6340 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6343 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6345 ret = ((bp - index->bitmap) * 8 + o);
6346 #ifdef AFS_DEMAND_ATTACH_FS
6348 #endif /* AFS_DEMAND_ATTACH_FS */
6351 bp += sizeof(bit32) /* i.e. 4 */ ;
6353 /* No bit map entry--must grow bitmap */
6355 bp = index->bitmap + index->bitmapOffset;
6357 ret = index->bitmapOffset * 8;
6358 #ifdef AFS_DEMAND_ATTACH_FS
6360 #endif /* AFS_DEMAND_ATTACH_FS */
6363 #ifdef AFS_DEMAND_ATTACH_FS
6364 VChangeState_r(vp, state_save);
6365 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6366 VCancelReservation_r(vp);
6368 #endif /* AFS_DEMAND_ATTACH_FS */
6373 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6377 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6383 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6384 unsigned bitNumber, int flags)
6386 unsigned int offset;
6390 #ifdef AFS_DEMAND_ATTACH_FS
6391 if (flags & VOL_FREE_BITMAP_WAIT) {
6392 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6393 * state, so ensure we're not in an exclusive volume state when we update
6395 VCreateReservation_r(vp);
6396 VWaitExclusiveState_r(vp);
6403 #endif /* BITMAP_LATER */
6405 offset = bitNumber >> 3;
6406 if (offset >= index->bitmapSize) {
6410 if (offset < index->bitmapOffset)
6411 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6412 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6415 #ifdef AFS_DEMAND_ATTACH_FS
6416 VCancelReservation_r(vp);
6418 return; /* make the compiler happy for non-DAFS */
6422 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6426 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6430 /* this function will drop the glock internally.
6431 * for old pthread fileservers, this is safe thanks to vbusy.
6433 * for demand attach fs, caller must have already called
6434 * VCreateReservation_r and VWaitExclusiveState_r */
6436 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6438 StreamHandle_t *file;
6439 afs_sfsize_t nVnodes, size;
6440 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6441 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6442 struct VnodeDiskObject *vnode;
6443 unsigned int unique = 0;
6447 #endif /* BITMAP_LATER */
6448 #ifdef AFS_DEMAND_ATTACH_FS
6449 VolState state_save;
6450 #endif /* AFS_DEMAND_ATTACH_FS */
6454 #ifdef AFS_DEMAND_ATTACH_FS
6455 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6456 #endif /* AFS_DEMAND_ATTACH_FS */
6459 fdP = IH_OPEN(vip->handle);
6460 opr_Assert(fdP != NULL);
6461 file = FDH_FDOPEN(fdP, "r");
6462 opr_Assert(file != NULL);
6463 vnode = malloc(vcp->diskSize);
6464 opr_Assert(vnode != NULL);
6465 size = OS_SIZE(fdP->fd_fd);
6466 opr_Assert(size != -1);
6467 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6469 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6470 * a few files can be created in this volume,
6471 * the whole thing is rounded up to nearest 4
6472 * bytes, because the bit map allocator likes
6475 BitMap = (byte *) calloc(1, vip->bitmapSize);
6476 opr_Assert(BitMap != NULL);
6477 #else /* BITMAP_LATER */
6478 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6479 opr_Assert(vip->bitmap != NULL);
6480 vip->bitmapOffset = 0;
6481 #endif /* BITMAP_LATER */
6482 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6484 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6485 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6487 if (vnode->type != vNull) {
6488 if (vnode->vnodeMagic != vcp->magic) {
6489 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6494 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6495 #else /* BITMAP_LATER */
6496 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6497 #endif /* BITMAP_LATER */
6498 if (unique <= vnode->uniquifier)
6499 unique = vnode->uniquifier + 1;
6501 #ifndef AFS_PTHREAD_ENV
6502 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6505 #endif /* !AFS_PTHREAD_ENV */
6508 if (vp->nextVnodeUnique < unique) {
6509 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6512 /* Paranoia, partly justified--I think fclose after fdopen
6513 * doesn't seem to close fd. In any event, the documentation
6514 * doesn't specify, so it's safer to close it twice.
6522 /* There may have been a racing condition with some other thread, both
6523 * creating the bitmaps for this volume. If the other thread was faster
6524 * the pointer to bitmap should already be filled and we can free ours.
6526 if (vip->bitmap == NULL) {
6527 vip->bitmap = BitMap;
6528 vip->bitmapOffset = 0;
6531 #endif /* BITMAP_LATER */
6532 #ifdef AFS_DEMAND_ATTACH_FS
6533 VChangeState_r(vp, state_save);
6534 #endif /* AFS_DEMAND_ATTACH_FS */
6538 /***************************************************/
6539 /* Volume Path and Volume Number utility routines */
6540 /***************************************************/
6543 * find the first occurrence of a volume header file and return the path.
6545 * @param[out] ec outbound error code
6546 * @param[in] volumeId volume id to find
6547 * @param[out] partitionp pointer to disk partition path string
6548 * @param[out] namep pointer to volume header file name string
6550 * @post path to first occurrence of volume header is returned in partitionp
6551 * and namep, or ec is set accordingly.
6553 * @warning this function is NOT re-entrant -- partitionp and namep point to
6554 * static data segments
6556 * @note if a volume utility inadvertently leaves behind a stale volume header
6557 * on a vice partition, it is possible for callers to get the wrong one,
6558 * depending on the order of the disk partition linked list.
6562 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6564 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6565 char path[VMAXPATHLEN];
6567 struct DiskPartition64 *dp;
6570 name[0] = OS_DIRSEPC;
6571 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6572 afs_printable_uint32_lu(volumeId));
6573 for (dp = DiskPartitionList; dp; dp = dp->next) {
6574 struct afs_stat_st status;
6575 strcpy(path, VPartitionPath(dp));
6577 if (afs_stat(path, &status) == 0) {
6578 strcpy(partition, dp->name);
6585 *partitionp = *namep = NULL;
6587 *partitionp = partition;
6593 * extract a volume number from a volume header filename string.
6595 * @param[in] name volume header filename string
6597 * @return volume number
6599 * @note the string must be of the form VFORMAT. the only permissible
6600 * deviation is a leading OS_DIRSEPC character.
6605 VolumeNumber(char *name)
6607 if (*name == OS_DIRSEPC)
6609 return strtoul(name + 1, NULL, 10);
6613 * compute the volume header filename.
6615 * @param[in] volumeId
6617 * @return volume header filename
6619 * @post volume header filename string is constructed
6621 * @warning this function is NOT re-entrant -- the returned string is
6622 * stored in a static char array. see VolumeExternalName_r
6623 * for a re-entrant equivalent.
6625 * @see VolumeExternalName_r
6627 * @deprecated due to the above re-entrancy warning, this interface should
6628 * be considered deprecated. Please use VolumeExternalName_r
6632 VolumeExternalName(VolumeId volumeId)
6634 static char name[VMAXPATHLEN];
6635 snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6640 * compute the volume header filename.
6642 * @param[in] volumeId
6643 * @param[inout] name array in which to store filename
6644 * @param[in] len length of name array
6646 * @return result code from afs_snprintf
6648 * @see VolumeExternalName
6651 * @note re-entrant equivalent of VolumeExternalName
6654 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6656 return snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6660 /***************************************************/
6661 /* Volume Usage Statistics routines */
6662 /***************************************************/
6664 #define OneDay (86400) /* 24 hours' worth of seconds */
6667 Midnight(time_t t) {
6668 struct tm local, *l;
6671 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6672 l = localtime_r(&t, &local);
6678 /* the following is strictly speaking problematic on the
6679 switching day to daylight saving time, after the switch,
6680 as tm_isdst does not match. Similarly, on the looong day when
6681 switching back the OneDay check will not do what naively expected!
6682 The effects are minor, though, and more a matter of interpreting
6684 #ifndef AFS_PTHREAD_ENV
6687 local.tm_hour = local.tm_min=local.tm_sec = 0;
6688 midnight = mktime(&local);
6689 if (midnight != (time_t) -1) return(midnight);
6691 return( (t/OneDay)*OneDay );
6695 /*------------------------------------------------------------------------
6696 * [export] VAdjustVolumeStatistics
6699 * If we've passed midnight, we need to update all the day use
6700 * statistics as well as zeroing the detailed volume statistics
6701 * (if we are implementing them).
6704 * vp : Pointer to the volume structure describing the lucky
6705 * volume being considered for update.
6711 * Nothing interesting.
6715 *------------------------------------------------------------------------*/
6718 VAdjustVolumeStatistics_r(Volume * vp)
6720 unsigned int now = FT_ApproxTime();
6722 if (now - V_dayUseDate(vp) > OneDay) {
6725 ndays = (now - V_dayUseDate(vp)) / OneDay;
6726 for (i = 6; i > ndays - 1; i--)
6727 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6728 for (i = 0; i < ndays - 1 && i < 7; i++)
6729 V_weekUse(vp)[i] = 0;
6731 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6733 V_dayUseDate(vp) = Midnight(now);
6736 * All we need to do is bzero the entire VOL_STATS_BYTES of
6737 * the detailed volume statistics area.
6739 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6742 /*It's been more than a day of collection */
6744 * Always return happily.
6747 } /*VAdjustVolumeStatistics */
6750 VAdjustVolumeStatistics(Volume * vp)
6754 retVal = VAdjustVolumeStatistics_r(vp);
6760 VBumpVolumeUsage_r(Volume * vp)
6762 unsigned int now = FT_ApproxTime();
6763 V_accessDate(vp) = now;
6764 if (now - V_dayUseDate(vp) > OneDay)
6765 VAdjustVolumeStatistics_r(vp);
6767 * Save the volume header image to disk after a threshold of bumps to dayUse,
6768 * at most every usage_rate_limit seconds.
6771 vp->usage_bumps_outstanding++;
6772 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6773 && vp->usage_bumps_next_write <= now) {
6775 vp->usage_bumps_outstanding = 0;
6776 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6777 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6782 VBumpVolumeUsage(Volume * vp)
6785 VBumpVolumeUsage_r(vp);
6790 VSetDiskUsage_r(void)
6792 #ifndef AFS_DEMAND_ATTACH_FS
6793 static int FifteenMinuteCounter = 0;
6797 /* NOTE: Don't attempt to access the partitions list until the
6798 * initialization level indicates that all volumes are attached,
6799 * which implies that all partitions are initialized. */
6800 #ifdef AFS_PTHREAD_ENV
6801 VOL_CV_WAIT(&vol_vinit_cond);
6802 #else /* AFS_PTHREAD_ENV */
6804 #endif /* AFS_PTHREAD_ENV */
6807 VResetDiskUsage_r();
6809 #ifndef AFS_DEMAND_ATTACH_FS
6810 if (++FifteenMinuteCounter == 3) {
6811 FifteenMinuteCounter = 0;
6814 #endif /* !AFS_DEMAND_ATTACH_FS */
6826 /***************************************************/
6827 /* Volume Update List routines */
6828 /***************************************************/
6830 /* The number of minutes that a volume hasn't been updated before the
6831 * "Dont salvage" flag in the volume header will be turned on */
6832 #define SALVAGE_INTERVAL (10*60)
6837 * volume update list functionality has been moved into the VLRU
6838 * the DONT_SALVAGE flag is now set during VLRU demotion
6841 #ifndef AFS_DEMAND_ATTACH_FS
6842 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6843 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6844 static int updateSize = 0; /* number of entries possible */
6845 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6846 #endif /* !AFS_DEMAND_ATTACH_FS */
6849 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6852 vp->updateTime = FT_ApproxTime();
6853 if (V_dontSalvage(vp) == 0)
6855 V_dontSalvage(vp) = 0;
6856 VSyncVolume_r(ec, vp, 0);
6857 #ifdef AFS_DEMAND_ATTACH_FS
6858 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6859 #else /* !AFS_DEMAND_ATTACH_FS */
6862 if (UpdateList == NULL) {
6863 updateSize = UPDATE_LIST_SIZE;
6864 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6866 if (nUpdatedVolumes == updateSize) {
6868 if (updateSize > 524288) {
6869 Log("warning: there is likely a bug in the volume update scanner\n");
6872 UpdateList = realloc(UpdateList,
6873 sizeof(VolumeId) * updateSize);
6876 opr_Assert(UpdateList != NULL);
6877 UpdateList[nUpdatedVolumes++] = V_id(vp);
6878 #endif /* !AFS_DEMAND_ATTACH_FS */
6881 #ifndef AFS_DEMAND_ATTACH_FS
6883 VScanUpdateList(void)
6888 afs_uint32 now = FT_ApproxTime();
6889 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6890 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6892 UpdateList[i - gap] = UpdateList[i];
6894 /* XXX this routine needlessly messes up the Volume LRU by
6895 * breaking the LRU temporal-locality assumptions.....
6896 * we should use a special volume header allocator here */
6897 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6900 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6901 V_dontSalvage(vp) = DONT_SALVAGE;
6902 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6910 #ifndef AFS_PTHREAD_ENV
6912 #endif /* !AFS_PTHREAD_ENV */
6914 nUpdatedVolumes -= gap;
6916 #endif /* !AFS_DEMAND_ATTACH_FS */
6919 /***************************************************/
6920 /* Volume LRU routines */
6921 /***************************************************/
6926 * with demand attach fs, we attempt to soft detach(1)
6927 * volumes which have not been accessed in a long time
6928 * in order to speed up fileserver shutdown
6930 * (1) by soft detach we mean a process very similar
6931 * to VOffline, except the final state of the
6932 * Volume will be VOL_STATE_PREATTACHED, instead
6933 * of the usual VOL_STATE_UNATTACHED
6935 #ifdef AFS_DEMAND_ATTACH_FS
6937 /* implementation is reminiscent of a generational GC
6939 * queue 0 is newly attached volumes. this queue is
6940 * sorted by attach timestamp
6942 * queue 1 is volumes that have been around a bit
6943 * longer than queue 0. this queue is sorted by
6946 * queue 2 is volumes tha have been around the longest.
6947 * this queue is unsorted
6949 * queue 3 is volumes that have been marked as
6950 * candidates for soft detachment. this queue is
6953 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6954 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6957 * definition of a VLRU queue.
6960 volatile struct rx_queue q;
6967 * main VLRU data structure.
6970 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6973 /** time interval (in seconds) between promotion passes for
6974 * each young generation queue. */
6975 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6977 /** time interval (in seconds) between soft detach candidate
6978 * scans for each generation queue.
6980 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6981 * we perform a soft detach pass. */
6982 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6984 /* scheduler state */
6985 int next_idx; /**< next queue to receive attention */
6986 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6987 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6989 int scanner_state; /**< state of scanner thread */
6990 pthread_cond_t cv; /**< state transition CV */
6993 /** global VLRU state */
6994 static struct VLRU volume_LRU;
6997 * defined states for VLRU scanner thread.
7000 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7001 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7002 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7003 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7004 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7005 } vlru_thread_state_t;
7007 /* vlru disk data header stuff */
7008 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7009 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7011 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7012 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7015 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7016 * soft detachment. */
7017 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7019 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7020 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7022 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7023 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7025 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7026 static afs_uint32 VLRU_enabled = 1;
7028 /* queue synchronization routines */
7029 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7030 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7031 static void VLRU_Wait_r(struct VLRU_q * q);
7034 * set VLRU subsystem tunable parameters.
7036 * @param[in] option tunable option to modify
7037 * @param[in] val new value for tunable parameter
7039 * @pre @c VInitVolumePackage2 has not yet been called.
7041 * @post tunable parameter is modified
7045 * @note valid option parameters are:
7046 * @arg @c VLRU_SET_THRESH
7047 * set the period of inactivity after which
7048 * volumes are eligible for soft detachment
7049 * @arg @c VLRU_SET_INTERVAL
7050 * set the time interval between calls
7051 * to the volume LRU "garbage collector"
7052 * @arg @c VLRU_SET_MAX
7053 * set the max number of volumes to deallocate
7057 VLRU_SetOptions(int option, afs_uint32 val)
7059 if (option == VLRU_SET_THRESH) {
7060 VLRU_offline_thresh = val;
7061 } else if (option == VLRU_SET_INTERVAL) {
7062 VLRU_offline_interval = val;
7063 } else if (option == VLRU_SET_MAX) {
7064 VLRU_offline_max = val;
7065 } else if (option == VLRU_SET_ENABLED) {
7068 VLRU_ComputeConstants();
7072 * compute VLRU internal timing parameters.
7074 * @post VLRU scanner thread internal timing parameters are computed
7076 * @note computes internal timing parameters based upon user-modifiable
7077 * tunable parameters.
7081 * @internal volume package internal use only.
7084 VLRU_ComputeConstants(void)
7086 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7088 /* compute the candidate scan interval */
7089 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7091 /* compute the promotion intervals */
7092 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7093 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7096 /* compute the gen 0 scan interval */
7097 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7099 /* compute the gen 0 scan interval */
7100 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7105 * initialize VLRU subsystem.
7107 * @pre this function has not yet been called
7109 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7113 * @internal volume package internal use only.
7119 pthread_attr_t attrs;
7122 if (!VLRU_enabled) {
7123 Log("VLRU: disabled\n");
7127 /* initialize each of the VLRU queues */
7128 for (i = 0; i < VLRU_QUEUES; i++) {
7129 queue_Init(&volume_LRU.q[i]);
7130 volume_LRU.q[i].len = 0;
7131 volume_LRU.q[i].busy = 0;
7132 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7135 /* setup the timing constants */
7136 VLRU_ComputeConstants();
7138 /* XXX put inside LogLevel check? */
7139 Log("VLRU: starting scanner with the following configuration parameters:\n");
7140 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7141 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7142 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7143 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7144 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7145 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7147 /* start up the VLRU scanner */
7148 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7149 if (programType == fileServer) {
7150 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7151 opr_Verify(pthread_attr_init(&attrs) == 0);
7152 opr_Verify(pthread_attr_setdetachstate(&attrs,
7153 PTHREAD_CREATE_DETACHED) == 0);
7154 opr_Verify(pthread_create(&tid, &attrs,
7155 &VLRU_ScannerThread, NULL) == 0);
7160 * initialize the VLRU-related fields of a newly allocated volume object.
7162 * @param[in] vp pointer to volume object
7165 * @arg @c VOL_LOCK is held.
7166 * @arg volume object is not on a VLRU queue.
7168 * @post VLRU fields are initialized to indicate that volume object is not
7169 * currently registered with the VLRU subsystem
7173 * @internal volume package interal use only.
7176 VLRU_Init_Node_r(Volume * vp)
7181 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7182 vp->vlru.idx = VLRU_QUEUE_INVALID;
7186 * add a volume object to a VLRU queue.
7188 * @param[in] vp pointer to volume object
7191 * @arg @c VOL_LOCK is held.
7192 * @arg caller MUST hold a lightweight ref on @p vp.
7193 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7195 * @post the volume object is added to the appropriate VLRU queue
7197 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7198 * then the volume is added to that queue. Otherwise, the value
7199 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7200 * volume is added to the NEW generation queue.
7202 * @note @c VOL_LOCK may be dropped internally
7204 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7205 * during the add operation, and is restored to the previous
7206 * state prior to return.
7210 * @internal volume package internal use only.
7213 VLRU_Add_r(Volume * vp)
7216 VolState state_save;
7221 if (queue_IsOnQueue(&vp->vlru))
7224 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7227 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7228 idx = VLRU_QUEUE_NEW;
7231 VLRU_Wait_r(&volume_LRU.q[idx]);
7233 /* repeat check since VLRU_Wait_r may have dropped
7235 if (queue_IsNotOnQueue(&vp->vlru)) {
7237 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7238 volume_LRU.q[idx].len++;
7239 V_attachFlags(vp) |= VOL_ON_VLRU;
7240 vp->stats.last_promote = FT_ApproxTime();
7243 VChangeState_r(vp, state_save);
7247 * delete a volume object from a VLRU queue.
7249 * @param[in] vp pointer to volume object
7252 * @arg @c VOL_LOCK is held.
7253 * @arg caller MUST hold a lightweight ref on @p vp.
7254 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7256 * @post volume object is removed from the VLRU queue
7258 * @note @c VOL_LOCK may be dropped internally
7262 * @todo We should probably set volume state to something exlcusive
7263 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7265 * @internal volume package internal use only.
7268 VLRU_Delete_r(Volume * vp)
7275 if (queue_IsNotOnQueue(&vp->vlru))
7281 if (idx == VLRU_QUEUE_INVALID)
7283 VLRU_Wait_r(&volume_LRU.q[idx]);
7284 } while (idx != vp->vlru.idx);
7286 /* now remove from the VLRU and update
7287 * the appropriate counter */
7288 queue_Remove(&vp->vlru);
7289 volume_LRU.q[idx].len--;
7290 vp->vlru.idx = VLRU_QUEUE_INVALID;
7291 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7295 * tell the VLRU subsystem that a volume was just accessed.
7297 * @param[in] vp pointer to volume object
7300 * @arg @c VOL_LOCK is held
7301 * @arg caller MUST hold a lightweight ref on @p vp
7302 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7304 * @post volume VLRU access statistics are updated. If the volume was on
7305 * the VLRU soft detach candidate queue, it is moved to the NEW
7308 * @note @c VOL_LOCK may be dropped internally
7312 * @internal volume package internal use only.
7315 VLRU_UpdateAccess_r(Volume * vp)
7317 Volume * rvp = NULL;
7322 if (queue_IsNotOnQueue(&vp->vlru))
7325 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7327 /* update the access timestamp */
7328 vp->stats.last_get = FT_ApproxTime();
7331 * if the volume is on the soft detach candidate
7332 * list, we need to safely move it back to a
7333 * regular generation. this has to be done
7334 * carefully so we don't race against the scanner
7338 /* if this volume is on the soft detach candidate queue,
7339 * then grab exclusive access to the necessary queues */
7340 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7342 VCreateReservation_r(rvp);
7344 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7345 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7346 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7347 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7350 /* make sure multiple threads don't race to update */
7351 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7352 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7356 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7357 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7358 VCancelReservation_r(rvp);
7363 * switch a volume between two VLRU queues.
7365 * @param[in] vp pointer to volume object
7366 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7367 * @param[in] append controls whether the volume will be appended or
7368 * prepended to the queue. A nonzero value means it will
7369 * be appended; zero means it will be prepended.
7371 * @pre The new (and old, if applicable) queue(s) must either be owned
7372 * exclusively by the calling thread for asynchronous manipulation,
7373 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7374 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7375 * for further details of the queue asynchronous processing mechanism.
7377 * @post If the volume object was already on a VLRU queue, it is
7378 * removed from the queue. Depending on the value of the append
7379 * parameter, the volume object is either appended or prepended
7380 * to the VLRU queue referenced by the new_idx parameter.
7384 * @see VLRU_BeginExclusive_r
7385 * @see VLRU_EndExclusive_r
7388 * @internal volume package internal use only.
7391 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7393 if (queue_IsNotOnQueue(&vp->vlru))
7396 queue_Remove(&vp->vlru);
7397 volume_LRU.q[vp->vlru.idx].len--;
7399 /* put the volume back on the correct generational queue */
7401 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7403 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7406 volume_LRU.q[new_idx].len++;
7407 vp->vlru.idx = new_idx;
7411 * VLRU background thread.
7413 * The VLRU Scanner Thread is responsible for periodically scanning through
7414 * each VLRU queue looking for volumes which should be moved to another
7415 * queue, or soft detached.
7417 * @param[in] args unused thread arguments parameter
7419 * @return unused thread return value
7420 * @retval NULL always
7422 * @internal volume package internal use only.
7425 VLRU_ScannerThread(void * args)
7427 afs_uint32 now, min_delay, delay;
7428 int i, min_idx, min_op, overdue, state;
7430 /* set t=0 for promotion cycle to be
7431 * fileserver startup */
7432 now = FT_ApproxTime();
7433 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7434 volume_LRU.last_promotion[i] = now;
7437 /* don't start the scanner until VLRU_offline_thresh
7438 * plus a small delay for VInitVolumePackage2 to finish
7441 sleep(VLRU_offline_thresh + 60);
7443 /* set t=0 for scan cycle to be now */
7444 now = FT_ApproxTime();
7445 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7446 volume_LRU.last_scan[i] = now;
7450 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7451 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7454 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7455 /* check to see if we've been asked to pause */
7456 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7457 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7458 CV_BROADCAST(&volume_LRU.cv);
7460 VOL_CV_WAIT(&volume_LRU.cv);
7461 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7464 /* scheduling can happen outside the glock */
7467 /* figure out what is next on the schedule */
7469 /* figure out a potential schedule for the new generation first */
7471 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7474 if (min_delay > volume_LRU.scan_interval[0]) {
7475 /* unsigned overflow -- we're overdue to run this scan */
7480 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7482 i = VLRU_QUEUE_CANDIDATE;
7483 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7484 if (delay < min_delay) {
7488 if (delay > volume_LRU.scan_interval[i]) {
7489 /* unsigned overflow -- we're overdue to run this scan */
7496 /* if we're still not overdue for something, figure out schedules for promotions */
7497 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7498 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7499 if (delay < min_delay) {
7504 if (delay > volume_LRU.promotion_interval[i]) {
7505 /* unsigned overflow -- we're overdue to run this promotion */
7514 /* sleep as needed */
7519 /* do whatever is next */
7522 VLRU_Promote_r(min_idx);
7523 VLRU_Demote_r(min_idx+1);
7525 VLRU_Scan_r(min_idx);
7527 now = FT_ApproxTime();
7530 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7532 /* signal that scanner is down */
7533 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7534 CV_BROADCAST(&volume_LRU.cv);
7540 * promote volumes from one VLRU generation to the next.
7542 * This routine scans a VLRU generation looking for volumes which are
7543 * eligible to be promoted to the next generation. All volumes which
7544 * meet the eligibility requirement are promoted.
7546 * Promotion eligibility is based upon meeting both of the following
7549 * @arg The volume has been accessed since the last promotion:
7550 * @c (vp->stats.last_get >= vp->stats.last_promote)
7551 * @arg The last promotion occurred at least
7552 * @c volume_LRU.promotion_interval[idx] seconds ago
7554 * As a performance optimization, promotions are "globbed". In other
7555 * words, we promote arbitrarily large contiguous sublists of elements
7558 * @param[in] idx VLRU queue index to scan
7562 * @internal VLRU internal use only.
7565 VLRU_Promote_r(int idx)
7567 int len, chaining, promote;
7568 afs_uint32 now, thresh;
7569 struct rx_queue *qp, *nqp;
7570 Volume * vp, *start = NULL, *end = NULL;
7572 /* get exclusive access to two chains, and drop the glock */
7573 VLRU_Wait_r(&volume_LRU.q[idx]);
7574 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7575 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7576 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7579 thresh = volume_LRU.promotion_interval[idx];
7580 now = FT_ApproxTime();
7583 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7584 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7585 promote = (((vp->stats.last_promote + thresh) <= now) &&
7586 (vp->stats.last_get >= vp->stats.last_promote));
7594 /* promote and prepend chain */
7595 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7609 /* promote and prepend */
7610 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7614 volume_LRU.q[idx].len -= len;
7615 volume_LRU.q[idx+1].len += len;
7618 /* release exclusive access to the two chains */
7620 volume_LRU.last_promotion[idx] = now;
7621 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7622 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7625 /* run the demotions */
7627 VLRU_Demote_r(int idx)
7630 int len, chaining, demote;
7631 afs_uint32 now, thresh;
7632 struct rx_queue *qp, *nqp;
7633 Volume * vp, *start = NULL, *end = NULL;
7634 Volume ** salv_flag_vec = NULL;
7635 int salv_vec_offset = 0;
7637 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7639 /* get exclusive access to two chains, and drop the glock */
7640 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7641 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7642 VLRU_Wait_r(&volume_LRU.q[idx]);
7643 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7646 /* no big deal if this allocation fails */
7647 if (volume_LRU.q[idx].len) {
7648 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7651 now = FT_ApproxTime();
7652 thresh = volume_LRU.promotion_interval[idx-1];
7655 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7656 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7657 demote = (((vp->stats.last_promote + thresh) <= now) &&
7658 (vp->stats.last_get < (now - thresh)));
7660 /* we now do volume update list DONT_SALVAGE flag setting during
7661 * demotion passes */
7662 if (salv_flag_vec &&
7663 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7665 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7666 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7667 salv_flag_vec[salv_vec_offset++] = vp;
7668 VCreateReservation_r(vp);
7677 /* demote and append chain */
7678 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7692 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7696 volume_LRU.q[idx].len -= len;
7697 volume_LRU.q[idx-1].len += len;
7700 /* release exclusive access to the two chains */
7702 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7703 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7705 /* now go back and set the DONT_SALVAGE flags as appropriate */
7706 if (salv_flag_vec) {
7708 for (i = 0; i < salv_vec_offset; i++) {
7709 vp = salv_flag_vec[i];
7710 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7711 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7712 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7715 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7716 V_dontSalvage(vp) = DONT_SALVAGE;
7717 VUpdateVolume_r(&ec, vp, 0);
7721 VCancelReservation_r(vp);
7723 free(salv_flag_vec);
7727 /* run a pass of the VLRU GC scanner */
7729 VLRU_Scan_r(int idx)
7731 afs_uint32 now, thresh;
7732 struct rx_queue *qp, *nqp;
7736 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7738 /* gain exclusive access to the idx VLRU */
7739 VLRU_Wait_r(&volume_LRU.q[idx]);
7740 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7742 if (idx != VLRU_QUEUE_CANDIDATE) {
7743 /* gain exclusive access to the candidate VLRU */
7744 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7745 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7748 now = FT_ApproxTime();
7749 thresh = now - VLRU_offline_thresh;
7751 /* perform candidate selection and soft detaching */
7752 if (idx == VLRU_QUEUE_CANDIDATE) {
7753 /* soft detach some volumes from the candidate pool */
7757 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7758 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7759 if (i >= VLRU_offline_max) {
7762 /* check timestamp to see if it's a candidate for soft detaching */
7763 if (vp->stats.last_get <= thresh) {
7765 if (VCheckSoftDetach(vp, thresh))
7771 /* scan for volumes to become soft detach candidates */
7772 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7773 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7775 /* check timestamp to see if it's a candidate for soft detaching */
7776 if (vp->stats.last_get <= thresh) {
7777 VCheckSoftDetachCandidate(vp, thresh);
7780 if (!(i&0x7f)) { /* lock coarsening optimization */
7788 /* relinquish exclusive access to the VLRU chains */
7792 volume_LRU.last_scan[idx] = now;
7793 if (idx != VLRU_QUEUE_CANDIDATE) {
7794 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7796 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7799 /* check whether volume is safe to soft detach
7800 * caller MUST NOT hold a ref count on vp */
7802 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7806 if (vp->nUsers || vp->nWaiters)
7809 if (vp->stats.last_get <= thresh) {
7810 ret = VSoftDetachVolume_r(vp, thresh);
7816 /* check whether volume should be made a
7817 * soft detach candidate */
7819 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7822 if (vp->nUsers || vp->nWaiters)
7827 opr_Assert(idx == VLRU_QUEUE_NEW);
7829 if (vp->stats.last_get <= thresh) {
7830 /* move to candidate pool */
7831 queue_Remove(&vp->vlru);
7832 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7833 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7834 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7835 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7843 /* begin exclusive access on VLRU */
7845 VLRU_BeginExclusive_r(struct VLRU_q * q)
7847 opr_Assert(q->busy == 0);
7851 /* end exclusive access on VLRU */
7853 VLRU_EndExclusive_r(struct VLRU_q * q)
7855 opr_Assert(q->busy);
7857 CV_BROADCAST(&q->cv);
7860 /* wait for another thread to end exclusive access on VLRU */
7862 VLRU_Wait_r(struct VLRU_q * q)
7865 VOL_CV_WAIT(&q->cv);
7870 * volume soft detach
7872 * caller MUST NOT hold a ref count on vp */
7874 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7879 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7881 ts_save = vp->stats.last_get;
7882 if (ts_save > thresh)
7885 if (vp->nUsers || vp->nWaiters)
7888 if (VIsExclusiveState(V_attachState(vp))) {
7892 switch (V_attachState(vp)) {
7893 case VOL_STATE_UNATTACHED:
7894 case VOL_STATE_PREATTACHED:
7895 case VOL_STATE_ERROR:
7896 case VOL_STATE_GOING_OFFLINE:
7897 case VOL_STATE_SHUTTING_DOWN:
7898 case VOL_STATE_SALVAGING:
7899 case VOL_STATE_DELETED:
7900 volume_LRU.q[vp->vlru.idx].len--;
7902 /* create and cancel a reservation to
7903 * give the volume an opportunity to
7905 VCreateReservation_r(vp);
7906 queue_Remove(&vp->vlru);
7907 vp->vlru.idx = VLRU_QUEUE_INVALID;
7908 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7909 VCancelReservation_r(vp);
7915 /* hold the volume and take it offline.
7916 * no need for reservations, as VHold_r
7917 * takes care of that internally. */
7918 if (VHold_r(vp) == 0) {
7919 /* vhold drops the glock, so now we should
7920 * check to make sure we aren't racing against
7921 * other threads. if we are racing, offlining vp
7922 * would be wasteful, and block the scanner for a while
7926 (vp->shuttingDown) ||
7927 (vp->goingOffline) ||
7928 (vp->stats.last_get != ts_save)) {
7929 /* looks like we're racing someone else. bail */
7933 /* pull it off the VLRU */
7934 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7935 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7936 queue_Remove(&vp->vlru);
7937 vp->vlru.idx = VLRU_QUEUE_INVALID;
7938 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7940 /* take if offline */
7941 VOffline_r(vp, "volume has been soft detached");
7943 /* invalidate the volume header cache */
7944 FreeVolumeHeader(vp);
7947 IncUInt64(&VStats.soft_detaches);
7948 vp->stats.soft_detaches++;
7950 /* put in pre-attached state so demand
7951 * attacher can work on it */
7952 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7958 #endif /* AFS_DEMAND_ATTACH_FS */
7961 /***************************************************/
7962 /* Volume Header Cache routines */
7963 /***************************************************/
7966 * volume header cache.
7968 struct volume_hdr_LRU_t volume_hdr_LRU;
7971 * initialize the volume header cache.
7973 * @param[in] howMany number of header cache entries to preallocate
7975 * @pre VOL_LOCK held. Function has never been called before.
7977 * @post howMany cache entries are allocated, initialized, and added
7978 * to the LRU list. Header cache statistics are initialized.
7980 * @note only applicable to fileServer program type. Should only be
7981 * called once during volume package initialization.
7983 * @internal volume package internal use only.
7986 VInitVolumeHeaderCache(afs_uint32 howMany)
7988 struct volHeader *hp;
7989 if (programType != fileServer)
7991 queue_Init(&volume_hdr_LRU);
7992 volume_hdr_LRU.stats.free = 0;
7993 volume_hdr_LRU.stats.used = howMany;
7994 volume_hdr_LRU.stats.attached = 0;
7995 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7996 opr_Assert(hp != NULL);
7999 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8000 * to ensure they have the right values
8002 ReleaseVolumeHeader(hp++);
8005 /* get a volume header off of the volume header LRU.
8007 * @return volume header
8008 * @retval NULL no usable volume header is available on the LRU
8010 * @pre VOL_LOCK held
8012 * @post for DAFS, if the returned header is associated with a volume, that
8013 * volume is NOT in an exclusive state
8015 * @internal volume package internal use only.
8017 #ifdef AFS_DEMAND_ATTACH_FS
8018 static struct volHeader*
8019 GetVolHeaderFromLRU(void)
8021 struct volHeader *hd = NULL, *qh, *nqh;
8022 /* Usually, a volume in an exclusive state will not have its header on
8023 * the LRU. However, it is possible for this to occur when a salvage
8024 * request is received over FSSYNC, and possibly in other corner cases.
8025 * So just skip over headers whose volumes are in an exclusive state. We
8026 * could VWaitExclusiveState_r instead, but not waiting is faster and
8028 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8029 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8037 #else /* AFS_DEMAND_ATTACH_FS */
8038 static struct volHeader*
8039 GetVolHeaderFromLRU(void)
8041 struct volHeader *hd = NULL;
8042 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8043 hd = queue_First(&volume_hdr_LRU, volHeader);
8048 #endif /* !AFS_DEMAND_ATTACH_FS */
8051 * get a volume header and attach it to the volume object.
8053 * @param[in] vp pointer to volume object
8055 * @return cache entry status
8056 * @retval 0 volume header was newly attached; cache data is invalid
8057 * @retval 1 volume header was previously attached; cache data is valid
8059 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8061 * @post volume header attached to volume object. if necessary, header cache
8062 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8064 * @note VOL_LOCK may be dropped
8066 * @warning this interface does not load header data from disk. it merely
8067 * attaches a header object to the volume object, and may sync the old
8068 * header cache data out to disk in the process.
8070 * @internal volume package internal use only.
8073 GetVolumeHeader(Volume * vp)
8076 struct volHeader *hd;
8078 static int everLogged = 0;
8080 #ifdef AFS_DEMAND_ATTACH_FS
8081 VolState vp_save = 0, back_save = 0;
8083 /* XXX debug 9/19/05 we've apparently got
8084 * a ref counting bug somewhere that's
8085 * breaking the nUsers == 0 => header on LRU
8087 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8088 Log("nUsers == 0, but header not on LRU\n");
8093 old = (vp->header != NULL); /* old == volume already has a header */
8095 if (programType != fileServer) {
8096 /* for volume utilities, we allocate volHeaders as needed */
8098 hd = calloc(1, sizeof(*vp->header));
8099 opr_Assert(hd != NULL);
8102 #ifdef AFS_DEMAND_ATTACH_FS
8103 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8107 /* for the fileserver, we keep a volume header cache */
8109 /* the header we previously dropped in the lru is
8110 * still available. pull it off the lru and return */
8113 opr_Assert(hd->back == vp);
8114 #ifdef AFS_DEMAND_ATTACH_FS
8115 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8118 hd = GetVolHeaderFromLRU();
8120 /* LRU is empty, so allocate a new volHeader
8121 * this is probably indicative of a leak, so let the user know */
8122 hd = calloc(1, sizeof(struct volHeader));
8123 opr_Assert(hd != NULL);
8125 Log("****Allocated more volume headers, probably leak****\n");
8128 volume_hdr_LRU.stats.free++;
8131 /* this header used to belong to someone else.
8132 * we'll need to check if the header needs to
8133 * be sync'd out to disk */
8135 #ifdef AFS_DEMAND_ATTACH_FS
8136 /* GetVolHeaderFromLRU had better not give us back a header
8137 * with a volume in exclusive state... */
8138 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8141 if (hd->diskstuff.inUse) {
8142 /* volume was in use, so we'll need to sync
8143 * its header to disk */
8145 #ifdef AFS_DEMAND_ATTACH_FS
8146 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8147 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8148 VCreateReservation_r(hd->back);
8152 WriteVolumeHeader_r(&error, hd->back);
8153 /* Ignore errors; catch them later */
8155 #ifdef AFS_DEMAND_ATTACH_FS
8160 hd->back->header = NULL;
8161 #ifdef AFS_DEMAND_ATTACH_FS
8162 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8164 if (hd->diskstuff.inUse) {
8165 VChangeState_r(hd->back, back_save);
8166 VCancelReservation_r(hd->back);
8167 VChangeState_r(vp, vp_save);
8171 volume_hdr_LRU.stats.attached++;
8175 #ifdef AFS_DEMAND_ATTACH_FS
8176 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8179 volume_hdr_LRU.stats.free--;
8180 volume_hdr_LRU.stats.used++;
8182 IncUInt64(&VStats.hdr_gets);
8183 #ifdef AFS_DEMAND_ATTACH_FS
8184 IncUInt64(&vp->stats.hdr_gets);
8185 vp->stats.last_hdr_get = FT_ApproxTime();
8192 * make sure volume header is attached and contains valid cache data.
8194 * @param[out] ec outbound error code
8195 * @param[in] vp pointer to volume object
8197 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8199 * @post header cache entry attached, and loaded with valid data, or
8200 * *ec is nonzero, and the header is released back into the LRU.
8202 * @internal volume package internal use only.
8205 LoadVolumeHeader(Error * ec, Volume * vp)
8207 #ifdef AFS_DEMAND_ATTACH_FS
8208 VolState state_save;
8212 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8213 IncUInt64(&VStats.hdr_loads);
8214 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8217 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8218 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8220 IncUInt64(&vp->stats.hdr_loads);
8221 now = FT_ApproxTime();
8225 V_attachFlags(vp) |= VOL_HDR_LOADED;
8226 vp->stats.last_hdr_load = now;
8228 VChangeState_r(vp, state_save);
8230 #else /* AFS_DEMAND_ATTACH_FS */
8232 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8233 IncUInt64(&VStats.hdr_loads);
8235 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8236 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8239 #endif /* AFS_DEMAND_ATTACH_FS */
8241 /* maintain (nUsers==0) => header in LRU invariant */
8242 FreeVolumeHeader(vp);
8247 * release a header cache entry back into the LRU list.
8249 * @param[in] hd pointer to volume header cache object
8251 * @pre VOL_LOCK held.
8253 * @post header cache object appended onto end of LRU list.
8255 * @note only applicable to fileServer program type.
8257 * @note used to place a header cache entry back into the
8258 * LRU pool without invalidating it as a cache entry.
8260 * @internal volume package internal use only.
8263 ReleaseVolumeHeader(struct volHeader *hd)
8265 if (programType != fileServer)
8267 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8269 queue_Append(&volume_hdr_LRU, hd);
8270 #ifdef AFS_DEMAND_ATTACH_FS
8272 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8275 volume_hdr_LRU.stats.free++;
8276 volume_hdr_LRU.stats.used--;
8280 * free/invalidate a volume header cache entry.
8282 * @param[in] vp pointer to volume object
8284 * @pre VOL_LOCK is held.
8286 * @post For fileserver, header cache entry is returned to LRU, and it is
8287 * invalidated as a cache entry. For volume utilities, the header
8288 * cache entry is freed.
8290 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8291 * whenever it is necessary to invalidate the header cache entry.
8293 * @see ReleaseVolumeHeader
8295 * @internal volume package internal use only.
8298 FreeVolumeHeader(Volume * vp)
8300 struct volHeader *hd = vp->header;
8303 if (programType == fileServer) {
8304 ReleaseVolumeHeader(hd);
8309 #ifdef AFS_DEMAND_ATTACH_FS
8310 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8312 volume_hdr_LRU.stats.attached--;
8317 /***************************************************/
8318 /* Volume Hash Table routines */
8319 /***************************************************/
8322 * set size of volume object hash table.
8324 * @param[in] logsize log(2) of desired hash table size
8326 * @return operation status
8328 * @retval -1 failure
8330 * @pre MUST be called prior to VInitVolumePackage2
8332 * @post Volume Hash Table will have 2^logsize buckets
8335 VSetVolHashSize(int logsize)
8337 /* 64 to 268435456 hash buckets seems like a reasonable range */
8338 if ((logsize < 6 ) || (logsize > 28)) {
8343 VolumeHashTable.Size = 1 << logsize;
8344 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8346 /* we can't yet support runtime modification of this
8347 * parameter. we'll need a configuration rwlock to
8348 * make runtime modification feasible.... */
8355 * initialize dynamic data structures for volume hash table.
8357 * @post hash table is allocated, and fields are initialized.
8359 * @internal volume package internal use only.
8362 VInitVolumeHash(void)
8366 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8367 sizeof(VolumeHashChainHead));
8368 opr_Assert(VolumeHashTable.Table != NULL);
8370 for (i=0; i < VolumeHashTable.Size; i++) {
8371 queue_Init(&VolumeHashTable.Table[i]);
8372 #ifdef AFS_DEMAND_ATTACH_FS
8373 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8374 #endif /* AFS_DEMAND_ATTACH_FS */
8379 * add a volume object to the hash table.
8381 * @param[in] vp pointer to volume object
8382 * @param[in] hashid hash of volume id
8384 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8387 * @post volume is added to hash chain.
8389 * @internal volume package internal use only.
8391 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8392 * asynchronous hash chain reordering to finish.
8395 AddVolumeToHashTable(Volume * vp, int hashid)
8397 VolumeHashChainHead * head;
8399 if (queue_IsOnQueue(vp))
8402 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8404 #ifdef AFS_DEMAND_ATTACH_FS
8405 /* wait for the hash chain to become available */
8408 V_attachFlags(vp) |= VOL_IN_HASH;
8409 vp->chainCacheCheck = ++head->cacheCheck;
8410 #endif /* AFS_DEMAND_ATTACH_FS */
8413 vp->hashid = hashid;
8414 queue_Append(head, vp);
8415 vp->vnodeHashOffset = VolumeHashOffset_r();
8419 * delete a volume object from the hash table.
8421 * @param[in] vp pointer to volume object
8423 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8426 * @post volume is removed from hash chain.
8428 * @internal volume package internal use only.
8430 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8431 * asynchronous hash chain reordering to finish.
8434 DeleteVolumeFromHashTable(Volume * vp)
8436 VolumeHashChainHead * head;
8438 if (!queue_IsOnQueue(vp))
8441 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8443 #ifdef AFS_DEMAND_ATTACH_FS
8444 /* wait for the hash chain to become available */
8447 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8449 #endif /* AFS_DEMAND_ATTACH_FS */
8453 /* do NOT reset hashid to zero, as the online
8454 * salvager package may need to know the volume id
8455 * after the volume is removed from the hash */
8459 * lookup a volume object in the hash table given a volume id.
8461 * @param[out] ec error code return
8462 * @param[in] volumeId volume id
8463 * @param[in] hint volume object which we believe could be the correct
8466 * @return volume object pointer
8467 * @retval NULL no such volume id is registered with the hash table.
8469 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8472 * @post volume object with the given id is returned. volume object and
8473 * hash chain access statistics are updated. hash chain may have
8476 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8477 * asynchronous hash chain reordering operation to finish, or
8478 * in order for us to perform an asynchronous chain reordering.
8480 * @note Hash chain reorderings occur when the access count for the
8481 * volume object being looked up exceeds the sum of the previous
8482 * node's (the node ahead of it in the hash chain linked list)
8483 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8485 * @note For DAFS, the hint parameter allows us to short-circuit if the
8486 * cacheCheck fields match between the hash chain head and the
8487 * hint volume object.
8490 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8494 #ifdef AFS_DEMAND_ATTACH_FS
8497 VolumeHashChainHead * head;
8500 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8502 #ifdef AFS_DEMAND_ATTACH_FS
8503 /* wait for the hash chain to become available */
8506 /* check to see if we can short circuit without walking the hash chain */
8507 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8508 IncUInt64(&hint->stats.hash_short_circuits);
8511 #endif /* AFS_DEMAND_ATTACH_FS */
8513 /* someday we need to either do per-chain locks, RWlocks,
8514 * or both for volhash access.
8515 * (and move to a data structure with better cache locality) */
8517 /* search the chain for this volume id */
8518 for(queue_Scan(head, vp, np, Volume)) {
8520 if (vp->hashid == volumeId) {
8525 if (queue_IsEnd(head, vp)) {
8529 #ifdef AFS_DEMAND_ATTACH_FS
8530 /* update hash chain statistics */
8533 FillInt64(lks, 0, looks);
8534 AddUInt64(head->looks, lks, &head->looks);
8535 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8536 IncUInt64(&head->gets);
8541 IncUInt64(&vp->stats.hash_lookups);
8543 /* for demand attach fileserver, we permit occasional hash chain reordering
8544 * so that frequently looked up volumes move towards the head of the chain */
8545 pp = queue_Prev(vp, Volume);
8546 if (!queue_IsEnd(head, pp)) {
8547 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8548 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8549 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8550 VReorderHash_r(head, pp, vp);
8554 /* update the short-circuit cache check */
8555 vp->chainCacheCheck = head->cacheCheck;
8557 #endif /* AFS_DEMAND_ATTACH_FS */
8562 #ifdef AFS_DEMAND_ATTACH_FS
8563 /* perform volume hash chain reordering.
8565 * advance a subchain beginning at vp ahead of
8566 * the adjacent subchain ending at pp */
8568 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8570 Volume *tp, *np, *lp;
8571 afs_uint64 move_thresh;
8573 /* this should never be called if the chain is already busy, so
8574 * no need to wait for other exclusive chain ops to finish */
8576 /* this is a rather heavy set of operations,
8577 * so let's set the chain busy flag and drop
8579 VHashBeginExclusive_r(head);
8582 /* scan forward in the chain from vp looking for the last element
8583 * in the chain we want to advance */
8584 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8585 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8586 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8587 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8591 lp = queue_Prev(tp, Volume);
8593 /* scan backwards from pp to determine where to splice and
8594 * insert the subchain we're advancing */
8595 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8596 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8600 tp = queue_Next(tp, Volume);
8602 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8603 queue_MoveChainBefore(tp,vp,lp);
8606 IncUInt64(&VStats.hash_reorders);
8608 IncUInt64(&head->reorders);
8610 /* wake up any threads waiting for the hash chain */
8611 VHashEndExclusive_r(head);
8615 /* demand-attach fs volume hash
8616 * asynchronous exclusive operations */
8619 * begin an asynchronous exclusive operation on a volume hash chain.
8621 * @param[in] head pointer to volume hash chain head object
8623 * @pre VOL_LOCK held. hash chain is quiescent.
8625 * @post hash chain marked busy.
8627 * @note this interface is used in conjunction with VHashEndExclusive_r and
8628 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8629 * volume hash chain. Its main use case is hash chain reordering, which
8630 * has the potential to be a highly latent operation.
8632 * @see VHashEndExclusive_r
8637 * @internal volume package internal use only.
8640 VHashBeginExclusive_r(VolumeHashChainHead * head)
8642 opr_Assert(head->busy == 0);
8647 * relinquish exclusive ownership of a volume hash chain.
8649 * @param[in] head pointer to volume hash chain head object
8651 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8653 * @post hash chain is marked quiescent. threads awaiting use of
8654 * chain are awakened.
8656 * @see VHashBeginExclusive_r
8661 * @internal volume package internal use only.
8664 VHashEndExclusive_r(VolumeHashChainHead * head)
8666 opr_Assert(head->busy);
8668 CV_BROADCAST(&head->chain_busy_cv);
8672 * wait for all asynchronous operations on a hash chain to complete.
8674 * @param[in] head pointer to volume hash chain head object
8676 * @pre VOL_LOCK held.
8678 * @post hash chain object is quiescent.
8680 * @see VHashBeginExclusive_r
8681 * @see VHashEndExclusive_r
8685 * @note This interface should be called before any attempt to
8686 * traverse the hash chain. It is permissible for a thread
8687 * to gain exclusive access to the chain, and then perform
8688 * latent operations on the chain asynchronously wrt the
8691 * @warning if waiting is necessary, VOL_LOCK is dropped
8693 * @internal volume package internal use only.
8696 VHashWait_r(VolumeHashChainHead * head)
8698 while (head->busy) {
8699 VOL_CV_WAIT(&head->chain_busy_cv);
8702 #endif /* AFS_DEMAND_ATTACH_FS */
8705 /***************************************************/
8706 /* Volume by Partition List routines */
8707 /***************************************************/
8710 * demand attach fileserver adds a
8711 * linked list of volumes to each
8712 * partition object, thus allowing
8713 * for quick enumeration of all
8714 * volumes on a partition
8717 #ifdef AFS_DEMAND_ATTACH_FS
8719 * add a volume to its disk partition VByPList.
8721 * @param[in] vp pointer to volume object
8723 * @pre either the disk partition VByPList is owned exclusively
8724 * by the calling thread, or the list is quiescent and
8727 * @post volume is added to disk partition VByPList
8731 * @warning it is the caller's responsibility to ensure list
8734 * @see VVByPListWait_r
8735 * @see VVByPListBeginExclusive_r
8736 * @see VVByPListEndExclusive_r
8738 * @internal volume package internal use only.
8741 AddVolumeToVByPList_r(Volume * vp)
8743 if (queue_IsNotOnQueue(&vp->vol_list)) {
8744 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8745 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8746 vp->partition->vol_list.len++;
8751 * delete a volume from its disk partition VByPList.
8753 * @param[in] vp pointer to volume object
8755 * @pre either the disk partition VByPList is owned exclusively
8756 * by the calling thread, or the list is quiescent and
8759 * @post volume is removed from the disk partition VByPList
8763 * @warning it is the caller's responsibility to ensure list
8766 * @see VVByPListWait_r
8767 * @see VVByPListBeginExclusive_r
8768 * @see VVByPListEndExclusive_r
8770 * @internal volume package internal use only.
8773 DeleteVolumeFromVByPList_r(Volume * vp)
8775 if (queue_IsOnQueue(&vp->vol_list)) {
8776 queue_Remove(&vp->vol_list);
8777 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8778 vp->partition->vol_list.len--;
8783 * begin an asynchronous exclusive operation on a VByPList.
8785 * @param[in] dp pointer to disk partition object
8787 * @pre VOL_LOCK held. VByPList is quiescent.
8789 * @post VByPList marked busy.
8791 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8792 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8795 * @see VVByPListEndExclusive_r
8796 * @see VVByPListWait_r
8800 * @internal volume package internal use only.
8802 /* take exclusive control over the list */
8804 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8806 opr_Assert(dp->vol_list.busy == 0);
8807 dp->vol_list.busy = 1;
8811 * relinquish exclusive ownership of a VByPList.
8813 * @param[in] dp pointer to disk partition object
8815 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8817 * @post VByPList is marked quiescent. threads awaiting use of
8818 * the list are awakened.
8820 * @see VVByPListBeginExclusive_r
8821 * @see VVByPListWait_r
8825 * @internal volume package internal use only.
8828 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8830 opr_Assert(dp->vol_list.busy);
8831 dp->vol_list.busy = 0;
8832 CV_BROADCAST(&dp->vol_list.cv);
8836 * wait for all asynchronous operations on a VByPList to complete.
8838 * @param[in] dp pointer to disk partition object
8840 * @pre VOL_LOCK is held.
8842 * @post disk partition's VByP list is quiescent
8846 * @note This interface should be called before any attempt to
8847 * traverse the VByPList. It is permissible for a thread
8848 * to gain exclusive access to the list, and then perform
8849 * latent operations on the list asynchronously wrt the
8852 * @warning if waiting is necessary, VOL_LOCK is dropped
8854 * @see VVByPListEndExclusive_r
8855 * @see VVByPListBeginExclusive_r
8857 * @internal volume package internal use only.
8860 VVByPListWait_r(struct DiskPartition64 * dp)
8862 while (dp->vol_list.busy) {
8863 VOL_CV_WAIT(&dp->vol_list.cv);
8866 #endif /* AFS_DEMAND_ATTACH_FS */
8868 /***************************************************/
8869 /* Volume Cache Statistics routines */
8870 /***************************************************/
8873 VPrintCacheStats_r(void)
8875 struct VnodeClassInfo *vcp;
8876 vcp = &VnodeClassInfo[vLarge];
8877 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);
8878 vcp = &VnodeClassInfo[vSmall];
8879 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);
8880 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8881 "%"AFS_INT64_FMT" replacements\n",
8882 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8886 VPrintCacheStats(void)
8889 VPrintCacheStats_r();
8893 #ifdef AFS_DEMAND_ATTACH_FS
8895 UInt64ToDouble(afs_uint64 * x)
8897 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8899 SplitInt64(*x, h, l);
8900 return (((double)h) * c32) + ((double) l);
8904 DoubleToPrintable(double x, char * buf, int len)
8906 static double billion = 1000000000.0;
8909 y[0] = (afs_uint32) (x / (billion * billion));
8910 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8911 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8914 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8916 snprintf(buf, len, "%d%09d", y[1], y[2]);
8918 snprintf(buf, len, "%d", y[2]);
8924 struct VLRUExtStatsEntry {
8928 struct VLRUExtStats {
8934 } queue_info[VLRU_QUEUE_INVALID];
8935 struct VLRUExtStatsEntry * vec;
8939 * add a 256-entry fudge factor onto the vector in case state changes
8940 * out from under us.
8942 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8945 * collect extended statistics for the VLRU subsystem.
8947 * @param[out] stats pointer to stats structure to be populated
8948 * @param[in] nvols number of volumes currently known to exist
8950 * @pre VOL_LOCK held
8952 * @post stats->vec allocated and populated
8954 * @return operation status
8959 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8961 afs_uint32 cur, idx, len;
8962 struct rx_queue * qp, * nqp;
8964 struct VLRUExtStatsEntry * vec;
8966 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8967 vec = stats->vec = calloc(len,
8968 sizeof(struct VLRUExtStatsEntry));
8974 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8975 VLRU_Wait_r(&volume_LRU.q[idx]);
8976 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8979 stats->queue_info[idx].start = cur;
8981 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8983 /* out of space in vec */
8986 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8987 vec[cur].volid = vp->hashid;
8991 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8994 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9002 #define ENUMTOSTRING(en) #en
9003 #define ENUMCASE(en) \
9004 case en: return ENUMTOSTRING(en)
9007 vlru_idx_to_string(int idx)
9010 ENUMCASE(VLRU_QUEUE_NEW);
9011 ENUMCASE(VLRU_QUEUE_MID);
9012 ENUMCASE(VLRU_QUEUE_OLD);
9013 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9014 ENUMCASE(VLRU_QUEUE_HELD);
9015 ENUMCASE(VLRU_QUEUE_INVALID);
9017 return "**UNKNOWN**";
9022 VPrintExtendedCacheStats_r(int flags)
9025 afs_uint32 vol_sum = 0;
9032 struct stats looks, gets, reorders, len;
9033 struct stats ch_looks, ch_gets, ch_reorders;
9035 VolumeHashChainHead *head;
9037 struct VLRUExtStats vlru_stats;
9039 /* zero out stats */
9040 memset(&looks, 0, sizeof(struct stats));
9041 memset(&gets, 0, sizeof(struct stats));
9042 memset(&reorders, 0, sizeof(struct stats));
9043 memset(&len, 0, sizeof(struct stats));
9044 memset(&ch_looks, 0, sizeof(struct stats));
9045 memset(&ch_gets, 0, sizeof(struct stats));
9046 memset(&ch_reorders, 0, sizeof(struct stats));
9048 for (i = 0; i < VolumeHashTable.Size; i++) {
9049 head = &VolumeHashTable.Table[i];
9052 VHashBeginExclusive_r(head);
9055 ch_looks.sum = UInt64ToDouble(&head->looks);
9056 ch_gets.sum = UInt64ToDouble(&head->gets);
9057 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9059 /* update global statistics */
9061 looks.sum += ch_looks.sum;
9062 gets.sum += ch_gets.sum;
9063 reorders.sum += ch_reorders.sum;
9064 len.sum += (double)head->len;
9065 vol_sum += head->len;
9068 len.min = (double) head->len;
9069 len.max = (double) head->len;
9070 looks.min = ch_looks.sum;
9071 looks.max = ch_looks.sum;
9072 gets.min = ch_gets.sum;
9073 gets.max = ch_gets.sum;
9074 reorders.min = ch_reorders.sum;
9075 reorders.max = ch_reorders.sum;
9077 if (((double)head->len) < len.min)
9078 len.min = (double) head->len;
9079 if (((double)head->len) > len.max)
9080 len.max = (double) head->len;
9081 if (ch_looks.sum < looks.min)
9082 looks.min = ch_looks.sum;
9083 else if (ch_looks.sum > looks.max)
9084 looks.max = ch_looks.sum;
9085 if (ch_gets.sum < gets.min)
9086 gets.min = ch_gets.sum;
9087 else if (ch_gets.sum > gets.max)
9088 gets.max = ch_gets.sum;
9089 if (ch_reorders.sum < reorders.min)
9090 reorders.min = ch_reorders.sum;
9091 else if (ch_reorders.sum > reorders.max)
9092 reorders.max = ch_reorders.sum;
9096 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9097 /* compute detailed per-chain stats */
9098 struct stats hdr_loads, hdr_gets;
9099 double v_looks, v_loads, v_gets;
9101 /* initialize stats with data from first element in chain */
9102 vp = queue_First(head, Volume);
9103 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9104 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9105 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9106 ch_gets.min = ch_gets.max = v_looks;
9107 hdr_loads.min = hdr_loads.max = v_loads;
9108 hdr_gets.min = hdr_gets.max = v_gets;
9109 hdr_loads.sum = hdr_gets.sum = 0;
9111 vp = queue_Next(vp, Volume);
9113 /* pull in stats from remaining elements in chain */
9114 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9115 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9116 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9117 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9119 hdr_loads.sum += v_loads;
9120 hdr_gets.sum += v_gets;
9122 if (v_looks < ch_gets.min)
9123 ch_gets.min = v_looks;
9124 else if (v_looks > ch_gets.max)
9125 ch_gets.max = v_looks;
9127 if (v_loads < hdr_loads.min)
9128 hdr_loads.min = v_loads;
9129 else if (v_loads > hdr_loads.max)
9130 hdr_loads.max = v_loads;
9132 if (v_gets < hdr_gets.min)
9133 hdr_gets.min = v_gets;
9134 else if (v_gets > hdr_gets.max)
9135 hdr_gets.max = v_gets;
9138 /* compute per-chain averages */
9139 ch_gets.avg = ch_gets.sum / ((double)head->len);
9140 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9141 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9143 /* dump per-chain stats */
9144 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9146 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9147 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9148 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9149 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9150 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9151 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9152 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9153 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9154 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9155 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9156 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9157 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9158 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9159 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9160 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9161 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9162 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9163 } else if (flags & VOL_STATS_PER_CHAIN) {
9164 /* dump simple per-chain stats */
9165 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9167 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9168 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9169 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9173 VHashEndExclusive_r(head);
9178 /* compute global averages */
9179 len.avg = len.sum / ((double)VolumeHashTable.Size);
9180 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9181 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9182 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9184 /* dump global stats */
9185 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9186 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9187 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9188 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9189 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9190 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9191 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9192 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9193 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9194 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9195 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9196 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9197 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9198 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9199 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9200 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9201 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9202 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9203 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9204 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9205 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9207 /* print extended disk related statistics */
9209 struct DiskPartition64 * diskP;
9210 afs_uint32 vol_count[VOLMAXPARTS+1];
9211 byte part_exists[VOLMAXPARTS+1];
9215 memset(vol_count, 0, sizeof(vol_count));
9216 memset(part_exists, 0, sizeof(part_exists));
9220 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9222 vol_count[id] = diskP->vol_list.len;
9223 part_exists[id] = 1;
9227 for (i = 0; i <= VOLMAXPARTS; i++) {
9228 if (part_exists[i]) {
9229 /* XXX while this is currently safe, it is a violation
9230 * of the VGetPartitionById_r interface contract. */
9231 diskP = VGetPartitionById_r(i, 0);
9233 Log("Partition %s has %d online volumes\n",
9234 VPartitionPath(diskP), diskP->vol_list.len);
9241 /* print extended VLRU statistics */
9242 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9243 afs_uint32 idx, cur, lpos;
9248 Log("VLRU State Dump:\n\n");
9250 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9251 Log("\t%s:\n", vlru_idx_to_string(idx));
9254 for (cur = vlru_stats.queue_info[idx].start;
9255 cur < vlru_stats.queue_info[idx].len;
9257 line[lpos++] = vlru_stats.vec[cur].volid;
9259 Log("\t\t%u, %u, %u, %u, %u,\n",
9260 line[0], line[1], line[2], line[3], line[4]);
9269 Log("\t\t%u, %u, %u, %u, %u\n",
9270 line[0], line[1], line[2], line[3], line[4]);
9275 free(vlru_stats.vec);
9282 VPrintExtendedCacheStats(int flags)
9285 VPrintExtendedCacheStats_r(flags);
9288 #endif /* AFS_DEMAND_ATTACH_FS */
9291 VCanScheduleSalvage(void)
9293 return vol_opts.canScheduleSalvage;
9299 return vol_opts.canUseFSSYNC;
9303 VCanUseSALVSYNC(void)
9305 return vol_opts.canUseSALVSYNC;
9309 VCanUnsafeAttach(void)
9311 return vol_opts.unsafe_attach;