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>
37 #include <rx/rx_queue.h>
40 #if !defined(AFS_SGI_ENV)
43 #else /* AFS_OSF_ENV */
44 #ifdef AFS_VFSINCL_ENV
47 #include <sys/fs/ufs_fs.h>
49 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
50 #include <ufs/ufs/dinode.h>
51 #include <ufs/ffs/fs.h>
56 #else /* AFS_VFSINCL_ENV */
57 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
60 #endif /* AFS_VFSINCL_ENV */
61 #endif /* AFS_OSF_ENV */
62 #endif /* AFS_SGI_ENV */
63 #endif /* !AFS_NT40_ENV */
71 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
73 #include <sys/mnttab.h>
74 #include <sys/mntent.h>
80 #if defined(AFS_SGI_ENV)
83 #ifndef AFS_LINUX20_ENV
84 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
87 #endif /* AFS_SGI_ENV */
89 #endif /* AFS_HPUX_ENV */
93 #include <afs/errors.h>
96 #include <afs/afssyscalls.h>
98 #include <afs/afsutil.h>
99 #include "daemon_com.h"
101 #include "salvsync.h"
104 #include "partition.h"
105 #include "volume_inline.h"
110 #ifdef AFS_PTHREAD_ENV
111 pthread_mutex_t vol_glock_mutex;
112 pthread_mutex_t vol_trans_mutex;
113 pthread_cond_t vol_put_volume_cond;
114 pthread_cond_t vol_sleep_cond;
115 pthread_cond_t vol_init_attach_cond;
116 pthread_cond_t vol_vinit_cond;
117 int vol_attach_threads = 1;
118 #endif /* AFS_PTHREAD_ENV */
120 /* start-time configurable I/O parameters */
121 ih_init_params vol_io_params;
123 #ifdef AFS_DEMAND_ATTACH_FS
124 pthread_mutex_t vol_salvsync_mutex;
127 * Set this to 1 to disallow SALVSYNC communication in all threads; used
128 * during shutdown, since the salvageserver may have gone away.
130 static volatile sig_atomic_t vol_disallow_salvsync = 0;
131 #endif /* AFS_DEMAND_ATTACH_FS */
134 * has VShutdown_r been called / is VShutdown_r running?
136 static int vol_shutting_down = 0;
139 extern void *calloc(), *realloc();
142 /* Forward declarations */
143 static Volume *attach2(Error * ec, VolId volumeId, char *path,
144 struct DiskPartition64 *partp, Volume * vp,
145 int isbusy, int mode, int *acheckedOut);
146 static void ReallyFreeVolume(Volume * vp);
147 #ifdef AFS_DEMAND_ATTACH_FS
148 static void FreeVolume(Volume * vp);
149 #else /* !AFS_DEMAND_ATTACH_FS */
150 #define FreeVolume(vp) ReallyFreeVolume(vp)
151 static void VScanUpdateList(void);
152 #endif /* !AFS_DEMAND_ATTACH_FS */
153 static void VInitVolumeHeaderCache(afs_uint32 howMany);
154 static int GetVolumeHeader(Volume * vp);
155 static void ReleaseVolumeHeader(struct volHeader *hd);
156 static void FreeVolumeHeader(Volume * vp);
157 static void AddVolumeToHashTable(Volume * vp, int hashid);
158 static void DeleteVolumeFromHashTable(Volume * vp);
160 static int VHold(Volume * vp);
162 static int VHold_r(Volume * vp);
163 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
164 static void VReleaseVolumeHandles_r(Volume * vp);
165 static void VCloseVolumeHandles_r(Volume * vp);
166 static void LoadVolumeHeader(Error * ec, Volume * vp);
167 static int VCheckOffline(Volume * vp);
168 static int VCheckDetach(Volume * vp);
169 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
170 Volume * hint, const struct timespec *ts);
172 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
173 * defined when not linked with vice, XXXX */
174 ProgramType programType; /* The type of program using the package */
175 static VolumePackageOptions vol_opts;
177 /* extended volume package statistics */
180 #ifdef VOL_LOCK_DEBUG
181 pthread_t vol_glock_holder = 0;
185 /* this parameter needs to be tunable at runtime.
186 * 128 was really inadequate for largish servers -- at 16384 volumes this
187 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
188 * talk about bad spatial locality...
190 * an AVL or splay tree might work a lot better, but we'll just increase
191 * the default hash table size for now
193 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
194 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
195 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
198 * turn volume hash chains into partially ordered lists.
199 * when the threshold is exceeded between two adjacent elements,
200 * perform a chain rebalancing operation.
202 * keep the threshold high in order to keep cache line invalidates
203 * low "enough" on SMPs
205 #define VOLUME_HASH_REORDER_THRESHOLD 200
208 * when possible, don't just reorder single elements, but reorder
209 * entire chains of elements at once. a chain of elements that
210 * exceed the element previous to the pivot by at least CHAIN_THRESH
211 * accesses are moved in front of the chain whose elements have at
212 * least CHAIN_THRESH less accesses than the pivot element
214 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
216 #include "rx/rx_queue.h"
219 VolumeHashTable_t VolumeHashTable = {
220 DEFAULT_VOLUME_HASH_SIZE,
221 DEFAULT_VOLUME_HASH_MASK,
226 static void VInitVolumeHash(void);
230 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
234 afs_int32 ffs_tmp = x;
238 for (ffs_i = 1;; ffs_i++) {
245 #endif /* !AFS_HAVE_FFS */
247 #ifdef AFS_PTHREAD_ENV
249 * disk partition queue element
251 typedef struct diskpartition_queue_t {
252 struct rx_queue queue; /**< queue header */
253 struct DiskPartition64 *diskP; /**< disk partition table entry */
254 } diskpartition_queue_t;
256 #ifndef AFS_DEMAND_ATTACH_FS
258 typedef struct vinitvolumepackage_thread_t {
259 struct rx_queue queue;
260 pthread_cond_t thread_done_cv;
261 int n_threads_complete;
262 } vinitvolumepackage_thread_t;
263 static void * VInitVolumePackageThread(void * args);
265 #else /* !AFS_DEMAND_ATTTACH_FS */
266 #define VINIT_BATCH_MAX_SIZE 512
269 * disk partition work queue
271 struct partition_queue {
272 struct rx_queue head; /**< diskpartition_queue_t queue */
273 pthread_mutex_t mutex;
278 * volumes parameters for preattach
280 struct volume_init_batch {
281 struct rx_queue queue; /**< queue header */
282 int thread; /**< posting worker thread */
283 int last; /**< indicates thread is done */
284 int size; /**< number of volume ids in batch */
285 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
289 * volume parameters work queue
291 struct volume_init_queue {
292 struct rx_queue head; /**< volume_init_batch queue */
293 pthread_mutex_t mutex;
298 * volume init worker thread parameters
300 struct vinitvolumepackage_thread_param {
301 int nthreads; /**< total number of worker threads */
302 int thread; /**< thread number for this worker thread */
303 struct partition_queue *pq; /**< queue partitions to scan */
304 struct volume_init_queue *vq; /**< queue of volume to preattach */
307 static void *VInitVolumePackageThread(void *args);
308 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
309 static VolId VInitNextVolumeId(DIR *dirp);
310 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
312 #endif /* !AFS_DEMAND_ATTACH_FS */
313 #endif /* AFS_PTHREAD_ENV */
315 #ifndef AFS_DEMAND_ATTACH_FS
316 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
317 int * nAttached, int * nUnattached);
318 #endif /* AFS_DEMAND_ATTACH_FS */
321 #ifdef AFS_DEMAND_ATTACH_FS
322 /* demand attach fileserver extensions */
325 * in the future we will support serialization of VLRU state into the fs_state
328 * these structures are the beginning of that effort
330 struct VLRU_DiskHeader {
331 struct versionStamp stamp; /* magic and structure version number */
332 afs_uint32 mtime; /* time of dump to disk */
333 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
336 struct VLRU_DiskEntry {
337 afs_uint32 vid; /* volume ID */
338 afs_uint32 idx; /* generation */
339 afs_uint32 last_get; /* timestamp of last get */
342 struct VLRU_StartupQueue {
343 struct VLRU_DiskEntry * entry;
348 typedef struct vshutdown_thread_t {
350 pthread_mutex_t lock;
352 pthread_cond_t master_cv;
354 int n_threads_complete;
356 int schedule_version;
359 byte n_parts_done_pass;
360 byte part_thread_target[VOLMAXPARTS+1];
361 byte part_done_pass[VOLMAXPARTS+1];
362 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
363 int stats[4][VOLMAXPARTS+1];
364 } vshutdown_thread_t;
365 static void * VShutdownThread(void * args);
368 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
369 static int VCheckFree(Volume * vp);
372 static void AddVolumeToVByPList_r(Volume * vp);
373 static void DeleteVolumeFromVByPList_r(Volume * vp);
374 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
375 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
376 static void VVByPListWait_r(struct DiskPartition64 * dp);
378 /* online salvager */
380 VCHECK_SALVAGE_OK = 0, /**< no pending salvage */
381 VCHECK_SALVAGE_SCHEDULED = 1, /**< salvage has been scheduled */
382 VCHECK_SALVAGE_ASYNC = 2, /**< salvage being scheduled */
383 VCHECK_SALVAGE_DENIED = 3, /**< salvage not scheduled; denied */
384 VCHECK_SALVAGE_FAIL = 4 /**< salvage not scheduled; failed */
386 static int VCheckSalvage(Volume * vp);
387 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
388 static int VScheduleSalvage_r(Volume * vp);
391 /* Volume hash table */
392 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
393 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
394 static void VHashEndExclusive_r(VolumeHashChainHead * head);
395 static void VHashWait_r(VolumeHashChainHead * head);
398 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
399 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
400 struct rx_queue ** idx);
401 static void ShutdownController(vshutdown_thread_t * params);
402 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
405 static void VLRU_ComputeConstants(void);
406 static void VInitVLRU(void);
407 static void VLRU_Init_Node_r(Volume * vp);
408 static void VLRU_Add_r(Volume * vp);
409 static void VLRU_Delete_r(Volume * vp);
410 static void VLRU_UpdateAccess_r(Volume * vp);
411 static void * VLRU_ScannerThread(void * args);
412 static void VLRU_Scan_r(int idx);
413 static void VLRU_Promote_r(int idx);
414 static void VLRU_Demote_r(int idx);
415 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
418 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
419 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
420 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
423 pthread_key_t VThread_key;
424 VThreadOptions_t VThread_defaults = {
425 0 /**< allow salvsync */
427 #endif /* AFS_DEMAND_ATTACH_FS */
430 struct Lock vol_listLock; /* Lock obtained when listing volumes:
431 * prevents a volume from being missed
432 * if the volume is attached during a
436 /* Common message used when the volume goes off line */
437 char *VSalvageMessage =
438 "Files in this volume are currently unavailable; call operations";
440 int VInit; /* 0 - uninitialized,
441 * 1 - initialized but not all volumes have been attached,
442 * 2 - initialized and all volumes have been attached,
443 * 3 - initialized, all volumes have been attached, and
444 * VConnectFS() has completed. */
446 static int vinit_attach_abort = 0;
448 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
449 * used to stamp volume headers and in-core
450 * vnodes. When the volume goes on-line the
451 * vnode will be invalidated
452 * access only with VOL_LOCK held */
457 /***************************************************/
458 /* Startup routines */
459 /***************************************************/
461 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
462 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
463 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
467 * assign default values to a VolumePackageOptions struct.
469 * Always call this on a VolumePackageOptions struct first, then set any
470 * specific options you want, then call VInitVolumePackage2.
472 * @param[in] pt caller's program type
473 * @param[out] opts volume package options
476 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
478 opts->nLargeVnodes = opts->nSmallVnodes = 5;
481 opts->canScheduleSalvage = 0;
482 opts->canUseFSSYNC = 0;
483 opts->canUseSALVSYNC = 0;
485 opts->interrupt_rxcall = NULL;
486 opts->offline_timeout = -1;
487 opts->offline_shutdown_timeout = -1;
488 opts->usage_threshold = 128;
489 opts->usage_rate_limit = 5;
492 opts->unsafe_attach = 1;
493 #else /* !FAST_RESTART */
494 opts->unsafe_attach = 0;
495 #endif /* !FAST_RESTART */
499 opts->canScheduleSalvage = 1;
500 opts->canUseSALVSYNC = 1;
504 opts->canUseFSSYNC = 1;
508 opts->nLargeVnodes = 0;
509 opts->nSmallVnodes = 0;
511 opts->canScheduleSalvage = 1;
512 opts->canUseFSSYNC = 1;
522 * Set VInit to a certain value, and signal waiters.
524 * @param[in] value the value to set VInit to
529 VSetVInit_r(int value)
532 CV_BROADCAST(&vol_vinit_cond);
536 VLogOfflineTimeout(const char *type, afs_int32 timeout)
542 Log("VInitVolumePackage: Interrupting clients accessing %s "
543 "immediately\n", type);
545 Log("VInitVolumePackage: Interrupting clients accessing %s "
546 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
551 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
553 int errors = 0; /* Number of errors while finding vice partitions. */
558 #ifndef AFS_PTHREAD_ENV
559 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
560 Log("VInitVolumePackage: offline_timeout and/or "
561 "offline_shutdown_timeout was specified, but the volume package "
562 "does not support these for LWP builds\n");
566 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
567 VLogOfflineTimeout("volumes going offline during shutdown",
568 opts->offline_shutdown_timeout);
570 memset(&VStats, 0, sizeof(VStats));
571 VStats.hdr_cache_size = 200;
573 VInitPartitionPackage();
575 #ifdef AFS_DEMAND_ATTACH_FS
576 if (programType == fileServer) {
579 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
581 opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
584 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
585 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
586 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
587 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
588 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
589 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
590 #ifndef AFS_PTHREAD_ENV
592 #endif /* AFS_PTHREAD_ENV */
593 Lock_Init(&vol_listLock);
595 srandom(time(0)); /* For VGetVolumeInfo */
597 #ifdef AFS_DEMAND_ATTACH_FS
598 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
599 #endif /* AFS_DEMAND_ATTACH_FS */
601 /* Ok, we have done enough initialization that fileserver can
602 * start accepting calls, even though the volumes may not be
603 * available just yet.
607 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
608 if (programType == salvageServer) {
611 #endif /* AFS_DEMAND_ATTACH_FS */
612 #ifdef FSSYNC_BUILD_SERVER
613 if (programType == fileServer) {
617 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
618 if (VCanUseSALVSYNC()) {
619 /* establish a connection to the salvager at this point */
620 opr_Verify(VConnectSALV() != 0);
622 #endif /* AFS_DEMAND_ATTACH_FS */
624 if (opts->volcache > VStats.hdr_cache_size)
625 VStats.hdr_cache_size = opts->volcache;
626 VInitVolumeHeaderCache(VStats.hdr_cache_size);
628 VInitVnodes(vLarge, opts->nLargeVnodes);
629 VInitVnodes(vSmall, opts->nSmallVnodes);
632 errors = VAttachPartitions();
636 if (programType != fileServer) {
637 errors = VInitAttachVolumes(programType);
643 #ifdef FSSYNC_BUILD_CLIENT
644 if (VCanUseFSSYNC()) {
646 #ifdef AFS_DEMAND_ATTACH_FS
647 if (programType == salvageServer) {
648 Log("Unable to connect to file server; aborted\n");
651 #endif /* AFS_DEMAND_ATTACH_FS */
652 Log("Unable to connect to file server; will retry at need\n");
655 #endif /* FSSYNC_BUILD_CLIENT */
660 #if !defined(AFS_PTHREAD_ENV)
662 * Attach volumes in vice partitions
664 * @param[in] pt calling program type
667 * @note This is the original, non-threaded version of attach parititions.
669 * @post VInit state is 2
672 VInitAttachVolumes(ProgramType pt)
674 opr_Assert(VInit==1);
675 if (pt == fileServer) {
676 struct DiskPartition64 *diskP;
677 /* Attach all the volumes in this partition */
678 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
679 int nAttached = 0, nUnattached = 0;
680 opr_Verify(VAttachVolumesByPartition(diskP,
681 &nAttached, &nUnattached)
686 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
687 LWP_NoYieldSignal(VInitAttachVolumes);
691 #endif /* !AFS_PTHREAD_ENV */
693 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
695 * Attach volumes in vice partitions
697 * @param[in] pt calling program type
700 * @note Threaded version of attach parititions.
702 * @post VInit state is 2
705 VInitAttachVolumes(ProgramType pt)
707 opr_Assert(VInit==1);
708 if (pt == fileServer) {
709 struct DiskPartition64 *diskP;
710 struct vinitvolumepackage_thread_t params;
711 struct diskpartition_queue_t * dpq;
712 int i, threads, parts;
714 pthread_attr_t attrs;
716 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
718 params.n_threads_complete = 0;
720 /* create partition work queue */
721 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
722 dpq = malloc(sizeof(struct diskpartition_queue_t));
723 opr_Assert(dpq != NULL);
725 queue_Append(¶ms,dpq);
728 threads = min(parts, vol_attach_threads);
731 /* spawn off a bunch of initialization threads */
732 opr_Verify(pthread_attr_init(&attrs) == 0);
733 opr_Verify(pthread_attr_setdetachstate(&attrs,
734 PTHREAD_CREATE_DETACHED)
737 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
738 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
742 for (i=0; i < threads; i++) {
745 opr_Verify(pthread_create(&tid, &attrs,
746 &VInitVolumePackageThread,
748 AFS_SIGSET_RESTORE();
751 while(params.n_threads_complete < threads) {
752 VOL_CV_WAIT(¶ms.thread_done_cv);
756 opr_Verify(pthread_attr_destroy(&attrs) == 0);
758 /* if we're only going to run one init thread, don't bother creating
760 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
761 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
764 VInitVolumePackageThread(¶ms);
767 CV_DESTROY(¶ms.thread_done_cv);
770 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
771 CV_BROADCAST(&vol_init_attach_cond);
777 VInitVolumePackageThread(void * args) {
779 struct DiskPartition64 *diskP;
780 struct vinitvolumepackage_thread_t * params;
781 struct diskpartition_queue_t * dpq;
783 params = (vinitvolumepackage_thread_t *) args;
787 /* Attach all the volumes in this partition */
788 while (queue_IsNotEmpty(params)) {
789 int nAttached = 0, nUnattached = 0;
791 if (vinit_attach_abort) {
792 Log("Aborting initialization\n");
796 dpq = queue_First(params,diskpartition_queue_t);
802 opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
809 params->n_threads_complete++;
810 CV_SIGNAL(¶ms->thread_done_cv);
814 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
816 #if defined(AFS_DEMAND_ATTACH_FS)
818 * Attach volumes in vice partitions
820 * @param[in] pt calling program type
823 * @note Threaded version of attach partitions.
825 * @post VInit state is 2
828 VInitAttachVolumes(ProgramType pt)
830 opr_Assert(VInit==1);
831 if (pt == fileServer) {
833 struct DiskPartition64 *diskP;
834 struct partition_queue pq;
835 struct volume_init_queue vq;
837 int i, threads, parts;
839 pthread_attr_t attrs;
841 /* create partition work queue */
843 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
844 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
845 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
846 struct diskpartition_queue_t *dp;
847 dp = malloc(sizeof(struct diskpartition_queue_t));
848 opr_Assert(dp != NULL);
850 queue_Append(&pq, dp);
853 /* number of worker threads; at least one, not to exceed the number of partitions */
854 threads = min(parts, vol_attach_threads);
856 /* create volume work queue */
858 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
859 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
861 opr_Verify(pthread_attr_init(&attrs) == 0);
862 opr_Verify(pthread_attr_setdetachstate(&attrs,
863 PTHREAD_CREATE_DETACHED) == 0);
865 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
866 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
869 /* create threads to scan disk partitions. */
870 for (i=0; i < threads; i++) {
871 struct vinitvolumepackage_thread_param *params;
874 params = malloc(sizeof(struct vinitvolumepackage_thread_param));
878 params->nthreads = threads;
879 params->thread = i+1;
882 opr_Verify(pthread_create(&tid, &attrs,
883 &VInitVolumePackageThread,
884 (void*)params) == 0);
885 AFS_SIGSET_RESTORE();
888 VInitPreAttachVolumes(threads, &vq);
890 opr_Verify(pthread_attr_destroy(&attrs) == 0);
892 MUTEX_DESTROY(&pq.mutex);
894 MUTEX_DESTROY(&vq.mutex);
898 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
899 CV_BROADCAST(&vol_init_attach_cond);
906 * Volume package initialization worker thread. Scan partitions for volume
907 * header files. Gather batches of volume ids and dispatch them to
908 * the main thread to be preattached. The volume preattachement is done
909 * in the main thread to avoid global volume lock contention.
912 VInitVolumePackageThread(void *args)
914 struct vinitvolumepackage_thread_param *params;
915 struct DiskPartition64 *partition;
916 struct partition_queue *pq;
917 struct volume_init_queue *vq;
918 struct volume_init_batch *vb;
921 params = (struct vinitvolumepackage_thread_param *)args;
927 vb = malloc(sizeof(struct volume_init_batch));
929 vb->thread = params->thread;
933 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
934 while((partition = VInitNextPartition(pq))) {
938 Log("Partition %s: pre-attaching volumes\n", partition->name);
939 dirp = opendir(VPartitionPath(partition));
941 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
944 while ((vid = VInitNextVolumeId(dirp))) {
945 Volume *vp = calloc(1, sizeof(Volume));
947 vp->device = partition->device;
948 vp->partition = partition;
950 queue_Init(&vp->vnode_list);
951 queue_Init(&vp->rx_call_list);
952 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
954 vb->batch[vb->size++] = vp;
955 if (vb->size == VINIT_BATCH_MAX_SIZE) {
956 MUTEX_ENTER(&vq->mutex);
957 queue_Append(vq, vb);
958 CV_BROADCAST(&vq->cv);
959 MUTEX_EXIT(&vq->mutex);
961 vb = malloc(sizeof(struct volume_init_batch));
963 vb->thread = params->thread;
972 MUTEX_ENTER(&vq->mutex);
973 queue_Append(vq, vb);
974 CV_BROADCAST(&vq->cv);
975 MUTEX_EXIT(&vq->mutex);
977 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
983 * Read next element from the pre-populated partition list.
985 static struct DiskPartition64*
986 VInitNextPartition(struct partition_queue *pq)
988 struct DiskPartition64 *partition;
989 struct diskpartition_queue_t *dp; /* queue element */
991 if (vinit_attach_abort) {
992 Log("Aborting volume preattach thread.\n");
996 /* get next partition to scan */
997 MUTEX_ENTER(&pq->mutex);
998 if (queue_IsEmpty(pq)) {
999 MUTEX_EXIT(&pq->mutex);
1002 dp = queue_First(pq, diskpartition_queue_t);
1004 MUTEX_EXIT(&pq->mutex);
1007 opr_Assert(dp->diskP);
1009 partition = dp->diskP;
1015 * Find next volume id on the partition.
1018 VInitNextVolumeId(DIR *dirp)
1024 while((d = readdir(dirp))) {
1025 if (vinit_attach_abort) {
1026 Log("Aborting volume preattach thread.\n");
1029 ext = strrchr(d->d_name, '.');
1030 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1031 vid = VolumeNumber(d->d_name);
1035 Log("Warning: bogus volume header file: %s\n", d->d_name);
1042 * Preattach volumes in batches to avoid lock contention.
1045 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1047 struct volume_init_batch *vb;
1051 /* dequeue next volume */
1052 MUTEX_ENTER(&vq->mutex);
1053 if (queue_IsEmpty(vq)) {
1054 CV_WAIT(&vq->cv, &vq->mutex);
1056 vb = queue_First(vq, volume_init_batch);
1058 MUTEX_EXIT(&vq->mutex);
1062 for (i = 0; i<vb->size; i++) {
1068 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1070 Log("Error looking up volume, code=%d\n", ec);
1073 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1076 /* put pre-attached volume onto the hash table
1077 * and bring it up to the pre-attached state */
1078 AddVolumeToHashTable(vp, vp->hashid);
1079 AddVolumeToVByPList_r(vp);
1080 VLRU_Init_Node_r(vp);
1081 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1094 #endif /* AFS_DEMAND_ATTACH_FS */
1096 #if !defined(AFS_DEMAND_ATTACH_FS)
1098 * attach all volumes on a given disk partition
1101 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1107 Log("Partition %s: attaching volumes\n", diskP->name);
1108 dirp = opendir(VPartitionPath(diskP));
1110 Log("opendir on Partition %s failed!\n", diskP->name);
1114 while ((dp = readdir(dirp))) {
1116 p = strrchr(dp->d_name, '.');
1118 if (vinit_attach_abort) {
1119 Log("Partition %s: abort attach volumes\n", diskP->name);
1123 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1126 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1128 (*(vp ? nAttached : nUnattached))++;
1129 if (error == VOFFLINE)
1130 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1131 else if (LogLevel >= 5) {
1132 Log("Partition %s: attached volume %d (%s)\n",
1133 diskP->name, VolumeNumber(dp->d_name),
1142 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1147 #endif /* !AFS_DEMAND_ATTACH_FS */
1149 /***************************************************/
1150 /* Shutdown routines */
1151 /***************************************************/
1155 * highly multithreaded volume package shutdown
1157 * with the demand attach fileserver extensions,
1158 * VShutdown has been modified to be multithreaded.
1159 * In order to achieve optimal use of many threads,
1160 * the shutdown code involves one control thread and
1161 * n shutdown worker threads. The control thread
1162 * periodically examines the number of volumes available
1163 * for shutdown on each partition, and produces a worker
1164 * thread allocation schedule. The idea is to eliminate
1165 * redundant scheduling computation on the workers by
1166 * having a single master scheduler.
1168 * The scheduler's objectives are:
1170 * each partition with volumes remaining gets allocated
1171 * at least 1 thread (assuming sufficient threads)
1173 * threads are allocated proportional to the number of
1174 * volumes remaining to be offlined. This ensures that
1175 * the OS I/O scheduler has many requests to elevator
1176 * seek on partitions that will (presumably) take the
1177 * longest amount of time (from now) to finish shutdown
1178 * (3) keep threads busy
1179 * when there are extra threads, they are assigned to
1180 * partitions using a simple round-robin algorithm
1182 * In the future, we may wish to add the ability to adapt
1183 * to the relative performance patterns of each disk
1188 * multi-step shutdown process
1190 * demand attach shutdown is a four-step process. Each
1191 * shutdown "pass" shuts down increasingly more difficult
1192 * volumes. The main purpose is to achieve better cache
1193 * utilization during shutdown.
1196 * shutdown volumes in the unattached, pre-attached
1199 * shutdown attached volumes with cached volume headers
1201 * shutdown all volumes in non-exclusive states
1203 * shutdown all remaining volumes
1206 #ifdef AFS_DEMAND_ATTACH_FS
1212 struct DiskPartition64 * diskP;
1213 struct diskpartition_queue_t * dpq;
1214 vshutdown_thread_t params;
1216 pthread_attr_t attrs;
1218 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1221 Log("VShutdown: aborting attach volumes\n");
1222 vinit_attach_abort = 1;
1223 VOL_CV_WAIT(&vol_init_attach_cond);
1226 for (params.n_parts=0, diskP = DiskPartitionList;
1227 diskP; diskP = diskP->next, params.n_parts++);
1229 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1230 params.n_parts, params.n_parts > 1 ? "s" : "");
1232 vol_shutting_down = 1;
1234 if (vol_attach_threads > 1) {
1235 /* prepare for parallel shutdown */
1236 params.n_threads = vol_attach_threads;
1237 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1238 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1239 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1240 opr_Verify(pthread_attr_init(&attrs) == 0);
1241 opr_Verify(pthread_attr_setdetachstate(&attrs,
1242 PTHREAD_CREATE_DETACHED) == 0);
1243 queue_Init(¶ms);
1245 /* setup the basic partition information structures for
1246 * parallel shutdown */
1247 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1249 struct rx_queue * qp, * nqp;
1253 VVByPListWait_r(diskP);
1254 VVByPListBeginExclusive_r(diskP);
1257 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1258 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1262 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1263 VPartitionPath(diskP), count);
1266 /* build up the pass 0 shutdown work queue */
1267 dpq = malloc(sizeof(struct diskpartition_queue_t));
1268 opr_Assert(dpq != NULL);
1270 queue_Prepend(¶ms, dpq);
1272 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1275 Log("VShutdown: beginning parallel fileserver shutdown\n");
1276 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1277 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1279 /* do pass 0 shutdown */
1280 MUTEX_ENTER(¶ms.lock);
1281 for (i=0; i < params.n_threads; i++) {
1282 opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1286 /* wait for all the pass 0 shutdowns to complete */
1287 while (params.n_threads_complete < params.n_threads) {
1288 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1290 params.n_threads_complete = 0;
1292 CV_BROADCAST(¶ms.cv);
1293 MUTEX_EXIT(¶ms.lock);
1295 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1296 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1298 /* run the parallel shutdown scheduler. it will drop the glock internally */
1299 ShutdownController(¶ms);
1301 /* wait for all the workers to finish pass 3 and terminate */
1302 while (params.pass < 4) {
1303 VOL_CV_WAIT(¶ms.cv);
1306 opr_Verify(pthread_attr_destroy(&attrs) == 0);
1307 CV_DESTROY(¶ms.cv);
1308 CV_DESTROY(¶ms.master_cv);
1309 MUTEX_DESTROY(¶ms.lock);
1311 /* drop the VByPList exclusive reservations */
1312 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1313 VVByPListEndExclusive_r(diskP);
1314 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1315 VPartitionPath(diskP),
1316 params.stats[0][diskP->index],
1317 params.stats[1][diskP->index],
1318 params.stats[2][diskP->index],
1319 params.stats[3][diskP->index]);
1322 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1324 /* if we're only going to run one shutdown thread, don't bother creating
1326 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1328 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1329 VShutdownByPartition_r(diskP);
1333 Log("VShutdown: complete.\n");
1336 #else /* AFS_DEMAND_ATTACH_FS */
1346 Log("VShutdown: aborting attach volumes\n");
1347 vinit_attach_abort = 1;
1348 #ifdef AFS_PTHREAD_ENV
1349 VOL_CV_WAIT(&vol_init_attach_cond);
1351 LWP_WaitProcess(VInitAttachVolumes);
1352 #endif /* AFS_PTHREAD_ENV */
1355 Log("VShutdown: shutting down on-line volumes...\n");
1356 vol_shutting_down = 1;
1357 for (i = 0; i < VolumeHashTable.Size; i++) {
1358 /* try to hold first volume in the hash table */
1359 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1363 Log("VShutdown: Attempting to take volume %u offline.\n",
1366 /* next, take the volume offline (drops reference count) */
1367 VOffline_r(vp, "File server was shut down");
1371 Log("VShutdown: complete.\n");
1373 #endif /* AFS_DEMAND_ATTACH_FS */
1379 opr_Assert(VInit>0);
1386 * stop new activity (e.g. SALVSYNC) from occurring
1388 * Use this to make the volume package less busy; for example, during
1389 * shutdown. This doesn't actually shutdown/detach anything in the
1390 * volume package, but prevents certain processes from ocurring. For
1391 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1392 * could also use this to prevent new volume attachment, or prevent
1393 * other programs from checking out volumes, etc.
1398 #ifdef AFS_DEMAND_ATTACH_FS
1399 /* make sure we don't try to contact the salvageserver, since it may
1400 * not be around anymore */
1401 vol_disallow_salvsync = 1;
1405 #ifdef AFS_DEMAND_ATTACH_FS
1408 * shutdown control thread
1411 ShutdownController(vshutdown_thread_t * params)
1414 struct DiskPartition64 * diskP;
1416 vshutdown_thread_t shadow;
1418 ShutdownCreateSchedule(params);
1420 while ((params->pass < 4) &&
1421 (params->n_threads_complete < params->n_threads)) {
1422 /* recompute schedule once per second */
1424 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1428 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1429 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1430 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1431 shadow.n_threads_complete, shadow.n_parts_done_pass);
1432 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1434 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1436 diskP->vol_list.len,
1437 shadow.part_thread_target[id],
1438 shadow.part_done_pass[id],
1439 shadow.part_pass_head[id]);
1445 ShutdownCreateSchedule(params);
1449 /* create the shutdown thread work schedule.
1450 * this scheduler tries to implement fairness
1451 * by allocating at least 1 thread to each
1452 * partition with volumes to be shutdown,
1453 * and then it attempts to allocate remaining
1454 * threads based upon the amount of work left
1457 ShutdownCreateSchedule(vshutdown_thread_t * params)
1459 struct DiskPartition64 * diskP;
1460 int sum, thr_workload, thr_left;
1461 int part_residue[VOLMAXPARTS+1];
1464 /* compute the total number of outstanding volumes */
1466 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1467 sum += diskP->vol_list.len;
1470 params->schedule_version++;
1471 params->vol_remaining = sum;
1476 /* compute average per-thread workload */
1477 thr_workload = sum / params->n_threads;
1478 if (sum % params->n_threads)
1481 thr_left = params->n_threads;
1482 memset(&part_residue, 0, sizeof(part_residue));
1484 /* for fairness, give every partition with volumes remaining
1485 * at least one thread */
1486 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1488 if (diskP->vol_list.len) {
1489 params->part_thread_target[id] = 1;
1492 params->part_thread_target[id] = 0;
1496 if (thr_left && thr_workload) {
1497 /* compute length-weighted workloads */
1500 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1502 delta = (diskP->vol_list.len / thr_workload) -
1503 params->part_thread_target[id];
1507 if (delta < thr_left) {
1508 params->part_thread_target[id] += delta;
1511 params->part_thread_target[id] += thr_left;
1519 /* try to assign any leftover threads to partitions that
1520 * had volume lengths closer to needing thread_target+1 */
1521 int max_residue, max_id = 0;
1523 /* compute the residues */
1524 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1526 part_residue[id] = diskP->vol_list.len -
1527 (params->part_thread_target[id] * thr_workload);
1530 /* now try to allocate remaining threads to partitions with the
1531 * highest residues */
1534 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1536 if (part_residue[id] > max_residue) {
1537 max_residue = part_residue[id];
1546 params->part_thread_target[max_id]++;
1548 part_residue[max_id] = 0;
1553 /* punt and give any remaining threads equally to each partition */
1555 if (thr_left >= params->n_parts) {
1556 alloc = thr_left / params->n_parts;
1557 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1559 params->part_thread_target[id] += alloc;
1564 /* finish off the last of the threads */
1565 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1567 params->part_thread_target[id]++;
1573 /* worker thread for parallel shutdown */
1575 VShutdownThread(void * args)
1577 vshutdown_thread_t * params;
1578 int found, pass, schedule_version_save, count;
1579 struct DiskPartition64 *diskP;
1580 struct diskpartition_queue_t * dpq;
1583 params = (vshutdown_thread_t *) args;
1585 /* acquire the shutdown pass 0 lock */
1586 MUTEX_ENTER(¶ms->lock);
1588 /* if there's still pass 0 work to be done,
1589 * get a work entry, and do a pass 0 shutdown */
1590 if (queue_IsNotEmpty(params)) {
1591 dpq = queue_First(params, diskpartition_queue_t);
1593 MUTEX_EXIT(¶ms->lock);
1599 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1601 params->stats[0][diskP->index] = count;
1602 MUTEX_ENTER(¶ms->lock);
1605 params->n_threads_complete++;
1606 if (params->n_threads_complete == params->n_threads) {
1607 /* notify control thread that all workers have completed pass 0 */
1608 CV_SIGNAL(¶ms->master_cv);
1610 while (params->pass == 0) {
1611 CV_WAIT(¶ms->cv, ¶ms->lock);
1615 MUTEX_EXIT(¶ms->lock);
1618 pass = params->pass;
1619 opr_Assert(pass > 0);
1621 /* now escalate through the more complicated shutdowns */
1623 schedule_version_save = params->schedule_version;
1625 /* find a disk partition to work on */
1626 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1628 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1629 params->part_thread_target[id]--;
1636 /* hmm. for some reason the controller thread couldn't find anything for
1637 * us to do. let's see if there's anything we can do */
1638 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1640 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1643 } else if (!params->part_done_pass[id]) {
1644 params->part_done_pass[id] = 1;
1645 params->n_parts_done_pass++;
1647 Log("VShutdown: done shutting down volumes on partition %s.\n",
1648 VPartitionPath(diskP));
1654 /* do work on this partition until either the controller
1655 * creates a new schedule, or we run out of things to do
1656 * on this partition */
1659 while (!params->part_done_pass[id] &&
1660 (schedule_version_save == params->schedule_version)) {
1661 /* ShutdownVolumeWalk_r will drop the glock internally */
1662 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1663 if (!params->part_done_pass[id]) {
1664 params->part_done_pass[id] = 1;
1665 params->n_parts_done_pass++;
1667 Log("VShutdown: done shutting down volumes on partition %s.\n",
1668 VPartitionPath(diskP));
1676 params->stats[pass][id] += count;
1678 /* ok, everyone is done this pass, proceed */
1681 params->n_threads_complete++;
1682 while (params->pass == pass) {
1683 if (params->n_threads_complete == params->n_threads) {
1684 /* we are the last thread to complete, so we will
1685 * reinitialize worker pool state for the next pass */
1686 params->n_threads_complete = 0;
1687 params->n_parts_done_pass = 0;
1689 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1691 params->part_done_pass[id] = 0;
1692 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1695 /* compute a new thread schedule before releasing all the workers */
1696 ShutdownCreateSchedule(params);
1698 /* wake up all the workers */
1699 CV_BROADCAST(¶ms->cv);
1702 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1703 pass, params->n_threads, params->n_parts);
1706 VOL_CV_WAIT(¶ms->cv);
1709 pass = params->pass;
1723 /* shut down all volumes on a given disk partition
1725 * note that this function will not allow mp-fast
1726 * shutdown of a partition */
1728 VShutdownByPartition_r(struct DiskPartition64 * dp)
1734 /* wait for other exclusive ops to finish */
1735 VVByPListWait_r(dp);
1737 /* begin exclusive access */
1738 VVByPListBeginExclusive_r(dp);
1740 /* pick the low-hanging fruit first,
1741 * then do the complicated ones last
1742 * (has the advantage of keeping
1743 * in-use volumes up until the bitter end) */
1744 for (pass = 0, total=0; pass < 4; pass++) {
1745 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1746 total += pass_stats[pass];
1749 /* end exclusive access */
1750 VVByPListEndExclusive_r(dp);
1752 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1753 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1758 /* internal shutdown functionality
1760 * for multi-pass shutdown:
1761 * 0 to only "shutdown" {pre,un}attached and error state volumes
1762 * 1 to also shutdown attached volumes w/ volume header loaded
1763 * 2 to also shutdown attached volumes w/o volume header loaded
1764 * 3 to also shutdown exclusive state volumes
1766 * caller MUST hold exclusive access on the hash chain
1767 * because we drop vol_glock_mutex internally
1769 * this function is reentrant for passes 1--3
1770 * (e.g. multiple threads can cooperate to
1771 * shutdown a partition mp-fast)
1773 * pass 0 is not scaleable because the volume state data is
1774 * synchronized by vol_glock mutex, and the locking overhead
1775 * is too high to drop the lock long enough to do linked list
1779 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1781 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1784 while (ShutdownVolumeWalk_r(dp, pass, &q))
1790 /* conditionally shutdown one volume on partition dp
1791 * returns 1 if a volume was shutdown in this pass,
1794 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1795 struct rx_queue ** idx)
1797 struct rx_queue *qp, *nqp;
1802 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1803 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1807 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1808 (V_attachState(vp) != VOL_STATE_ERROR) &&
1809 (V_attachState(vp) != VOL_STATE_DELETED) &&
1810 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1814 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1815 (vp->header == NULL)) {
1819 if (VIsExclusiveState(V_attachState(vp))) {
1824 DeleteVolumeFromVByPList_r(vp);
1825 VShutdownVolume_r(vp);
1835 * shutdown a specific volume
1837 /* caller MUST NOT hold a heavyweight ref on vp */
1839 VShutdownVolume_r(Volume * vp)
1843 VCreateReservation_r(vp);
1845 if (LogLevel >= 5) {
1846 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1847 vp->hashid, vp->partition->device, V_attachState(vp));
1850 /* wait for other blocking ops to finish */
1851 VWaitExclusiveState_r(vp);
1853 opr_Assert(VIsValidState(V_attachState(vp)));
1855 switch(V_attachState(vp)) {
1856 case VOL_STATE_SALVAGING:
1857 /* Leave salvaging volumes alone. Any in-progress salvages will
1858 * continue working after viced shuts down. This is intentional.
1861 case VOL_STATE_PREATTACHED:
1862 case VOL_STATE_ERROR:
1863 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1864 case VOL_STATE_UNATTACHED:
1865 case VOL_STATE_DELETED:
1867 case VOL_STATE_GOING_OFFLINE:
1868 case VOL_STATE_SHUTTING_DOWN:
1869 case VOL_STATE_ATTACHED:
1873 Log("VShutdown: Attempting to take volume %u offline.\n",
1876 /* take the volume offline (drops reference count) */
1877 VOffline_r(vp, "File server was shut down");
1884 VCancelReservation_r(vp);
1888 #endif /* AFS_DEMAND_ATTACH_FS */
1891 /***************************************************/
1892 /* Header I/O routines */
1893 /***************************************************/
1896 HeaderName(bit32 magic)
1899 case VOLUMEINFOMAGIC:
1900 return "volume info";
1901 case SMALLINDEXMAGIC:
1902 return "small index";
1903 case LARGEINDEXMAGIC:
1904 return "large index";
1905 case LINKTABLEMAGIC:
1906 return "link table";
1911 /* open a descriptor for the inode (h),
1912 * read in an on-disk structure into buffer (to) of size (size),
1913 * verify versionstamp in structure has magic (magic) and
1914 * optionally verify version (version) if (version) is nonzero
1917 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1920 struct versionStamp *vsn;
1922 afs_sfsize_t nbytes;
1927 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1935 Log("ReadHeader: Failed to open %s header file "
1936 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1937 PrintInode(stmp, h->ih_ino), errno);
1942 vsn = (struct versionStamp *)to;
1943 nbytes = FDH_PREAD(fdP, to, size, 0);
1945 Log("ReadHeader: Failed to read %s header file "
1946 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1947 PrintInode(stmp, h->ih_ino), errno);
1949 FDH_REALLYCLOSE(fdP);
1952 if (nbytes != size) {
1953 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1954 "(volume=%u, inode=%s); expected=%d, read=%d\n",
1955 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), size,
1958 FDH_REALLYCLOSE(fdP);
1961 if (vsn->magic != magic) {
1962 Log("ReadHeader: Incorrect magic for %s header file "
1963 "(volume=%u, inode=%s); expected=0x%x, read=0x%x\n",
1964 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), magic,
1967 FDH_REALLYCLOSE(fdP);
1973 /* Check is conditional, in case caller wants to inspect version himself */
1974 if (version && vsn->version != version) {
1975 Log("ReadHeader: Incorrect version for %s header file "
1976 "(volume=%u, inode=%s); expected=%x, read=%x\n",
1977 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino),
1978 version, vsn->version);
1984 WriteVolumeHeader_r(Error * ec, Volume * vp)
1986 IHandle_t *h = V_diskDataHandle(vp);
1996 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1997 != sizeof(V_disk(vp))) {
1999 FDH_REALLYCLOSE(fdP);
2005 /* VolumeHeaderToDisk
2006 * Allows for storing 64 bit inode numbers in on-disk volume header
2009 /* convert in-memory representation of a volume header to the
2010 * on-disk representation of a volume header */
2012 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2015 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2016 dh->stamp = h->stamp;
2018 dh->parent = h->parent;
2020 #ifdef AFS_64BIT_IOPS_ENV
2021 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2022 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2023 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2024 dh->smallVnodeIndex_hi =
2025 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2026 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2027 dh->largeVnodeIndex_hi =
2028 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2029 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2030 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2032 dh->volumeInfo_lo = h->volumeInfo;
2033 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2034 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2035 dh->linkTable_lo = h->linkTable;
2039 /* DiskToVolumeHeader
2040 * Converts an on-disk representation of a volume header to
2041 * the in-memory representation of a volume header.
2043 * Makes the assumption that AFS has *always*
2044 * zero'd the volume header file so that high parts of inode
2045 * numbers are 0 in older (SGI EFS) volume header files.
2048 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2050 memset(h, 0, sizeof(VolumeHeader_t));
2051 h->stamp = dh->stamp;
2053 h->parent = dh->parent;
2055 #ifdef AFS_64BIT_IOPS_ENV
2057 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2059 h->smallVnodeIndex =
2060 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2061 smallVnodeIndex_hi << 32);
2063 h->largeVnodeIndex =
2064 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2065 largeVnodeIndex_hi << 32);
2067 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2069 h->volumeInfo = dh->volumeInfo_lo;
2070 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2071 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2072 h->linkTable = dh->linkTable_lo;
2077 /***************************************************/
2078 /* Volume Attachment routines */
2079 /***************************************************/
2081 #ifdef AFS_DEMAND_ATTACH_FS
2083 * pre-attach a volume given its path.
2085 * @param[out] ec outbound error code
2086 * @param[in] partition partition path string
2087 * @param[in] name volume id string
2089 * @return volume object pointer
2091 * @note A pre-attached volume will only have its partition
2092 * and hashid fields initialized. At first call to
2093 * VGetVolume, the volume will be fully attached.
2097 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2101 vp = VPreAttachVolumeByName_r(ec, partition, name);
2107 * pre-attach a volume given its path.
2109 * @param[out] ec outbound error code
2110 * @param[in] partition path to vice partition
2111 * @param[in] name volume id string
2113 * @return volume object pointer
2115 * @pre VOL_LOCK held
2117 * @internal volume package internal use only.
2120 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2122 return VPreAttachVolumeById_r(ec,
2124 VolumeNumber(name));
2128 * pre-attach a volume given its path and numeric volume id.
2130 * @param[out] ec error code return
2131 * @param[in] partition path to vice partition
2132 * @param[in] volumeId numeric volume id
2134 * @return volume object pointer
2136 * @pre VOL_LOCK held
2138 * @internal volume package internal use only.
2141 VPreAttachVolumeById_r(Error * ec,
2146 struct DiskPartition64 *partp;
2150 opr_Assert(programType == fileServer);
2152 if (!(partp = VGetPartition_r(partition, 0))) {
2154 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2158 vp = VLookupVolume_r(ec, volumeId, NULL);
2163 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2167 * preattach a volume.
2169 * @param[out] ec outbound error code
2170 * @param[in] partp pointer to partition object
2171 * @param[in] vp pointer to volume object
2172 * @param[in] vid volume id
2174 * @return volume object pointer
2176 * @pre VOL_LOCK is held.
2178 * @warning Returned volume object pointer does not have to
2179 * equal the pointer passed in as argument vp. There
2180 * are potential race conditions which can result in
2181 * the pointers having different values. It is up to
2182 * the caller to make sure that references are handled
2183 * properly in this case.
2185 * @note If there is already a volume object registered with
2186 * the same volume id, its pointer MUST be passed as
2187 * argument vp. Failure to do so will result in a silent
2188 * failure to preattach.
2190 * @internal volume package internal use only.
2193 VPreAttachVolumeByVp_r(Error * ec,
2194 struct DiskPartition64 * partp,
2202 /* check to see if pre-attach already happened */
2204 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2205 (V_attachState(vp) != VOL_STATE_DELETED) &&
2206 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2207 !VIsErrorState(V_attachState(vp))) {
2209 * pre-attach is a no-op in all but the following cases:
2211 * - volume is unattached
2212 * - volume is in an error state
2213 * - volume is pre-attached
2215 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state (state %u flags 0x%x)\n",
2216 vid, V_attachState(vp), V_attachFlags(vp));
2219 /* we're re-attaching a volume; clear out some old state */
2220 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2222 if (V_partition(vp) != partp) {
2223 /* XXX potential race */
2224 DeleteVolumeFromVByPList_r(vp);
2227 /* if we need to allocate a new Volume struct,
2228 * go ahead and drop the vol glock, otherwise
2229 * do the basic setup synchronised, as it's
2230 * probably not worth dropping the lock */
2233 /* allocate the volume structure */
2234 vp = nvp = calloc(1, sizeof(Volume));
2235 opr_Assert(vp != NULL);
2236 queue_Init(&vp->vnode_list);
2237 queue_Init(&vp->rx_call_list);
2238 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2241 /* link the volume with its associated vice partition */
2242 vp->device = partp->device;
2243 vp->partition = partp;
2246 vp->specialStatus = 0;
2248 /* if we dropped the lock, reacquire the lock,
2249 * check for pre-attach races, and then add
2250 * the volume to the hash table */
2253 nvp = VLookupVolume_r(ec, vid, NULL);
2258 } else if (nvp) { /* race detected */
2263 /* hack to make up for VChangeState_r() decrementing
2264 * the old state counter */
2265 VStats.state_levels[0]++;
2269 /* put pre-attached volume onto the hash table
2270 * and bring it up to the pre-attached state */
2271 AddVolumeToHashTable(vp, vp->hashid);
2272 AddVolumeToVByPList_r(vp);
2273 VLRU_Init_Node_r(vp);
2274 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2277 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2285 #endif /* AFS_DEMAND_ATTACH_FS */
2287 /* Attach an existing volume, given its pathname, and return a
2288 pointer to the volume header information. The volume also
2289 normally goes online at this time. An offline volume
2290 must be reattached to make it go online */
2292 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2296 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2302 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2305 struct DiskPartition64 *partp;
2310 #ifdef AFS_DEMAND_ATTACH_FS
2311 VolumeStats stats_save;
2313 #endif /* AFS_DEMAND_ATTACH_FS */
2317 volumeId = VolumeNumber(name);
2319 if (!(partp = VGetPartition_r(partition, 0))) {
2321 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2325 if (VRequiresPartLock()) {
2326 opr_Assert(VInit == 3);
2327 VLockPartition_r(partition);
2328 } else if (programType == fileServer) {
2329 #ifdef AFS_DEMAND_ATTACH_FS
2330 /* lookup the volume in the hash table */
2331 vp = VLookupVolume_r(ec, volumeId, NULL);
2337 /* save any counters that are supposed to
2338 * be monotonically increasing over the
2339 * lifetime of the fileserver */
2340 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2342 memset(&stats_save, 0, sizeof(VolumeStats));
2345 /* if there's something in the hash table, and it's not
2346 * in the pre-attach state, then we may need to detach
2347 * it before proceeding */
2348 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2349 VCreateReservation_r(vp);
2350 VWaitExclusiveState_r(vp);
2352 /* at this point state must be one of:
2362 if (vp->specialStatus == VBUSY)
2365 /* if it's already attached, see if we can return it */
2366 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2367 VGetVolumeByVp_r(ec, vp);
2368 if (V_inUse(vp) == fileServer) {
2369 VCancelReservation_r(vp);
2373 /* otherwise, we need to detach, and attempt to re-attach */
2374 VDetachVolume_r(ec, vp);
2376 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2379 /* if it isn't fully attached, delete from the hash tables,
2380 and let the refcounter handle the rest */
2381 DeleteVolumeFromHashTable(vp);
2382 DeleteVolumeFromVByPList_r(vp);
2385 VCancelReservation_r(vp);
2389 /* pre-attach volume if it hasn't been done yet */
2391 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2392 (V_attachState(vp) == VOL_STATE_DELETED) ||
2393 (V_attachState(vp) == VOL_STATE_ERROR)) {
2395 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2401 opr_Assert(vp != NULL);
2403 /* handle pre-attach races
2405 * multiple threads can race to pre-attach a volume,
2406 * but we can't let them race beyond that
2408 * our solution is to let the first thread to bring
2409 * the volume into an exclusive state win; the other
2410 * threads just wait until it finishes bringing the
2411 * volume online, and then they do a vgetvolumebyvp
2413 if (svp && (svp != vp)) {
2414 /* wait for other exclusive ops to finish */
2415 VCreateReservation_r(vp);
2416 VWaitExclusiveState_r(vp);
2418 /* get a heavyweight ref, kill the lightweight ref, and return */
2419 VGetVolumeByVp_r(ec, vp);
2420 VCancelReservation_r(vp);
2424 /* at this point, we are chosen as the thread to do
2425 * demand attachment for this volume. all other threads
2426 * doing a getvolume on vp->hashid will block until we finish */
2428 /* make sure any old header cache entries are invalidated
2429 * before proceeding */
2430 FreeVolumeHeader(vp);
2432 VChangeState_r(vp, VOL_STATE_ATTACHING);
2434 /* restore any saved counters */
2435 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2436 #else /* AFS_DEMAND_ATTACH_FS */
2437 vp = VGetVolume_r(ec, volumeId);
2439 if (V_inUse(vp) == fileServer)
2441 if (vp->specialStatus == VBUSY)
2443 VDetachVolume_r(ec, vp);
2445 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2449 #endif /* AFS_DEMAND_ATTACH_FS */
2453 strcpy(path, VPartitionPath(partp));
2457 strcat(path, OS_DIRSEP);
2461 vp = (Volume *) calloc(1, sizeof(Volume));
2462 opr_Assert(vp != NULL);
2463 vp->hashid = volumeId;
2464 vp->device = partp->device;
2465 vp->partition = partp;
2466 queue_Init(&vp->vnode_list);
2467 queue_Init(&vp->rx_call_list);
2468 #ifdef AFS_DEMAND_ATTACH_FS
2469 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2470 #endif /* AFS_DEMAND_ATTACH_FS */
2473 /* attach2 is entered without any locks, and returns
2474 * with vol_glock_mutex held */
2475 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2477 if (VCanUseFSSYNC() && vp) {
2478 #ifdef AFS_DEMAND_ATTACH_FS
2479 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2480 /* mark volume header as in use so that volser crashes lead to a
2481 * salvage attempt */
2482 VUpdateVolume_r(ec, vp, 0);
2484 /* for dafs, we should tell the fileserver, except for V_PEEK
2485 * where we know it is not necessary */
2486 if (mode == V_PEEK) {
2487 vp->needsPutBack = 0;
2489 vp->needsPutBack = VOL_PUTBACK;
2491 #else /* !AFS_DEMAND_ATTACH_FS */
2492 /* duplicate computation in fssync.c about whether the server
2493 * takes the volume offline or not. If the volume isn't
2494 * offline, we must not return it when we detach the volume,
2495 * or the server will abort */
2496 if (mode == V_READONLY || mode == V_PEEK
2497 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2498 vp->needsPutBack = 0;
2500 vp->needsPutBack = VOL_PUTBACK;
2501 #endif /* !AFS_DEMAND_ATTACH_FS */
2503 #ifdef FSSYNC_BUILD_CLIENT
2504 /* Only give back the vol to the fileserver if we checked it out; attach2
2505 * will set checkedOut only if we successfully checked it out from the
2507 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2509 #ifdef AFS_DEMAND_ATTACH_FS
2510 /* If we couldn't attach but we scheduled a salvage, we already
2511 * notified the fileserver; don't online it now */
2512 if (*ec != VSALVAGING)
2513 #endif /* AFS_DEMAND_ATTACH_FS */
2514 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2517 if (programType == fileServer && vp) {
2518 #ifdef AFS_DEMAND_ATTACH_FS
2520 * we can get here in cases where we don't "own"
2521 * the volume (e.g. volume owned by a utility).
2522 * short circuit around potential disk header races.
2524 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2528 VUpdateVolume_r(ec, vp, 0);
2530 Log("VAttachVolume: Error updating volume\n");
2535 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2536 #ifndef AFS_DEMAND_ATTACH_FS
2537 /* This is a hack: by temporarily setting the incore
2538 * dontSalvage flag ON, the volume will be put back on the
2539 * Update list (with dontSalvage OFF again). It will then
2540 * come back in N minutes with DONT_SALVAGE eventually
2541 * set. This is the way that volumes that have never had
2542 * it set get it set; or that volumes that have been
2543 * offline without DONT SALVAGE having been set also
2544 * eventually get it set */
2545 V_dontSalvage(vp) = DONT_SALVAGE;
2546 #endif /* !AFS_DEMAND_ATTACH_FS */
2547 VAddToVolumeUpdateList_r(ec, vp);
2549 Log("VAttachVolume: Error adding volume to update list\n");
2556 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2561 if (VRequiresPartLock()) {
2562 VUnlockPartition_r(partition);
2565 #ifdef AFS_DEMAND_ATTACH_FS
2566 /* attach failed; make sure we're in error state */
2567 if (vp && !VIsErrorState(V_attachState(vp))) {
2568 VChangeState_r(vp, VOL_STATE_ERROR);
2570 #endif /* AFS_DEMAND_ATTACH_FS */
2577 #ifdef AFS_DEMAND_ATTACH_FS
2578 /* VAttachVolumeByVp_r
2580 * finish attaching a volume that is
2581 * in a less than fully attached state
2583 /* caller MUST hold a ref count on vp */
2585 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2587 char name[VMAXPATHLEN];
2589 struct DiskPartition64 *partp;
2593 Volume * nvp = NULL;
2594 VolumeStats stats_save;
2598 /* volume utility should never call AttachByVp */
2599 opr_Assert(programType == fileServer);
2601 volumeId = vp->hashid;
2602 partp = vp->partition;
2603 VolumeExternalName_r(volumeId, name, sizeof(name));
2606 /* if another thread is performing a blocking op, wait */
2607 VWaitExclusiveState_r(vp);
2609 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2611 /* if it's already attached, see if we can return it */
2612 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2613 VGetVolumeByVp_r(ec, vp);
2614 if (V_inUse(vp) == fileServer) {
2617 if (vp->specialStatus == VBUSY)
2619 VDetachVolume_r(ec, vp);
2621 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2627 /* pre-attach volume if it hasn't been done yet */
2629 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2630 (V_attachState(vp) == VOL_STATE_DELETED) ||
2631 (V_attachState(vp) == VOL_STATE_ERROR)) {
2632 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2638 VCreateReservation_r(nvp);
2643 opr_Assert(vp != NULL);
2644 VChangeState_r(vp, VOL_STATE_ATTACHING);
2646 /* restore monotonically increasing stats */
2647 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2651 /* compute path to disk header */
2652 strcpy(path, VPartitionPath(partp));
2656 strcat(path, OS_DIRSEP);
2661 * NOTE: attach2 is entered without any locks, and returns
2662 * with vol_glock_mutex held */
2663 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2666 * the event that an error was encountered, or
2667 * the volume was not brought to an attached state
2668 * for any reason, skip to the end. We cannot
2669 * safely call VUpdateVolume unless we "own" it.
2673 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2677 VUpdateVolume_r(ec, vp, 0);
2679 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2683 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2684 #ifndef AFS_DEMAND_ATTACH_FS
2685 /* This is a hack: by temporarily setting the incore
2686 * dontSalvage flag ON, the volume will be put back on the
2687 * Update list (with dontSalvage OFF again). It will then
2688 * come back in N minutes with DONT_SALVAGE eventually
2689 * set. This is the way that volumes that have never had
2690 * it set get it set; or that volumes that have been
2691 * offline without DONT SALVAGE having been set also
2692 * eventually get it set */
2693 V_dontSalvage(vp) = DONT_SALVAGE;
2694 #endif /* !AFS_DEMAND_ATTACH_FS */
2695 VAddToVolumeUpdateList_r(ec, vp);
2697 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2704 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2708 VCancelReservation_r(nvp);
2711 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2712 if (vp && !VIsErrorState(V_attachState(vp))) {
2713 VChangeState_r(vp, VOL_STATE_ERROR);
2722 * lock a volume on disk (non-blocking).
2724 * @param[in] vp The volume to lock
2725 * @param[in] locktype READ_LOCK or WRITE_LOCK
2727 * @return operation status
2728 * @retval 0 success, lock was obtained
2729 * @retval EBUSY a conflicting lock was held by another process
2730 * @retval EIO error acquiring lock
2732 * @pre If we're in the fileserver, vp is in an exclusive state
2734 * @pre vp is not already locked
2737 VLockVolumeNB(Volume *vp, int locktype)
2741 opr_Assert(programType != fileServer
2742 || VIsExclusiveState(V_attachState(vp)));
2743 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2745 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2747 V_attachFlags(vp) |= VOL_LOCKED;
2754 * unlock a volume on disk that was locked with VLockVolumeNB.
2756 * @param[in] vp volume to unlock
2758 * @pre If we're in the fileserver, vp is in an exclusive state
2760 * @pre vp has already been locked
2763 VUnlockVolume(Volume *vp)
2765 opr_Assert(programType != fileServer
2766 || VIsExclusiveState(V_attachState(vp)));
2767 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2769 VUnlockVolumeById(vp->hashid, vp->partition);
2771 V_attachFlags(vp) &= ~VOL_LOCKED;
2773 #endif /* AFS_DEMAND_ATTACH_FS */
2776 * read in a vol header, possibly lock the vol header, and possibly check out
2777 * the vol header from the fileserver, as part of volume attachment.
2779 * @param[out] ec error code
2780 * @param[in] vp volume pointer object
2781 * @param[in] partp disk partition object of the attaching partition
2782 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2784 * @param[in] peek 1 to just try to read in the volume header and make sure
2785 * we don't try to lock the vol, or check it out from
2786 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2788 * @param[out] acheckedOut If we successfully checked-out the volume from
2789 * the fileserver (if we needed to), this is set
2790 * to 1, otherwise it is untouched.
2792 * @note As part of DAFS volume attachment, the volume header may be either
2793 * read- or write-locked to ensure mutual exclusion of certain volume
2794 * operations. In some cases in order to determine whether we need to
2795 * read- or write-lock the header, we need to read in the header to see
2796 * if the volume is RW or not. So, if we read in the header under a
2797 * read-lock and determine that we actually need a write-lock on the
2798 * volume header, this function will drop the read lock, acquire a write
2799 * lock, and read the header in again.
2802 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2803 int mode, int peek, int *acheckedOut)
2805 struct VolumeDiskHeader diskHeader;
2806 struct VolumeHeader header;
2809 int lock_tries = 0, checkout_tries = 0;
2811 VolumeId volid = vp->hashid;
2812 #ifdef FSSYNC_BUILD_CLIENT
2813 int checkout, done_checkout = 0;
2814 #endif /* FSSYNC_BUILD_CLIENT */
2815 #ifdef AFS_DEMAND_ATTACH_FS
2816 int locktype = 0, use_locktype = -1;
2817 #endif /* AFS_DEMAND_ATTACH_FS */
2823 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2824 Log("VAttachVolume: retried too many times trying to lock header for "
2825 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2826 VPartitionPath(partp));
2830 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2831 Log("VAttachVolume: retried too many times trying to checkout "
2832 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2833 VPartitionPath(partp));
2838 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2839 /* short-circuit the 'volume does not exist' case */
2844 #ifdef FSSYNC_BUILD_CLIENT
2845 checkout = !done_checkout;
2847 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2849 memset(&res, 0, sizeof(res));
2851 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2854 if (res.hdr.reason == FSYNC_SALVAGE) {
2855 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2856 afs_printable_uint32_lu(volid));
2859 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2860 afs_printable_uint32_lu(volid));
2861 *ec = VNOVOL; /* XXXX */
2869 #ifdef AFS_DEMAND_ATTACH_FS
2870 if (use_locktype < 0) {
2871 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2872 * if it turns out to be RW */
2873 locktype = VVolLockType(mode, 0);
2876 /* a previous try says we should use use_locktype to lock the volume,
2878 locktype = use_locktype;
2881 if (!peek && locktype) {
2882 code = VLockVolumeNB(vp, locktype);
2884 if (code == EBUSY) {
2885 Log("VAttachVolume: another program has vol %lu locked\n",
2886 afs_printable_uint32_lu(volid));
2888 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2889 code, afs_printable_uint32_lu(volid));
2896 #endif /* AFS_DEMAND_ATTACH_FS */
2898 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2908 DiskToVolumeHeader(&header, &diskHeader);
2910 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2911 header.largeVnodeIndex);
2912 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2913 header.smallVnodeIndex);
2914 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2916 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2919 /* only need to do this once */
2921 GetVolumeHeader(vp);
2925 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2926 /* demand attach changes the V_PEEK mechanism
2928 * we can now suck the current disk data structure over
2929 * the fssync interface without going to disk
2931 * (technically, we don't need to restrict this feature
2932 * to demand attach fileservers. However, I'm trying
2933 * to limit the number of common code changes)
2935 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2937 res.payload.len = sizeof(VolumeDiskData);
2938 res.payload.buf = &vp->header->diskstuff;
2940 if (FSYNC_VolOp(vp->hashid,
2942 FSYNC_VOL_QUERY_HDR,
2945 goto disk_header_loaded;
2948 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2949 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2950 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2952 #ifdef AFS_DEMAND_ATTACH_FS
2955 IncUInt64(&VStats.hdr_loads);
2956 IncUInt64(&vp->stats.hdr_loads);
2958 #endif /* AFS_DEMAND_ATTACH_FS */
2961 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2962 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2966 #ifdef AFS_DEMAND_ATTACH_FS
2967 # ifdef FSSYNC_BUILD_CLIENT
2969 # endif /* FSSYNC_BUILD_CLIENT */
2971 /* if the lock type we actually used to lock the volume is different than
2972 * the lock type we should have used, retry with the lock type we should
2974 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2975 if (locktype != use_locktype) {
2979 #endif /* AFS_DEMAND_ATTACH_FS */
2984 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2985 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2987 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2989 if (code == SYNC_DENIED) {
2990 /* must retry checkout; fileserver no longer thinks we have
2996 } else if (code != SYNC_OK) {
3000 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3003 /* either we are going to be called again for a second pass, or we
3004 * encountered an error; clean up in either case */
3006 #ifdef AFS_DEMAND_ATTACH_FS
3007 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3010 #endif /* AFS_DEMAND_ATTACH_FS */
3011 if (vp->linkHandle) {
3012 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3013 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3014 IH_RELEASE(vp->diskDataHandle);
3015 IH_RELEASE(vp->linkHandle);
3021 FreeVolumeHeader(vp);
3031 #ifdef AFS_DEMAND_ATTACH_FS
3033 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3034 Volume *vp, int *acheckedOut)
3038 if (vp->pending_vol_op) {
3042 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3044 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3046 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3047 } else if (code == 0) {
3048 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3051 /* we need the vol header to determine if the volume can be
3052 * left online for the vop, so... get the header */
3056 /* attach header with peek=1 to avoid checking out the volume
3057 * or locking it; we just want the header info, we're not
3058 * messing with the volume itself at all */
3059 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3066 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3067 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3069 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3072 /* make sure we grab a new vol header and re-open stuff on
3073 * actual attachment; we can't keep the data we grabbed, since
3074 * it was not done under a lock and thus not safe */
3075 FreeVolumeHeader(vp);
3076 VReleaseVolumeHandles_r(vp);
3079 /* see if the pending volume op requires exclusive access */
3080 switch (vp->pending_vol_op->vol_op_state) {
3081 case FSSYNC_VolOpPending:
3082 /* this should never happen */
3083 opr_Assert(vp->pending_vol_op->vol_op_state
3084 != FSSYNC_VolOpPending);
3087 case FSSYNC_VolOpRunningUnknown:
3088 /* this should never happen; we resolved 'unknown' above */
3089 opr_Assert(vp->pending_vol_op->vol_op_state
3090 != FSSYNC_VolOpRunningUnknown);
3093 case FSSYNC_VolOpRunningOffline:
3094 /* mark the volume down */
3096 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3098 /* do not set V_offlineMessage here; we don't have ownership of
3099 * the volume (and probably do not have the header loaded), so we
3100 * can't alter the disk header */
3102 /* check to see if we should set the specialStatus flag */
3103 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3104 /* don't overwrite specialStatus if it was already set to
3105 * something else (e.g. VMOVED) */
3106 if (!vp->specialStatus) {
3107 vp->specialStatus = VBUSY;
3119 #endif /* AFS_DEMAND_ATTACH_FS */
3122 * volume attachment helper function.
3124 * @param[out] ec error code
3125 * @param[in] volumeId volume ID of the attaching volume
3126 * @param[in] path full path to the volume header .vol file
3127 * @param[in] partp disk partition object for the attaching partition
3128 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3129 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3130 * DAFS) should already be initialized
3131 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3132 * if there is a volume operation running for this volume
3133 * that should set the volume to VBUSY during its run. 0
3134 * otherwise. (see VVolOpSetVBusy_r)
3135 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3137 * @param[out] acheckedOut If we successfully checked-out the volume from
3138 * the fileserver (if we needed to), this is set
3139 * to 1, otherwise it is 0.
3141 * @return pointer to the semi-attached volume pointer
3142 * @retval NULL an error occurred (check value of *ec)
3143 * @retval vp volume successfully attaching
3145 * @pre no locks held
3147 * @post VOL_LOCK held
3150 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3151 Volume * vp, int isbusy, int mode, int *acheckedOut)
3153 /* have we read in the header successfully? */
3154 int read_header = 0;
3156 #ifdef AFS_DEMAND_ATTACH_FS
3157 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3161 /* in the case of an error, to what state should the volume be
3163 VolState error_state = VOL_STATE_ERROR;
3164 #endif /* AFS_DEMAND_ATTACH_FS */
3168 vp->vnodeIndex[vLarge].handle = NULL;
3169 vp->vnodeIndex[vSmall].handle = NULL;
3170 vp->diskDataHandle = NULL;
3171 vp->linkHandle = NULL;
3175 #ifdef AFS_DEMAND_ATTACH_FS
3176 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3178 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3181 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3182 #endif /* !AFS_DEMAND_ATTACH_FS */
3184 if (*ec == VNOVOL) {
3185 /* if the volume doesn't exist, skip straight to 'error' so we don't
3186 * request a salvage */
3187 goto unlocked_error;
3193 /* ensure that we don't override specialStatus if it was set to
3194 * something else (e.g. VMOVED) */
3195 if (isbusy && !vp->specialStatus) {
3196 vp->specialStatus = VBUSY;
3198 vp->shuttingDown = 0;
3199 vp->goingOffline = 0;
3201 #ifdef AFS_DEMAND_ATTACH_FS
3202 vp->stats.last_attach = FT_ApproxTime();
3203 vp->stats.attaches++;
3207 IncUInt64(&VStats.attaches);
3208 vp->cacheCheck = ++VolumeCacheCheck;
3209 /* just in case this ever rolls over */
3210 if (!vp->cacheCheck)
3211 vp->cacheCheck = ++VolumeCacheCheck;
3214 #ifdef AFS_DEMAND_ATTACH_FS
3215 V_attachFlags(vp) |= VOL_HDR_LOADED;
3216 vp->stats.last_hdr_load = vp->stats.last_attach;
3217 #endif /* AFS_DEMAND_ATTACH_FS */
3221 struct IndexFileHeader iHead;
3224 * We just read in the diskstuff part of the header. If the detailed
3225 * volume stats area has not yet been initialized, we should bzero the
3226 * area and mark it as initialized.
3228 if (!(V_stat_initialized(vp))) {
3229 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3230 V_stat_initialized(vp) = 1;
3233 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3234 (char *)&iHead, sizeof(iHead),
3235 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3238 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3243 struct IndexFileHeader iHead;
3245 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3246 (char *)&iHead, sizeof(iHead),
3247 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3250 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3254 #ifdef AFS_NAMEI_ENV
3256 struct versionStamp stamp;
3258 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3259 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3262 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3265 #endif /* AFS_NAMEI_ENV */
3267 #if defined(AFS_DEMAND_ATTACH_FS)
3268 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3270 if (!VCanScheduleSalvage()) {
3271 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3273 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3278 /* volume operation in progress */
3280 /* we have already transitioned the vp away from ATTACHING state, so we
3281 * can go right to the end of attach2, and we do not need to transition
3283 goto error_notbroken;
3285 #else /* AFS_DEMAND_ATTACH_FS */
3287 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3288 goto unlocked_error;
3290 #endif /* AFS_DEMAND_ATTACH_FS */
3292 if (V_needsSalvaged(vp)) {
3293 if (vp->specialStatus)
3294 vp->specialStatus = 0;
3296 #if defined(AFS_DEMAND_ATTACH_FS)
3297 if (!VCanScheduleSalvage()) {
3298 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3300 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3303 #else /* AFS_DEMAND_ATTACH_FS */
3305 #endif /* AFS_DEMAND_ATTACH_FS */
3311 vp->nextVnodeUnique = V_uniquifier(vp);
3313 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3314 if (!V_needsSalvaged(vp)) {
3315 V_needsSalvaged(vp) = 1;
3316 VUpdateVolume_r(ec, vp, 0);
3318 #if defined(AFS_DEMAND_ATTACH_FS)
3319 if (!VCanScheduleSalvage()) {
3320 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3322 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3325 #else /* AFS_DEMAND_ATTACH_FS */
3326 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3328 #endif /* AFS_DEMAND_ATTACH_FS */
3333 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3334 /* Only check destroyMe if we are the fileserver, since the
3335 * volserver et al sometimes need to work with volumes with
3336 * destroyMe set. Examples are 'temporary' volumes the
3337 * volserver creates, and when we create a volume (destroyMe
3338 * is set on creation; sometimes a separate volserver
3339 * transaction is created to clear destroyMe).
3342 #if defined(AFS_DEMAND_ATTACH_FS)
3343 /* schedule a salvage so the volume goes away on disk */
3344 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3345 VChangeState_r(vp, VOL_STATE_ERROR);
3348 #endif /* AFS_DEMAND_ATTACH_FS */
3349 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3354 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3355 #ifndef BITMAP_LATER
3356 if (programType == fileServer && VolumeWriteable(vp)) {
3358 for (i = 0; i < nVNODECLASSES; i++) {
3359 VGetBitmap_r(ec, vp, i);
3361 #ifdef AFS_DEMAND_ATTACH_FS
3362 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3364 #endif /* AFS_DEMAND_ATTACH_FS */
3365 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3371 #endif /* BITMAP_LATER */
3373 if (VInit >= 2 && V_needsCallback(vp)) {
3374 if (V_BreakVolumeCallbacks) {
3375 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3376 afs_printable_uint32_lu(V_id(vp)));
3377 V_needsCallback(vp) = 0;
3379 (*V_BreakVolumeCallbacks) (V_id(vp));
3382 VUpdateVolume_r(ec, vp, 0);
3384 #ifdef FSSYNC_BUILD_CLIENT
3385 else if (VCanUseFSSYNC()) {
3386 afs_int32 fsync_code;
3388 V_needsCallback(vp) = 0;
3390 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3394 V_needsCallback(vp) = 1;
3395 Log("Error trying to tell the fileserver to break callbacks for "
3396 "changed volume %lu; error code %ld\n",
3397 afs_printable_uint32_lu(V_id(vp)),
3398 afs_printable_int32_ld(fsync_code));
3400 VUpdateVolume_r(ec, vp, 0);
3403 #endif /* FSSYNC_BUILD_CLIENT */
3406 Log("VAttachVolume: error %d clearing needsCallback on volume "
3407 "%lu; needs salvage\n", (int)*ec,
3408 afs_printable_uint32_lu(V_id(vp)));
3409 #ifdef AFS_DEMAND_ATTACH_FS
3410 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3412 #else /* !AFS_DEMAND_ATTACH_FS */
3414 #endif /* !AFS_DEMAND_ATTACh_FS */
3419 if (programType == fileServer) {
3420 if (vp->specialStatus)
3421 vp->specialStatus = 0;
3422 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3423 V_inUse(vp) = fileServer;
3424 V_offlineMessage(vp)[0] = '\0';
3428 #ifdef AFS_DEMAND_ATTACH_FS
3429 /* Put the vol into PREATTACHED state, so if someone tries to
3430 * access it again, we try to attach, see that we're not blessed,
3431 * and give a VNOVOL error again. Putting it into UNATTACHED state
3432 * would result in a VOFFLINE error instead. */
3433 error_state = VOL_STATE_PREATTACHED;
3434 #endif /* AFS_DEMAND_ATTACH_FS */
3436 /* mimic e.g. GetVolume errors */
3437 if (!V_blessed(vp)) {
3438 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3439 FreeVolumeHeader(vp);
3440 } else if (!V_inService(vp)) {
3441 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3442 FreeVolumeHeader(vp);
3444 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3446 #ifdef AFS_DEMAND_ATTACH_FS
3447 error_state = VOL_STATE_ERROR;
3448 /* see if we can recover */
3449 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3452 #ifdef AFS_DEMAND_ATTACH_FS
3458 #ifdef AFS_DEMAND_ATTACH_FS
3459 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3460 V_inUse(vp) = programType;
3461 #endif /* AFS_DEMAND_ATTACH_FS */
3462 V_checkoutMode(vp) = mode;
3465 AddVolumeToHashTable(vp, V_id(vp));
3466 #ifdef AFS_DEMAND_ATTACH_FS
3467 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3470 if ((programType != fileServer) ||
3471 (V_inUse(vp) == fileServer)) {
3472 AddVolumeToVByPList_r(vp);
3474 VChangeState_r(vp, VOL_STATE_ATTACHED);
3476 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3485 #ifdef AFS_DEMAND_ATTACH_FS
3486 if (!VIsErrorState(V_attachState(vp))) {
3487 if (VIsErrorState(error_state)) {
3488 Log("attach2: forcing vol %u to error state (state %u flags 0x%x ec %d)\n",
3489 vp->hashid, V_attachState(vp), V_attachFlags(vp), *ec);
3491 VChangeState_r(vp, error_state);
3493 #endif /* AFS_DEMAND_ATTACH_FS */
3496 VReleaseVolumeHandles_r(vp);
3499 #ifdef AFS_DEMAND_ATTACH_FS
3501 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3502 /* The salvage could not be scheduled with the salvage server
3503 * due to a hard error. Reset the error code to prevent retry loops by
3505 if (*ec == VSALVAGING) {
3514 #else /* !AFS_DEMAND_ATTACH_FS */
3516 #endif /* !AFS_DEMAND_ATTACH_FS */
3520 /* Attach an existing volume.
3521 The volume also normally goes online at this time.
3522 An offline volume must be reattached to make it go online.
3526 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3530 retVal = VAttachVolume_r(ec, volumeId, mode);
3536 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3539 VGetVolumePath(ec, volumeId, &part, &name);
3543 vp = VGetVolume_r(&error, volumeId);
3545 opr_Assert(V_inUse(vp) == 0);
3546 VDetachVolume_r(ec, vp);
3550 return VAttachVolumeByName_r(ec, part, name, mode);
3553 /* Increment a reference count to a volume, sans context swaps. Requires
3554 * possibly reading the volume header in from the disk, since there's
3555 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3557 * N.B. This call can fail if we can't read in the header!! In this case
3558 * we still guarantee we won't context swap, but the ref count won't be
3559 * incremented (otherwise we'd violate the invariant).
3561 /* NOTE: with the demand attach fileserver extensions, the global lock
3562 * is dropped within VHold */
3563 #ifdef AFS_DEMAND_ATTACH_FS
3565 VHold_r(Volume * vp)
3569 VCreateReservation_r(vp);
3570 VWaitExclusiveState_r(vp);
3572 LoadVolumeHeader(&error, vp);
3574 VCancelReservation_r(vp);
3578 VCancelReservation_r(vp);
3581 #else /* AFS_DEMAND_ATTACH_FS */
3583 VHold_r(Volume * vp)
3587 LoadVolumeHeader(&error, vp);
3593 #endif /* AFS_DEMAND_ATTACH_FS */
3595 /**** volume timeout-related stuff ****/
3597 #ifdef AFS_PTHREAD_ENV
3599 static struct timespec *shutdown_timeout;
3600 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3603 VTimedOut(const struct timespec *ts)
3608 if (ts->tv_sec == 0) {
3609 /* short-circuit; this will have always timed out */
3613 code = gettimeofday(&tv, NULL);
3615 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3616 /* assume no timeout; failure mode is we just wait longer than normal
3617 * instead of returning errors when we shouldn't */
3621 if (tv.tv_sec < ts->tv_sec ||
3622 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3631 * Calculate an absolute timeout.
3633 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3634 * NULL, the memory is not touched
3635 * @param[in] timeout How long the timeout should be from now
3637 * @return timeout to use
3638 * @retval NULL no timeout; wait forever
3639 * @retval non-NULL the given value for "ts"
3643 static struct timespec *
3644 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3654 ts->tv_sec = ts->tv_nsec = 0;
3658 code = gettimeofday(&now, NULL);
3660 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3664 ts->tv_sec = now.tv_sec + timeout;
3665 ts->tv_nsec = now.tv_usec * 1000;
3671 * Initialize the shutdown_timeout global.
3674 VShutdownTimeoutInit(void)
3676 struct timespec *ts;
3678 ts = malloc(sizeof(*ts));
3680 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3682 if (!shutdown_timeout) {
3688 * Figure out the timeout that should be used for waiting for offline volumes.
3690 * @param[out] ats Storage space for a local timeout value if needed
3692 * @return The timeout value that should be used
3693 * @retval NULL No timeout; wait forever for offlining volumes
3694 * @retval non-NULL A pointer to the absolute time that should be used as
3695 * the deadline for waiting for offlining volumes.
3697 * @note If we return non-NULL, the pointer we return may or may not be the
3700 static const struct timespec *
3701 VOfflineTimeout(struct timespec *ats)
3703 if (vol_shutting_down) {
3704 opr_Verify(pthread_once(&shutdown_timeout_once,
3705 VShutdownTimeoutInit) == 0);
3706 return shutdown_timeout;
3708 return VCalcTimeout(ats, vol_opts.offline_timeout);
3712 #else /* AFS_PTHREAD_ENV */
3714 /* Waiting a certain amount of time for offlining volumes is not supported
3715 * for LWP due to a lack of primitives. So, we never time out */
3716 # define VTimedOut(x) (0)
3717 # define VOfflineTimeout(x) (NULL)
3719 #endif /* !AFS_PTHREAD_ENV */
3727 retVal = VHold_r(vp);
3734 VIsGoingOffline_r(struct Volume *vp)
3738 if (vp->goingOffline) {
3739 if (vp->specialStatus) {
3740 code = vp->specialStatus;
3741 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3752 * Tell the caller if a volume is waiting to go offline.
3754 * @param[in] vp The volume we want to know about
3756 * @return volume status
3757 * @retval 0 volume is not waiting to go offline, go ahead and use it
3758 * @retval nonzero volume is waiting to offline, and give the returned code
3759 * as an error to anyone accessing the volume
3761 * @pre VOL_LOCK is NOT held
3762 * @pre caller holds a heavyweight reference on vp
3765 VIsGoingOffline(struct Volume *vp)
3770 code = VIsGoingOffline_r(vp);
3777 * Register an RX call with a volume.
3779 * @param[inout] ec Error code; if unset when passed in, may be set if
3780 * the volume starts going offline
3781 * @param[out] client_ec @see GetVolume
3782 * @param[in] vp Volume struct
3783 * @param[in] cbv VCallByVol struct containing the RX call to register
3785 * @pre VOL_LOCK held
3786 * @pre caller holds heavy ref on vp
3791 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3794 #ifdef AFS_DEMAND_ATTACH_FS
3796 /* just in case the volume started going offline after we got the
3797 * reference to it... otherwise, if the volume started going
3798 * offline right at the end of GetVolume(), we might race with the
3799 * RX call scanner, and return success and add our cbv to the
3800 * rx_call_list _after_ the scanner has scanned the list. */
3801 *ec = VIsGoingOffline_r(vp);
3807 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3808 VWaitStateChange_r(vp);
3810 #endif /* AFS_DEMAND_ATTACH_FS */
3812 queue_Prepend(&vp->rx_call_list, cbv);
3817 * Deregister an RX call with a volume.
3819 * @param[in] vp Volume struct
3820 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3822 * @pre VOL_LOCK held
3823 * @pre caller holds heavy ref on vp
3828 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3830 if (cbv && queue_IsOnQueue(cbv)) {
3831 #ifdef AFS_DEMAND_ATTACH_FS
3832 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3833 VWaitStateChange_r(vp);
3835 #endif /* AFS_DEMAND_ATTACH_FS */
3841 /***************************************************/
3842 /* get and put volume routines */
3843 /***************************************************/
3846 * put back a heavyweight reference to a volume object.
3848 * @param[in] vp volume object pointer
3850 * @pre VOL_LOCK held
3852 * @post heavyweight volume reference put back.
3853 * depending on state, volume may have been taken offline,
3854 * detached, salvaged, freed, etc.
3856 * @internal volume package internal use only
3859 VPutVolume_r(Volume * vp)
3861 opr_Verify(--vp->nUsers >= 0);
3862 if (vp->nUsers == 0) {
3864 ReleaseVolumeHeader(vp->header);
3865 #ifdef AFS_DEMAND_ATTACH_FS
3866 if (!VCheckDetach(vp)) {
3870 #else /* AFS_DEMAND_ATTACH_FS */
3872 #endif /* AFS_DEMAND_ATTACH_FS */
3877 VPutVolume(Volume * vp)
3885 * Puts a volume reference obtained with VGetVolumeWithCall.
3887 * @param[in] vp Volume struct
3888 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3890 * @pre VOL_LOCK is NOT held
3893 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3896 VDeregisterCall_r(vp, cbv);
3901 /* Get a pointer to an attached volume. The pointer is returned regardless
3902 of whether or not the volume is in service or on/off line. An error
3903 code, however, is returned with an indication of the volume's status */
3905 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3909 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3915 * Get a volume reference associated with an RX call.
3917 * @param[out] ec @see GetVolume
3918 * @param[out] client_ec @see GetVolume
3919 * @param[in] volumeId @see GetVolume
3920 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3921 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3922 * with an error if the volume is going offline.
3923 * @param[in] cbv Contains an RX call to be associated with this volume
3924 * reference. This call may be interrupted if the volume is
3925 * requested to go offline while we hold a ref on it. Give NULL
3926 * to not associate an RX call with this reference.
3928 * @return @see GetVolume
3930 * @note for LWP builds, ts must be NULL
3932 * @note A reference obtained with this function MUST be put back with
3933 * VPutVolumeWithCall
3936 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3937 const struct timespec *ts, struct VCallByVol *cbv)
3941 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3942 VRegisterCall_r(ec, client_ec, retVal, cbv);
3948 VGetVolume_r(Error * ec, VolId volumeId)
3950 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3953 /* try to get a volume we've previously looked up */
3954 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3956 VGetVolumeByVp_r(Error * ec, Volume * vp)
3958 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3962 * private interface for getting a volume handle
3964 * @param[out] ec error code (0 if no error)
3965 * @param[out] client_ec wire error code to be given to clients
3966 * @param[in] volumeId ID of the volume we want
3967 * @param[in] hint optional hint for hash lookups, or NULL
3968 * @param[in] timeout absolute deadline for waiting for the volume to go
3969 * offline, if it is going offline. NULL to wait forever.
3971 * @return a volume handle for the specified volume
3972 * @retval NULL an error occurred, or the volume is in such a state that
3973 * we cannot load a header or return any volume struct
3975 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3977 * @note 'timeout' is only checked if the volume is actually going offline; so
3978 * if you pass timeout->tv_sec = 0, this will exhibit typical
3979 * nonblocking behavior.
3981 * @note for LWP builds, 'timeout' must be NULL
3984 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3985 const struct timespec *timeout)
3988 /* pull this profiling/debugging code out of regular builds */
3990 #define VGET_CTR_INC(x) x++
3991 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3992 0, V7 = 0, V8 = 0, V9 = 0;
3993 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3995 #define VGET_CTR_INC(x)
3997 #ifdef AFS_DEMAND_ATTACH_FS
3998 Volume *avp, * rvp = hint;
4002 * if VInit is zero, the volume package dynamic
4003 * data structures have not been initialized yet,
4004 * and we must immediately return an error
4010 *client_ec = VOFFLINE;
4015 #ifdef AFS_DEMAND_ATTACH_FS
4017 VCreateReservation_r(rvp);
4019 #endif /* AFS_DEMAND_ATTACH_FS */
4027 vp = VLookupVolume_r(ec, volumeId, vp);
4033 #ifdef AFS_DEMAND_ATTACH_FS
4034 if (rvp && (rvp != vp)) {
4035 /* break reservation on old vp */
4036 VCancelReservation_r(rvp);
4039 #endif /* AFS_DEMAND_ATTACH_FS */
4045 /* Until we have reached an initialization level of 2
4046 * we don't know whether this volume exists or not.
4047 * We can't sleep and retry later because before a volume
4048 * is attached, the caller tries to get it first. Just
4049 * return VOFFLINE and the caller can choose whether to
4050 * retry the command or not. */
4060 IncUInt64(&VStats.hdr_gets);
4062 #ifdef AFS_DEMAND_ATTACH_FS
4063 /* block if someone else is performing an exclusive op on this volume */
4066 VCreateReservation_r(rvp);
4068 VWaitExclusiveState_r(vp);
4070 /* short circuit with VNOVOL in the following circumstances:
4073 * - VOL_STATE_SHUTTING_DOWN
4075 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4076 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4083 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4084 * VNOVOL for VOL_STATE_DELETED
4086 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4087 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4088 (V_attachState(vp) == VOL_STATE_DELETED)) {
4089 if (vp->specialStatus) {
4090 *ec = vp->specialStatus;
4091 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4100 /* allowable states:
4107 if (vp->salvage.requested) {
4108 VUpdateSalvagePriority_r(vp);
4111 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4112 if (vp->specialStatus) {
4113 *ec = vp->specialStatus;
4117 avp = VAttachVolumeByVp_r(ec, vp, 0);
4120 /* VAttachVolumeByVp_r can return a pointer
4121 * != the vp passed to it under certain
4122 * conditions; make sure we don't leak
4123 * reservations if that happens */
4125 VCancelReservation_r(rvp);
4127 VCreateReservation_r(rvp);
4138 if (vp->specialStatus) {
4139 *ec = vp->specialStatus;
4144 if (vp->specialStatus) {
4145 *ec = vp->specialStatus;
4158 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4160 /* see CheckVnode() in afsfileprocs.c for an explanation
4161 * of this error code logic */
4162 afs_uint32 now = FT_ApproxTime();
4163 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4166 *client_ec = VRESTARTING;
4174 if (VIsErrorState(V_attachState(vp))) {
4175 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4176 * it, or transition it out of that state */
4185 * this test MUST happen after VAttachVolymeByVp, so we have no
4186 * conflicting vol op. (attach2 would have errored out if we had one;
4187 * specifically attach_check_vop must have detected a conflicting vop)
4189 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4191 #endif /* AFS_DEMAND_ATTACH_FS */
4193 LoadVolumeHeader(ec, vp);
4196 /* Only log the error if it was a totally unexpected error. Simply
4197 * a missing inode is likely to be caused by the volume being deleted */
4198 if (errno != ENXIO || LogLevel)
4199 Log("Volume %u: couldn't reread volume header\n",
4201 #ifdef AFS_DEMAND_ATTACH_FS
4202 if (VCanScheduleSalvage()) {
4203 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4208 #else /* AFS_DEMAND_ATTACH_FS */
4211 #endif /* AFS_DEMAND_ATTACH_FS */
4216 if (vp->shuttingDown) {
4223 if (programType == fileServer) {
4225 if (vp->goingOffline) {
4226 if (timeout && VTimedOut(timeout)) {
4227 /* we've timed out; don't wait for the vol */
4230 #ifdef AFS_DEMAND_ATTACH_FS
4231 /* wait for the volume to go offline */
4232 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4233 VTimedWaitStateChange_r(vp, timeout, NULL);
4235 #elif defined(AFS_PTHREAD_ENV)
4236 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4237 #else /* AFS_PTHREAD_ENV */
4238 /* LWP has no timed wait, so the caller better not be
4240 opr_Assert(!timeout);
4241 LWP_WaitProcess(VPutVolume);
4242 #endif /* AFS_PTHREAD_ENV */
4246 if (vp->specialStatus) {
4248 *ec = vp->specialStatus;
4249 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4252 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4263 #ifdef AFS_DEMAND_ATTACH_FS
4264 /* if no error, bump nUsers */
4267 VLRU_UpdateAccess_r(vp);
4270 VCancelReservation_r(rvp);
4273 if (client_ec && !*client_ec) {
4276 #else /* AFS_DEMAND_ATTACH_FS */
4277 /* if no error, bump nUsers */
4284 #endif /* AFS_DEMAND_ATTACH_FS */
4287 opr_Assert(vp || *ec);
4292 /***************************************************/
4293 /* Volume offline/detach routines */
4294 /***************************************************/
4296 /* caller MUST hold a heavyweight ref on vp */
4297 #ifdef AFS_DEMAND_ATTACH_FS
4299 VTakeOffline_r(Volume * vp)
4303 opr_Assert(vp->nUsers > 0);
4304 opr_Assert(programType == fileServer);
4306 VCreateReservation_r(vp);
4307 VWaitExclusiveState_r(vp);
4309 vp->goingOffline = 1;
4310 V_needsSalvaged(vp) = 1;
4312 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4313 VCancelReservation_r(vp);
4315 #else /* AFS_DEMAND_ATTACH_FS */
4317 VTakeOffline_r(Volume * vp)
4319 opr_Assert(vp->nUsers > 0);
4320 opr_Assert(programType == fileServer);
4322 vp->goingOffline = 1;
4323 V_needsSalvaged(vp) = 1;
4325 #endif /* AFS_DEMAND_ATTACH_FS */
4328 VTakeOffline(Volume * vp)
4336 * force a volume offline.
4338 * @param[in] vp volume object pointer
4339 * @param[in] flags flags (see note below)
4341 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4342 * used when VUpdateVolume_r needs to call VForceOffline_r
4343 * (which in turn would normally call VUpdateVolume_r)
4345 * @see VUpdateVolume_r
4347 * @pre VOL_LOCK must be held.
4348 * for DAFS, caller must hold ref.
4350 * @note for DAFS, it _is safe_ to call this function from an
4353 * @post needsSalvaged flag is set.
4354 * for DAFS, salvage is requested.
4355 * no further references to the volume through the volume
4356 * package will be honored.
4357 * all file descriptor and vnode caches are invalidated.
4359 * @warning this is a heavy-handed interface. it results in
4360 * a volume going offline regardless of the current
4361 * reference count state.
4363 * @internal volume package internal use only
4366 VForceOffline_r(Volume * vp, int flags)
4370 #ifdef AFS_DEMAND_ATTACH_FS
4371 VChangeState_r(vp, VOL_STATE_ERROR);
4376 strcpy(V_offlineMessage(vp),
4377 "Forced offline due to internal error: volume needs to be salvaged");
4378 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4381 vp->goingOffline = 0;
4382 V_needsSalvaged(vp) = 1;
4383 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4384 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4387 #ifdef AFS_DEMAND_ATTACH_FS
4388 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4389 #endif /* AFS_DEMAND_ATTACH_FS */
4391 #ifdef AFS_PTHREAD_ENV
4392 CV_BROADCAST(&vol_put_volume_cond);
4393 #else /* AFS_PTHREAD_ENV */
4394 LWP_NoYieldSignal(VPutVolume);
4395 #endif /* AFS_PTHREAD_ENV */
4397 VReleaseVolumeHandles_r(vp);
4401 * force a volume offline.
4403 * @param[in] vp volume object pointer
4405 * @see VForceOffline_r
4408 VForceOffline(Volume * vp)
4411 VForceOffline_r(vp, 0);
4416 * Iterate over the RX calls associated with a volume, and interrupt them.
4418 * @param[in] vp The volume whose RX calls we want to scan
4420 * @pre VOL_LOCK held
4423 VScanCalls_r(struct Volume *vp)
4425 struct VCallByVol *cbv, *ncbv;
4427 #ifdef AFS_DEMAND_ATTACH_FS
4428 VolState state_save;
4431 if (queue_IsEmpty(&vp->rx_call_list))
4432 return; /* no calls to interrupt */
4433 if (!vol_opts.interrupt_rxcall)
4434 return; /* we have no function with which to interrupt calls */
4435 err = VIsGoingOffline_r(vp);
4437 return; /* we're not going offline anymore */
4439 #ifdef AFS_DEMAND_ATTACH_FS
4440 VWaitExclusiveState_r(vp);
4441 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4443 #endif /* AFS_DEMAND_ATTACH_FS */
4445 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4447 struct rx_peer *peer;
4449 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4451 Log("Offlining volume %lu while client %s:%u is trying to read "
4452 "from it; kicking client off with error %ld\n",
4453 (long unsigned) vp->hashid,
4454 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4455 (unsigned) ntohs(rx_PortOf(peer)),
4458 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4461 #ifdef AFS_DEMAND_ATTACH_FS
4463 VChangeState_r(vp, state_save);
4464 #endif /* AFS_DEMAND_ATTACH_FS */
4467 #ifdef AFS_DEMAND_ATTACH_FS
4469 * Wait for a vp to go offline.
4471 * @param[out] ec 1 if a salvage on the volume has been requested and
4472 * salvok == 0, 0 otherwise
4473 * @param[in] vp The volume to wait for
4474 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4475 * has been requested to salvage. Otherwise we keep waiting
4476 * until the volume has gone offline.
4478 * @pre VOL_LOCK held
4479 * @pre caller holds a lightweight ref on vp
4484 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4486 struct timespec timeout_ts;
4487 const struct timespec *ts;
4490 ts = VOfflineTimeout(&timeout_ts);
4494 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4495 if (!salvok && vp->salvage.requested) {
4499 VTimedWaitStateChange_r(vp, ts, &timedout);
4502 /* we didn't time out, so the volume must be offline, so we're done */
4506 /* If we got here, we timed out waiting for the volume to go offline.
4507 * Kick off the accessing RX calls and wait again */
4511 while (!VIsOfflineState(V_attachState(vp))) {
4512 if (!salvok && vp->salvage.requested) {
4517 VWaitStateChange_r(vp);
4521 #else /* AFS_DEMAND_ATTACH_FS */
4524 * Wait for a volume to go offline.
4526 * @pre VOL_LOCK held
4528 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4531 VWaitForOffline_r(Error *ec, VolumeId volid)
4534 const struct timespec *ts;
4535 #ifdef AFS_PTHREAD_ENV
4536 struct timespec timeout_ts;
4539 ts = VOfflineTimeout(&timeout_ts);
4541 vp = GetVolume(ec, NULL, volid, NULL, ts);
4543 /* error occurred so bad that we can't even get a vp; we have no
4544 * information on the vol so we don't know whether to wait, so just
4548 if (!VIsGoingOffline_r(vp)) {
4549 /* volume is no longer going offline, so we're done */
4554 /* If we got here, we timed out waiting for the volume to go offline.
4555 * Kick off the accessing RX calls and wait again */
4561 vp = VGetVolume_r(ec, volid);
4563 /* In case it was reattached... */
4567 #endif /* !AFS_DEMAND_ATTACH_FS */
4569 /* The opposite of VAttachVolume. The volume header is written to disk, with
4570 the inUse bit turned off. A copy of the header is maintained in memory,
4571 however (which is why this is VOffline, not VDetach).
4574 VOffline_r(Volume * vp, char *message)
4577 #ifndef AFS_DEMAND_ATTACH_FS
4578 VolumeId vid = V_id(vp);
4581 opr_Assert(programType != volumeUtility && programType != volumeServer);
4586 if (V_offlineMessage(vp)[0] == '\0')
4587 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4588 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4590 vp->goingOffline = 1;
4591 #ifdef AFS_DEMAND_ATTACH_FS
4592 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4593 VCreateReservation_r(vp);
4595 VWaitForOfflineByVp_r(&error, vp, 1);
4596 VCancelReservation_r(vp);
4597 #else /* AFS_DEMAND_ATTACH_FS */
4599 VWaitForOffline_r(&error, vid);
4600 #endif /* AFS_DEMAND_ATTACH_FS */
4603 #ifdef AFS_DEMAND_ATTACH_FS
4605 * Take a volume offline in order to perform a volume operation.
4607 * @param[inout] ec address in which to store error code
4608 * @param[in] vp volume object pointer
4609 * @param[in] message volume offline status message
4612 * - VOL_LOCK is held
4613 * - caller MUST hold a heavyweight ref on vp
4616 * - volume is taken offline
4617 * - if possible, volume operation is promoted to running state
4618 * - on failure, *ec is set to nonzero
4620 * @note Although this function does not return any value, it may
4621 * still fail to promote our pending volume operation to
4622 * a running state. Any caller MUST check the value of *ec,
4623 * and MUST NOT blindly assume success.
4625 * @warning if the caller does not hold a lightweight ref on vp,
4626 * then it MUST NOT reference vp after this function
4627 * returns to the caller.
4629 * @internal volume package internal use only
4632 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4635 opr_Assert(vp->pending_vol_op);
4641 if (V_offlineMessage(vp)[0] == '\0')
4642 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4643 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4645 vp->goingOffline = 1;
4646 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4647 VCreateReservation_r(vp);
4650 if (vp->pending_vol_op->com.programType != salvageServer) {
4651 /* do not give corrupted volumes to the volserver */
4656 VWaitForOfflineByVp_r(ec, vp, salvok);
4658 VCancelReservation_r(vp);
4660 #endif /* AFS_DEMAND_ATTACH_FS */
4663 VOffline(Volume * vp, char *message)
4666 VOffline_r(vp, message);
4670 /* This gets used for the most part by utility routines that don't want
4671 * to keep all the volume headers around. Generally, the file server won't
4672 * call this routine, because then the offline message in the volume header
4673 * (or other information) won't be available to clients. For NAMEI, also
4674 * close the file handles. However, the fileserver does call this during
4675 * an attach following a volume operation.
4678 VDetachVolume_r(Error * ec, Volume * vp)
4680 #ifdef FSSYNC_BUILD_CLIENT
4682 struct DiskPartition64 *tpartp;
4683 int notifyServer = 0;
4684 int useDone = FSYNC_VOL_ON;
4686 if (VCanUseFSSYNC()) {
4687 notifyServer = vp->needsPutBack;
4688 if (V_destroyMe(vp) == DESTROY_ME)
4689 useDone = FSYNC_VOL_LEAVE_OFF;
4690 # ifdef AFS_DEMAND_ATTACH_FS
4691 else if (!V_blessed(vp) || !V_inService(vp))
4692 useDone = FSYNC_VOL_LEAVE_OFF;
4695 # ifdef AFS_DEMAND_ATTACH_FS
4696 if (V_needsSalvaged(vp)) {
4698 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4701 tpartp = vp->partition;
4703 #endif /* FSSYNC_BUILD_CLIENT */
4705 *ec = 0; /* always "succeeds" */
4706 DeleteVolumeFromHashTable(vp);
4707 vp->shuttingDown = 1;
4708 #ifdef AFS_DEMAND_ATTACH_FS
4709 DeleteVolumeFromVByPList_r(vp);
4711 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4713 if (programType != fileServer)
4715 #endif /* AFS_DEMAND_ATTACH_FS */
4717 /* Will be detached sometime in the future--this is OK since volume is offline */
4719 /* XXX the following code should really be moved to VCheckDetach() since the volume
4720 * is not technically detached until the refcounts reach zero
4722 #ifdef FSSYNC_BUILD_CLIENT
4723 if (VCanUseFSSYNC() && notifyServer) {
4724 if (notifyServer == VOL_PUTBACK_DELETE) {
4725 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4726 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4727 * to signify a deleted volume. */
4728 useDone = FSYNC_VOL_DONE;
4731 * Note: The server is not notified in the case of a bogus volume
4732 * explicitly to make it possible to create a volume, do a partial
4733 * restore, then abort the operation without ever putting the volume
4734 * online. This is essential in the case of a volume move operation
4735 * between two partitions on the same server. In that case, there
4736 * would be two instances of the same volume, one of them bogus,
4737 * which the file server would attempt to put on line
4739 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4740 /* XXX this code path is only hit by volume utilities, thus
4741 * V_BreakVolumeCallbacks will always be NULL. if we really
4742 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4744 /* Dettaching it so break all callbacks on it */
4745 if (V_BreakVolumeCallbacks) {
4746 Log("volume %u detached; breaking all call backs\n", volume);
4747 (*V_BreakVolumeCallbacks) (volume);
4751 #endif /* FSSYNC_BUILD_CLIENT */
4755 VDetachVolume(Error * ec, Volume * vp)
4758 VDetachVolume_r(ec, vp);
4763 /***************************************************/
4764 /* Volume fd/inode handle closing routines */
4765 /***************************************************/
4767 /* For VDetachVolume, we close all cached file descriptors, but keep
4768 * the Inode handles in case we need to read from a busy volume.
4770 /* for demand attach, caller MUST hold ref count on vp */
4772 VCloseVolumeHandles_r(Volume * vp)
4774 #ifdef AFS_DEMAND_ATTACH_FS
4775 VolState state_save;
4777 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4782 DFlushVolume(vp->hashid);
4784 #ifdef AFS_DEMAND_ATTACH_FS
4788 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4789 VCloseVnodeFiles_r(vp);
4791 #ifdef AFS_DEMAND_ATTACH_FS
4795 /* Too time consuming and unnecessary for the volserver */
4796 if (programType == fileServer) {
4797 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4798 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4799 IH_CONDSYNC(vp->diskDataHandle);
4801 IH_CONDSYNC(vp->linkHandle);
4802 #endif /* AFS_NT40_ENV */
4805 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4806 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4807 IH_REALLYCLOSE(vp->diskDataHandle);
4808 IH_REALLYCLOSE(vp->linkHandle);
4810 #ifdef AFS_DEMAND_ATTACH_FS
4811 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4816 VChangeState_r(vp, state_save);
4820 /* For both VForceOffline and VOffline, we close all relevant handles.
4821 * For VOffline, if we re-attach the volume, the files may possible be
4822 * different than before.
4824 /* for demand attach, caller MUST hold a ref count on vp */
4826 VReleaseVolumeHandles_r(Volume * vp)
4828 #ifdef AFS_DEMAND_ATTACH_FS
4829 VolState state_save;
4831 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4836 DFlushVolume(vp->hashid);
4838 #ifdef AFS_DEMAND_ATTACH_FS
4842 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4844 #ifdef AFS_DEMAND_ATTACH_FS
4848 /* Too time consuming and unnecessary for the volserver */
4849 if (programType == fileServer) {
4850 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4851 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4852 IH_CONDSYNC(vp->diskDataHandle);
4854 IH_CONDSYNC(vp->linkHandle);
4855 #endif /* AFS_NT40_ENV */
4858 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4859 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4860 IH_RELEASE(vp->diskDataHandle);
4861 IH_RELEASE(vp->linkHandle);
4863 #ifdef AFS_DEMAND_ATTACH_FS
4864 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4869 VChangeState_r(vp, state_save);
4874 /***************************************************/
4875 /* Volume write and fsync routines */
4876 /***************************************************/
4879 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4881 #ifdef AFS_DEMAND_ATTACH_FS
4882 VolState state_save;
4884 if (flags & VOL_UPDATE_WAIT) {
4885 VCreateReservation_r(vp);
4886 VWaitExclusiveState_r(vp);
4891 if (programType == fileServer)
4893 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4894 200 : V_nextVnodeUnique(vp));
4896 #ifdef AFS_DEMAND_ATTACH_FS
4897 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4901 WriteVolumeHeader_r(ec, vp);
4903 #ifdef AFS_DEMAND_ATTACH_FS
4905 VChangeState_r(vp, state_save);
4906 if (flags & VOL_UPDATE_WAIT) {
4907 VCancelReservation_r(vp);
4912 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4913 V_id(vp), V_name(vp));
4914 /* try to update on-disk header,
4915 * while preventing infinite recursion */
4916 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4917 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4923 VUpdateVolume(Error * ec, Volume * vp)
4926 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4931 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4935 #ifdef AFS_DEMAND_ATTACH_FS
4936 VolState state_save;
4939 if (flags & VOL_SYNC_WAIT) {
4940 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4942 VUpdateVolume_r(ec, vp, 0);
4945 #ifdef AFS_DEMAND_ATTACH_FS
4946 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4949 fdP = IH_OPEN(V_diskDataHandle(vp));
4950 opr_Assert(fdP != NULL);
4951 code = FDH_SYNC(fdP);
4952 opr_Assert(code == 0);
4954 #ifdef AFS_DEMAND_ATTACH_FS
4956 VChangeState_r(vp, state_save);
4962 VSyncVolume(Error * ec, Volume * vp)
4965 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4970 /***************************************************/
4971 /* Volume dealloaction routines */
4972 /***************************************************/
4974 #ifdef AFS_DEMAND_ATTACH_FS
4976 FreeVolume(Volume * vp)
4978 /* free the heap space, iff it's safe.
4979 * otherwise, pull it out of the hash table, so it
4980 * will get deallocated when all refs to it go away */
4981 if (!VCheckFree(vp)) {
4982 DeleteVolumeFromHashTable(vp);
4983 DeleteVolumeFromVByPList_r(vp);
4985 /* make sure we invalidate the header cache entry */
4986 FreeVolumeHeader(vp);
4989 #endif /* AFS_DEMAND_ATTACH_FS */
4992 ReallyFreeVolume(Volume * vp)
4997 #ifdef AFS_DEMAND_ATTACH_FS
4999 VChangeState_r(vp, VOL_STATE_FREED);
5000 if (vp->pending_vol_op)
5001 free(vp->pending_vol_op);
5002 #endif /* AFS_DEMAND_ATTACH_FS */
5003 for (i = 0; i < nVNODECLASSES; i++)
5004 if (vp->vnodeIndex[i].bitmap)
5005 free(vp->vnodeIndex[i].bitmap);
5006 FreeVolumeHeader(vp);
5007 #ifndef AFS_DEMAND_ATTACH_FS
5008 DeleteVolumeFromHashTable(vp);
5009 #endif /* AFS_DEMAND_ATTACH_FS */
5013 /* check to see if we should shutdown this volume
5014 * returns 1 if volume was freed, 0 otherwise */
5015 #ifdef AFS_DEMAND_ATTACH_FS
5017 VCheckDetach(Volume * vp)
5022 if (vp->nUsers || vp->nWaiters)
5025 if (vp->shuttingDown) {
5027 if ((programType != fileServer) &&
5028 (V_inUse(vp) == programType) &&
5029 ((V_checkoutMode(vp) == V_VOLUPD) ||
5030 (V_checkoutMode(vp) == V_SECRETLY) ||
5031 ((V_checkoutMode(vp) == V_CLONE) &&
5032 (VolumeWriteable(vp))))) {
5034 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5036 Log("VCheckDetach: volume header update for volume %u "
5037 "failed with errno %d\n", vp->hashid, errno);
5040 VReleaseVolumeHandles_r(vp);
5042 ReallyFreeVolume(vp);
5043 if (programType == fileServer) {
5044 CV_BROADCAST(&vol_put_volume_cond);
5049 #else /* AFS_DEMAND_ATTACH_FS */
5051 VCheckDetach(Volume * vp)
5059 if (vp->shuttingDown) {
5061 if ((programType != fileServer) &&
5062 (V_inUse(vp) == programType) &&
5063 ((V_checkoutMode(vp) == V_VOLUPD) ||
5064 (V_checkoutMode(vp) == V_SECRETLY) ||
5065 ((V_checkoutMode(vp) == V_CLONE) &&
5066 (VolumeWriteable(vp))))) {
5068 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5070 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5074 VReleaseVolumeHandles_r(vp);
5075 ReallyFreeVolume(vp);
5076 if (programType == fileServer) {
5077 #if defined(AFS_PTHREAD_ENV)
5078 CV_BROADCAST(&vol_put_volume_cond);
5079 #else /* AFS_PTHREAD_ENV */
5080 LWP_NoYieldSignal(VPutVolume);
5081 #endif /* AFS_PTHREAD_ENV */
5086 #endif /* AFS_DEMAND_ATTACH_FS */
5088 /* check to see if we should offline this volume
5089 * return 1 if volume went offline, 0 otherwise */
5090 #ifdef AFS_DEMAND_ATTACH_FS
5092 VCheckOffline(Volume * vp)
5096 if (vp->goingOffline && !vp->nUsers) {
5098 opr_Assert(programType == fileServer);
5099 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5100 (V_attachState(vp) != VOL_STATE_FREED) &&
5101 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5102 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5103 (V_attachState(vp) != VOL_STATE_DELETED));
5107 * VOL_STATE_GOING_OFFLINE
5108 * VOL_STATE_SHUTTING_DOWN
5109 * VIsErrorState(V_attachState(vp))
5110 * VIsExclusiveState(V_attachState(vp))
5113 VCreateReservation_r(vp);
5114 VChangeState_r(vp, VOL_STATE_OFFLINING);
5117 /* must clear the goingOffline flag before we drop the glock */
5118 vp->goingOffline = 0;
5123 /* perform async operations */
5124 VUpdateVolume_r(&error, vp, 0);
5125 VCloseVolumeHandles_r(vp);
5128 if (V_offlineMessage(vp)[0]) {
5129 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5130 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5131 V_offlineMessage(vp));
5133 Log("VOffline: Volume %lu (%s) is now offline\n",
5134 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5138 /* invalidate the volume header cache entry */
5139 FreeVolumeHeader(vp);
5141 /* if nothing changed state to error or salvaging,
5142 * drop state to unattached */
5143 if (!VIsErrorState(V_attachState(vp))) {
5144 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5146 VCancelReservation_r(vp);
5147 /* no usage of vp is safe beyond this point */
5151 #else /* AFS_DEMAND_ATTACH_FS */
5153 VCheckOffline(Volume * vp)
5157 if (vp->goingOffline && !vp->nUsers) {
5159 opr_Assert(programType == fileServer);
5162 vp->goingOffline = 0;
5164 VUpdateVolume_r(&error, vp, 0);
5165 VCloseVolumeHandles_r(vp);
5167 if (V_offlineMessage(vp)[0]) {
5168 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5169 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5170 V_offlineMessage(vp));
5172 Log("VOffline: Volume %lu (%s) is now offline\n",
5173 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5176 FreeVolumeHeader(vp);
5177 #ifdef AFS_PTHREAD_ENV
5178 CV_BROADCAST(&vol_put_volume_cond);
5179 #else /* AFS_PTHREAD_ENV */
5180 LWP_NoYieldSignal(VPutVolume);
5181 #endif /* AFS_PTHREAD_ENV */
5185 #endif /* AFS_DEMAND_ATTACH_FS */
5187 /***************************************************/
5188 /* demand attach fs ref counting routines */
5189 /***************************************************/
5191 #ifdef AFS_DEMAND_ATTACH_FS
5192 /* the following two functions handle reference counting for
5193 * asynchronous operations on volume structs.
5195 * their purpose is to prevent a VDetachVolume or VShutdown
5196 * from free()ing the Volume struct during an async i/o op */
5198 /* register with the async volume op ref counter */
5199 /* VCreateReservation_r moved into inline code header because it
5200 * is now needed in vnode.c -- tkeiser 11/20/2007
5204 * decrement volume-package internal refcount.
5206 * @param vp volume object pointer
5208 * @internal volume package internal use only
5211 * @arg VOL_LOCK is held
5212 * @arg lightweight refcount held
5214 * @post volume waiters refcount is decremented; volume may
5215 * have been deallocated/shutdown/offlined/salvaged/
5216 * whatever during the process
5218 * @warning once you have tossed your last reference (you can acquire
5219 * lightweight refs recursively) it is NOT SAFE to reference
5220 * a volume object pointer ever again
5222 * @see VCreateReservation_r
5224 * @note DEMAND_ATTACH_FS only
5227 VCancelReservation_r(Volume * vp)
5229 opr_Verify(--vp->nWaiters >= 0);
5230 if (vp->nWaiters == 0) {
5232 if (!VCheckDetach(vp)) {
5239 /* check to see if we should free this volume now
5240 * return 1 if volume was freed, 0 otherwise */
5242 VCheckFree(Volume * vp)
5245 if ((vp->nUsers == 0) &&
5246 (vp->nWaiters == 0) &&
5247 !(V_attachFlags(vp) & (VOL_IN_HASH |
5251 ReallyFreeVolume(vp);
5256 #endif /* AFS_DEMAND_ATTACH_FS */
5259 /***************************************************/
5260 /* online volume operations routines */
5261 /***************************************************/
5263 #ifdef AFS_DEMAND_ATTACH_FS
5265 * register a volume operation on a given volume.
5267 * @param[in] vp volume object
5268 * @param[in] vopinfo volume operation info object
5270 * @pre VOL_LOCK is held
5272 * @post volume operation info object attached to volume object.
5273 * volume operation statistics updated.
5275 * @note by "attached" we mean a copy of the passed in object is made
5277 * @internal volume package internal use only
5280 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5282 FSSYNC_VolOp_info * info;
5284 /* attach a vol op info node to the volume struct */
5285 info = malloc(sizeof(FSSYNC_VolOp_info));
5286 opr_Assert(info != NULL);
5287 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5288 vp->pending_vol_op = info;
5291 vp->stats.last_vol_op = FT_ApproxTime();
5292 vp->stats.vol_ops++;
5293 IncUInt64(&VStats.vol_ops);
5299 * deregister the volume operation attached to this volume.
5301 * @param[in] vp volume object pointer
5303 * @pre VOL_LOCK is held
5305 * @post the volume operation info object is detached from the volume object
5307 * @internal volume package internal use only
5310 VDeregisterVolOp_r(Volume * vp)
5312 if (vp->pending_vol_op) {
5313 free(vp->pending_vol_op);
5314 vp->pending_vol_op = NULL;
5318 #endif /* AFS_DEMAND_ATTACH_FS */
5321 * determine whether it is safe to leave a volume online during
5322 * the volume operation described by the vopinfo object.
5324 * @param[in] vp volume object
5325 * @param[in] vopinfo volume operation info object
5327 * @return whether it is safe to leave volume online
5328 * @retval 0 it is NOT SAFE to leave the volume online
5329 * @retval 1 it is safe to leave the volume online during the operation
5332 * @arg VOL_LOCK is held
5333 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5334 * this condition is met)
5336 * @internal volume package internal use only
5339 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5341 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5342 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5343 (vopinfo->com.reason == V_READONLY ||
5344 (!VolumeWriteable(vp) &&
5345 (vopinfo->com.reason == V_CLONE ||
5346 vopinfo->com.reason == V_DUMP)))));
5350 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5353 * @param[in] vp volume object
5354 * @param[in] vopinfo volume operation info object
5356 * @return whether it is safe to leave volume online
5357 * @retval 0 it is NOT SAFE to leave the volume online
5358 * @retval 1 it is safe to leave the volume online during the operation
5359 * @retval -1 unsure; volume header is required in order to know whether or
5360 * not is is safe to leave the volume online
5362 * @pre VOL_LOCK is held
5364 * @internal volume package internal use only
5367 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5369 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5370 * assume that we don't know VolumeWriteable; return -1 if the answer
5371 * depends on VolumeWriteable */
5373 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5376 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5377 vopinfo->com.reason == V_READONLY) {
5381 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5382 (vopinfo->com.reason == V_CLONE ||
5383 vopinfo->com.reason == V_DUMP)) {
5385 /* must know VolumeWriteable */
5392 * determine whether VBUSY should be set during this volume operation.
5394 * @param[in] vp volume object
5395 * @param[in] vopinfo volume operation info object
5397 * @return whether VBUSY should be set
5398 * @retval 0 VBUSY does NOT need to be set
5399 * @retval 1 VBUSY SHOULD be set
5401 * @pre VOL_LOCK is held
5403 * @internal volume package internal use only
5406 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5408 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5409 vopinfo->com.reason == FSYNC_SALVAGE) ||
5410 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5411 (vopinfo->com.reason == V_CLONE ||
5412 vopinfo->com.reason == V_DUMP)));
5416 /***************************************************/
5417 /* online salvager routines */
5418 /***************************************************/
5419 #if defined(AFS_DEMAND_ATTACH_FS)
5422 * offline a volume to let it be salvaged.
5424 * @param[in] vp Volume to offline
5426 * @return whether we offlined the volume successfully
5427 * @retval 0 volume was not offlined
5428 * @retval 1 volume is now offline
5430 * @note This is similar to VCheckOffline, but slightly different. We do not
5431 * deal with vp->goingOffline, and we try to avoid touching the volume
5432 * header except just to set needsSalvaged
5434 * @pre VOL_LOCK held
5435 * @pre vp->nUsers == 0
5436 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5439 VOfflineForSalvage_r(struct Volume *vp)
5443 VCreateReservation_r(vp);
5444 VWaitExclusiveState_r(vp);
5446 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5447 /* Someone's using the volume, or someone got to scheduling the salvage
5448 * before us. I don't think either of these should be possible, as we
5449 * should gain no new heavyweight references while we're trying to
5450 * salvage, but just to be sure... */
5451 VCancelReservation_r(vp);
5455 VChangeState_r(vp, VOL_STATE_OFFLINING);
5459 V_needsSalvaged(vp) = 1;
5460 /* ignore error; updating needsSalvaged is just best effort */
5461 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5463 VCloseVolumeHandles_r(vp);
5465 FreeVolumeHeader(vp);
5467 /* volume has been effectively offlined; we can mark it in the SALVAGING
5468 * state now, which lets FSSYNC give it away */
5469 VChangeState_r(vp, VOL_STATE_SALVAGING);
5471 VCancelReservation_r(vp);
5477 * check whether a salvage needs to be performed on this volume.
5479 * @param[in] vp pointer to volume object
5481 * @return status code
5482 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5483 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5484 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5485 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5486 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5488 * @pre VOL_LOCK is held
5490 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5491 * then a salvage will be requested
5493 * @note this is one of the event handlers called by VCancelReservation_r
5495 * @note the caller must check if the volume needs to be freed after calling
5496 * this; the volume may not have any references or be on any lists after
5497 * we return, and we do not free it
5499 * @see VCancelReservation_r
5501 * @internal volume package internal use only.
5504 VCheckSalvage(Volume * vp)
5506 int ret = VCHECK_SALVAGE_OK;
5508 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5509 if (!vp->salvage.requested) {
5510 return VCHECK_SALVAGE_OK;
5513 return VCHECK_SALVAGE_ASYNC;
5516 /* prevent recursion; some of the code below creates and removes
5517 * lightweight refs, which can call VCheckSalvage */
5518 if (vp->salvage.scheduling) {
5519 return VCHECK_SALVAGE_ASYNC;
5521 vp->salvage.scheduling = 1;
5523 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5524 if (!VOfflineForSalvage_r(vp)) {
5525 vp->salvage.scheduling = 0;
5526 return VCHECK_SALVAGE_FAIL;
5530 if (vp->salvage.requested) {
5531 ret = VScheduleSalvage_r(vp);
5533 vp->salvage.scheduling = 0;
5534 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5539 * request volume salvage.
5541 * @param[out] ec computed client error code
5542 * @param[in] vp volume object pointer
5543 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5544 * @param[in] flags see flags note below
5547 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5548 * not been fully attached
5550 * @pre VOL_LOCK is held.
5552 * @post volume state is changed.
5553 * for fileserver, salvage will be requested once refcount reaches zero.
5555 * @return operation status code
5556 * @retval 0 volume salvage will occur
5557 * @retval 1 volume salvage could not be scheduled
5561 * @note in the fileserver, this call does not synchronously schedule a volume
5562 * salvage. rather, it sets volume state so that when volume refcounts
5563 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5564 * nUsers and nWaiters must be zero.
5566 * @internal volume package internal use only.
5569 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5573 * for DAFS volume utilities that are not supposed to schedule salvages,
5574 * just transition to error state instead
5576 if (!VCanScheduleSalvage()) {
5577 VChangeState_r(vp, VOL_STATE_ERROR);
5582 if (programType != fileServer && !VCanUseFSSYNC()) {
5583 VChangeState_r(vp, VOL_STATE_ERROR);
5588 if (!vp->salvage.requested) {
5589 vp->salvage.requested = 1;
5590 vp->salvage.reason = reason;
5591 vp->stats.last_salvage = FT_ApproxTime();
5593 /* Note that it is not possible for us to reach this point if a
5594 * salvage is already running on this volume (even if the fileserver
5595 * was restarted during the salvage). If a salvage were running, the
5596 * salvager would have write-locked the volume header file, so when
5597 * we tried to lock the volume header, the lock would have failed,
5598 * and we would have failed during attachment prior to calling
5599 * VRequestSalvage. So we know that we can schedule salvages without
5600 * fear of a salvage already running for this volume. */
5602 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5604 /* if we don't need to offline the volume, we can go directly
5605 * to SALVAGING. SALVAGING says the volume is offline and is
5606 * either salvaging or ready to be handed to the salvager.
5607 * SALVAGE_REQ says that we want to salvage the volume, but we
5608 * are waiting for it to go offline first. */
5609 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5610 VChangeState_r(vp, VOL_STATE_SALVAGING);
5612 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5613 if (vp->nUsers == 0) {
5614 /* normally VOfflineForSalvage_r would be called from
5615 * PutVolume et al when nUsers reaches 0, but if
5616 * it's already 0, just do it ourselves, since PutVolume
5617 * isn't going to get called */
5618 VOfflineForSalvage_r(vp);
5621 /* If we are non-fileserver, we're telling the fileserver to
5622 * salvage the vol, so we don't need to give it back separately. */
5623 vp->needsPutBack = 0;
5627 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5629 /* make sure neither VScheduleSalvage_r nor
5630 * VUpdateSalvagePriority_r try to schedule another salvage */
5631 vp->salvage.requested = vp->salvage.scheduled = 0;
5633 VChangeState_r(vp, VOL_STATE_ERROR);
5642 * update salvageserver scheduling priority for a volume.
5644 * @param[in] vp pointer to volume object
5646 * @return operation status
5648 * @retval 1 request denied, or SALVSYNC communications failure
5650 * @pre VOL_LOCK is held.
5652 * @post in-core salvage priority counter is incremented. if at least
5653 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5654 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5655 * to update its priority queue. if no salvage is scheduled,
5656 * this function is a no-op.
5658 * @note DAFS fileserver only
5660 * @note this should be called whenever a VGetVolume fails due to a
5661 * pending salvage request
5663 * @todo should set exclusive state and drop glock around salvsync call
5665 * @internal volume package internal use only.
5668 VUpdateSalvagePriority_r(Volume * vp)
5672 #ifdef SALVSYNC_BUILD_CLIENT
5677 now = FT_ApproxTime();
5679 /* update the salvageserver priority queue occasionally so that
5680 * frequently requested volumes get moved to the head of the queue
5682 if ((vp->salvage.scheduled) &&
5683 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5684 code = SALVSYNC_SalvageVolume(vp->hashid,
5685 VPartitionPath(vp->partition),
5690 vp->stats.last_salvage_req = now;
5691 if (code != SYNC_OK) {
5695 #endif /* SALVSYNC_BUILD_CLIENT */
5700 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5702 /* A couple of little helper functions. These return true if we tried to
5703 * use this mechanism to schedule a salvage, false if we haven't tried.
5704 * If we did try a salvage then the results are contained in code.
5708 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5709 #ifdef SALVSYNC_BUILD_CLIENT
5710 if (VCanUseSALVSYNC()) {
5711 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5712 afs_printable_uint32_lu(vp->hashid), partName);
5714 /* can't use V_id() since there's no guarantee
5715 * we have the disk data header at this point */
5716 *code = SALVSYNC_SalvageVolume(vp->hashid,
5729 try_FSSYNC(Volume *vp, char *partName, int *code) {
5730 #ifdef FSSYNC_BUILD_CLIENT
5731 if (VCanUseFSSYNC()) {
5732 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5733 afs_printable_uint32_lu(vp->hashid), partName);
5736 * If we aren't the fileserver, tell the fileserver the volume
5737 * needs to be salvaged. We could directly tell the
5738 * salvageserver, but the fileserver keeps track of some stats
5739 * related to salvages, and handles some other salvage-related
5740 * complications for us.
5742 *code = FSYNC_VolOp(vp->hashid, partName,
5743 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5746 #endif /* FSSYNC_BUILD_CLIENT */
5751 * schedule a salvage with the salvage server or fileserver.
5753 * @param[in] vp pointer to volume object
5755 * @return operation status
5756 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5757 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5758 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5759 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5760 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5763 * @arg VOL_LOCK is held.
5764 * @arg nUsers and nWaiters should be zero.
5766 * @post salvageserver or fileserver is sent a salvage request
5768 * @note If we are the fileserver, the request will be sent to the salvage
5769 * server over SALVSYNC. If we are not the fileserver, the request will be
5770 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5772 * @note the caller must check if the volume needs to be freed after calling
5773 * this; the volume may not have any references or be on any lists after
5774 * we return, and we do not free it
5778 * @internal volume package internal use only.
5781 VScheduleSalvage_r(Volume * vp)
5783 int ret = VCHECK_SALVAGE_SCHEDULED;
5785 VolState state_save;
5786 VThreadOptions_t * thread_opts;
5789 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5791 if (vp->nWaiters || vp->nUsers) {
5792 return VCHECK_SALVAGE_ASYNC;
5795 /* prevent endless salvage,attach,salvage,attach,... loops */
5796 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5797 return VCHECK_SALVAGE_FAIL;
5801 * don't perform salvsync ops on certain threads
5803 thread_opts = pthread_getspecific(VThread_key);
5804 if (thread_opts == NULL) {
5805 thread_opts = &VThread_defaults;
5807 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5808 return VCHECK_SALVAGE_ASYNC;
5811 if (vp->salvage.scheduled) {
5812 return VCHECK_SALVAGE_SCHEDULED;
5815 VCreateReservation_r(vp);
5816 VWaitExclusiveState_r(vp);
5819 * XXX the scheduling process should really be done asynchronously
5820 * to avoid fssync deadlocks
5822 if (vp->salvage.scheduled) {
5823 ret = VCHECK_SALVAGE_SCHEDULED;
5825 /* if we haven't previously scheduled a salvage, do so now
5827 * set the volume to an exclusive state and drop the lock
5828 * around the SALVSYNC call
5830 strlcpy(partName, vp->partition->name, sizeof(partName));
5831 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5834 opr_Verify(try_SALVSYNC(vp, partName, &code)
5835 || try_FSSYNC(vp, partName, &code));
5838 VChangeState_r(vp, state_save);
5840 if (code == SYNC_OK) {
5841 ret = VCHECK_SALVAGE_SCHEDULED;
5842 vp->salvage.scheduled = 1;
5843 vp->stats.last_salvage_req = FT_ApproxTime();
5844 if (VCanUseSALVSYNC()) {
5845 /* don't record these stats for non-fileservers; let the
5846 * fileserver take care of these */
5847 vp->stats.salvages++;
5848 IncUInt64(&VStats.salvages);
5852 case SYNC_BAD_COMMAND:
5853 case SYNC_COM_ERROR:
5854 ret = VCHECK_SALVAGE_FAIL;
5857 ret = VCHECK_SALVAGE_DENIED;
5858 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5859 "denied\n", afs_printable_uint32_lu(vp->hashid));
5862 ret = VCHECK_SALVAGE_FAIL;
5863 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5864 "failed\n", afs_printable_uint32_lu(vp->hashid));
5867 ret = VCHECK_SALVAGE_FAIL;
5868 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5869 "received unknown protocol error %d\n",
5870 afs_printable_uint32_lu(vp->hashid), code);
5874 if (VCanUseFSSYNC()) {
5875 VChangeState_r(vp, VOL_STATE_ERROR);
5880 /* NB: this is cancelling the reservation we obtained above, but we do
5881 * not call VCancelReservation_r, since that may trigger the vp dtor,
5882 * possibly free'ing the vp. We need to keep the vp around after
5883 * this, as the caller may reference vp without any refs. Instead, it
5884 * is the duty of the caller to inspect 'vp' after we return to see if
5885 * needs to be freed. */
5886 opr_Verify(--vp->nWaiters >= 0);
5889 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5891 #ifdef SALVSYNC_BUILD_CLIENT
5894 * connect to the salvageserver SYNC service.
5896 * @return operation status
5900 * @post connection to salvageserver SYNC service established
5902 * @see VConnectSALV_r
5903 * @see VDisconnectSALV
5904 * @see VReconnectSALV
5911 retVal = VConnectSALV_r();
5917 * connect to the salvageserver SYNC service.
5919 * @return operation status
5923 * @pre VOL_LOCK is held.
5925 * @post connection to salvageserver SYNC service established
5928 * @see VDisconnectSALV_r
5929 * @see VReconnectSALV_r
5930 * @see SALVSYNC_clientInit
5932 * @internal volume package internal use only.
5935 VConnectSALV_r(void)
5937 return SALVSYNC_clientInit();
5941 * disconnect from the salvageserver SYNC service.
5943 * @return operation status
5946 * @pre client should have a live connection to the salvageserver
5948 * @post connection to salvageserver SYNC service destroyed
5950 * @see VDisconnectSALV_r
5952 * @see VReconnectSALV
5955 VDisconnectSALV(void)
5958 VDisconnectSALV_r();
5964 * disconnect from the salvageserver SYNC service.
5966 * @return operation status
5970 * @arg VOL_LOCK is held.
5971 * @arg client should have a live connection to the salvageserver.
5973 * @post connection to salvageserver SYNC service destroyed
5975 * @see VDisconnectSALV
5976 * @see VConnectSALV_r
5977 * @see VReconnectSALV_r
5978 * @see SALVSYNC_clientFinis
5980 * @internal volume package internal use only.
5983 VDisconnectSALV_r(void)
5985 return SALVSYNC_clientFinis();
5989 * disconnect and then re-connect to the salvageserver SYNC service.
5991 * @return operation status
5995 * @pre client should have a live connection to the salvageserver
5997 * @post old connection is dropped, and a new one is established
6000 * @see VDisconnectSALV
6001 * @see VReconnectSALV_r
6004 VReconnectSALV(void)
6008 retVal = VReconnectSALV_r();
6014 * disconnect and then re-connect to the salvageserver SYNC service.
6016 * @return operation status
6021 * @arg VOL_LOCK is held.
6022 * @arg client should have a live connection to the salvageserver.
6024 * @post old connection is dropped, and a new one is established
6026 * @see VConnectSALV_r
6027 * @see VDisconnectSALV
6028 * @see VReconnectSALV
6029 * @see SALVSYNC_clientReconnect
6031 * @internal volume package internal use only.
6034 VReconnectSALV_r(void)
6036 return SALVSYNC_clientReconnect();
6038 #endif /* SALVSYNC_BUILD_CLIENT */
6039 #endif /* AFS_DEMAND_ATTACH_FS */
6042 /***************************************************/
6043 /* FSSYNC routines */
6044 /***************************************************/
6046 /* This must be called by any volume utility which needs to run while the
6047 file server is also running. This is separated from VInitVolumePackage2 so
6048 that a utility can fork--and each of the children can independently
6049 initialize communication with the file server */
6050 #ifdef FSSYNC_BUILD_CLIENT
6052 * connect to the fileserver SYNC service.
6054 * @return operation status
6059 * @arg VInit must equal 2.
6060 * @arg Program Type must not be fileserver or salvager.
6062 * @post connection to fileserver SYNC service established
6065 * @see VDisconnectFS
6066 * @see VChildProcReconnectFS
6073 retVal = VConnectFS_r();
6079 * connect to the fileserver SYNC service.
6081 * @return operation status
6086 * @arg VInit must equal 2.
6087 * @arg Program Type must not be fileserver or salvager.
6088 * @arg VOL_LOCK is held.
6090 * @post connection to fileserver SYNC service established
6093 * @see VDisconnectFS_r
6094 * @see VChildProcReconnectFS_r
6096 * @internal volume package internal use only.
6102 opr_Assert((VInit == 2) &&
6103 (programType != fileServer) &&
6104 (programType != salvager));
6105 rc = FSYNC_clientInit();
6113 * disconnect from the fileserver SYNC service.
6116 * @arg client should have a live connection to the fileserver.
6117 * @arg VOL_LOCK is held.
6118 * @arg Program Type must not be fileserver or salvager.
6120 * @post connection to fileserver SYNC service destroyed
6122 * @see VDisconnectFS
6124 * @see VChildProcReconnectFS_r
6126 * @internal volume package internal use only.
6129 VDisconnectFS_r(void)
6131 opr_Assert((programType != fileServer) &&
6132 (programType != salvager));
6133 FSYNC_clientFinis();
6138 * disconnect from the fileserver SYNC service.
6141 * @arg client should have a live connection to the fileserver.
6142 * @arg Program Type must not be fileserver or salvager.
6144 * @post connection to fileserver SYNC service destroyed
6146 * @see VDisconnectFS_r
6148 * @see VChildProcReconnectFS
6159 * connect to the fileserver SYNC service from a child process following a fork.
6161 * @return operation status
6166 * @arg VOL_LOCK is held.
6167 * @arg current FSYNC handle is shared with a parent process
6169 * @post current FSYNC handle is discarded and a new connection to the
6170 * fileserver SYNC service is established
6172 * @see VChildProcReconnectFS
6174 * @see VDisconnectFS_r
6176 * @internal volume package internal use only.
6179 VChildProcReconnectFS_r(void)
6181 return FSYNC_clientChildProcReconnect();
6185 * connect to the fileserver SYNC service from a child process following a fork.
6187 * @return operation status
6191 * @pre current FSYNC handle is shared with a parent process
6193 * @post current FSYNC handle is discarded and a new connection to the
6194 * fileserver SYNC service is established
6196 * @see VChildProcReconnectFS_r
6198 * @see VDisconnectFS
6201 VChildProcReconnectFS(void)
6205 ret = VChildProcReconnectFS_r();
6209 #endif /* FSSYNC_BUILD_CLIENT */
6212 /***************************************************/
6213 /* volume bitmap routines */
6214 /***************************************************/
6217 * Grow the bitmap by the defined increment
6220 VGrowBitmap(struct vnodeIndex *index)
6224 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6225 osi_Assert(bp != NULL);
6227 bp += index->bitmapSize;
6228 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6229 index->bitmapOffset = index->bitmapSize;
6230 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6236 * allocate a vnode bitmap number for the vnode
6238 * @param[out] ec error code
6239 * @param[in] vp volume object pointer
6240 * @param[in] index vnode index number for the vnode
6241 * @param[in] flags flag values described in note
6243 * @note for DAFS, flags parameter controls locking behavior.
6244 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6245 * will create a reservation and block on any other exclusive
6246 * operations. Otherwise, this function assumes the caller
6247 * already has exclusive access to vp, and we just change the
6250 * @pre VOL_LOCK held
6252 * @return bit number allocated
6258 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6259 struct vnodeIndex *index, int flags)
6263 #ifdef AFS_DEMAND_ATTACH_FS
6264 VolState state_save;
6265 #endif /* AFS_DEMAND_ATTACH_FS */
6269 /* This test is probably redundant */
6270 if (!VolumeWriteable(vp)) {
6271 *ec = (bit32) VREADONLY;
6275 #ifdef AFS_DEMAND_ATTACH_FS
6276 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6277 VCreateReservation_r(vp);
6278 VWaitExclusiveState_r(vp);
6280 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6281 #endif /* AFS_DEMAND_ATTACH_FS */
6284 if ((programType == fileServer) && !index->bitmap) {
6286 #ifndef AFS_DEMAND_ATTACH_FS
6287 /* demand attach fs uses the volume state to avoid races.
6288 * specialStatus field is not used at all */
6290 if (vp->specialStatus == VBUSY) {
6291 if (vp->goingOffline) { /* vos dump waiting for the volume to
6292 * go offline. We probably come here
6293 * from AddNewReadableResidency */
6296 while (vp->specialStatus == VBUSY) {
6297 #ifdef AFS_PTHREAD_ENV
6301 #else /* !AFS_PTHREAD_ENV */
6303 #endif /* !AFS_PTHREAD_ENV */
6307 #endif /* !AFS_DEMAND_ATTACH_FS */
6309 if (!index->bitmap) {
6310 #ifndef AFS_DEMAND_ATTACH_FS
6311 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6312 #endif /* AFS_DEMAND_ATTACH_FS */
6313 for (i = 0; i < nVNODECLASSES; i++) {
6314 VGetBitmap_r(ec, vp, i);
6316 #ifdef AFS_DEMAND_ATTACH_FS
6317 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6318 #else /* AFS_DEMAND_ATTACH_FS */
6319 DeleteVolumeFromHashTable(vp);
6320 vp->shuttingDown = 1; /* Let who has it free it. */
6321 vp->specialStatus = 0;
6322 #endif /* AFS_DEMAND_ATTACH_FS */
6326 #ifndef AFS_DEMAND_ATTACH_FS
6328 vp->specialStatus = 0; /* Allow others to have access. */
6329 #endif /* AFS_DEMAND_ATTACH_FS */
6332 #endif /* BITMAP_LATER */
6334 #ifdef AFS_DEMAND_ATTACH_FS
6336 #endif /* AFS_DEMAND_ATTACH_FS */
6337 bp = index->bitmap + index->bitmapOffset;
6338 ep = index->bitmap + index->bitmapSize;
6340 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6342 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6345 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6347 ret = ((bp - index->bitmap) * 8 + o);
6348 #ifdef AFS_DEMAND_ATTACH_FS
6350 #endif /* AFS_DEMAND_ATTACH_FS */
6353 bp += sizeof(bit32) /* i.e. 4 */ ;
6355 /* No bit map entry--must grow bitmap */
6357 bp = index->bitmap + index->bitmapOffset;
6359 ret = index->bitmapOffset * 8;
6360 #ifdef AFS_DEMAND_ATTACH_FS
6362 #endif /* AFS_DEMAND_ATTACH_FS */
6365 #ifdef AFS_DEMAND_ATTACH_FS
6366 VChangeState_r(vp, state_save);
6367 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6368 VCancelReservation_r(vp);
6370 #endif /* AFS_DEMAND_ATTACH_FS */
6375 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6379 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6385 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6386 unsigned bitNumber, int flags)
6388 unsigned int offset;
6392 #ifdef AFS_DEMAND_ATTACH_FS
6393 if (flags & VOL_FREE_BITMAP_WAIT) {
6394 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6395 * state, so ensure we're not in an exclusive volume state when we update
6397 VCreateReservation_r(vp);
6398 VWaitExclusiveState_r(vp);
6405 #endif /* BITMAP_LATER */
6407 offset = bitNumber >> 3;
6408 if (offset >= index->bitmapSize) {
6412 if (offset < index->bitmapOffset)
6413 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6414 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6417 #ifdef AFS_DEMAND_ATTACH_FS
6418 VCancelReservation_r(vp);
6420 return; /* make the compiler happy for non-DAFS */
6424 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6428 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6432 /* this function will drop the glock internally.
6433 * for old pthread fileservers, this is safe thanks to vbusy.
6435 * for demand attach fs, caller must have already called
6436 * VCreateReservation_r and VWaitExclusiveState_r */
6438 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6440 StreamHandle_t *file;
6441 afs_sfsize_t nVnodes, size;
6442 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6443 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6444 struct VnodeDiskObject *vnode;
6445 unsigned int unique = 0;
6449 #endif /* BITMAP_LATER */
6450 #ifdef AFS_DEMAND_ATTACH_FS
6451 VolState state_save;
6452 #endif /* AFS_DEMAND_ATTACH_FS */
6456 #ifdef AFS_DEMAND_ATTACH_FS
6457 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6458 #endif /* AFS_DEMAND_ATTACH_FS */
6461 fdP = IH_OPEN(vip->handle);
6462 opr_Assert(fdP != NULL);
6463 file = FDH_FDOPEN(fdP, "r");
6464 opr_Assert(file != NULL);
6465 vnode = malloc(vcp->diskSize);
6466 opr_Assert(vnode != NULL);
6467 size = OS_SIZE(fdP->fd_fd);
6468 opr_Assert(size != -1);
6469 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6471 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6472 * a few files can be created in this volume,
6473 * the whole thing is rounded up to nearest 4
6474 * bytes, because the bit map allocator likes
6477 BitMap = (byte *) calloc(1, vip->bitmapSize);
6478 opr_Assert(BitMap != NULL);
6479 #else /* BITMAP_LATER */
6480 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6481 opr_Assert(vip->bitmap != NULL);
6482 vip->bitmapOffset = 0;
6483 #endif /* BITMAP_LATER */
6484 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6486 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6487 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6489 if (vnode->type != vNull) {
6490 if (vnode->vnodeMagic != vcp->magic) {
6491 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6496 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6497 #else /* BITMAP_LATER */
6498 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6499 #endif /* BITMAP_LATER */
6500 if (unique <= vnode->uniquifier)
6501 unique = vnode->uniquifier + 1;
6503 #ifndef AFS_PTHREAD_ENV
6504 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6507 #endif /* !AFS_PTHREAD_ENV */
6510 if (vp->nextVnodeUnique < unique) {
6511 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6514 /* Paranoia, partly justified--I think fclose after fdopen
6515 * doesn't seem to close fd. In any event, the documentation
6516 * doesn't specify, so it's safer to close it twice.
6524 /* There may have been a racing condition with some other thread, both
6525 * creating the bitmaps for this volume. If the other thread was faster
6526 * the pointer to bitmap should already be filled and we can free ours.
6528 if (vip->bitmap == NULL) {
6529 vip->bitmap = BitMap;
6530 vip->bitmapOffset = 0;
6533 #endif /* BITMAP_LATER */
6534 #ifdef AFS_DEMAND_ATTACH_FS
6535 VChangeState_r(vp, state_save);
6536 #endif /* AFS_DEMAND_ATTACH_FS */
6540 /***************************************************/
6541 /* Volume Path and Volume Number utility routines */
6542 /***************************************************/
6545 * find the first occurrence of a volume header file and return the path.
6547 * @param[out] ec outbound error code
6548 * @param[in] volumeId volume id to find
6549 * @param[out] partitionp pointer to disk partition path string
6550 * @param[out] namep pointer to volume header file name string
6552 * @post path to first occurrence of volume header is returned in partitionp
6553 * and namep, or ec is set accordingly.
6555 * @warning this function is NOT re-entrant -- partitionp and namep point to
6556 * static data segments
6558 * @note if a volume utility inadvertently leaves behind a stale volume header
6559 * on a vice partition, it is possible for callers to get the wrong one,
6560 * depending on the order of the disk partition linked list.
6564 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6566 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6567 char path[VMAXPATHLEN];
6569 struct DiskPartition64 *dp;
6572 name[0] = OS_DIRSEPC;
6573 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6574 afs_printable_uint32_lu(volumeId));
6575 for (dp = DiskPartitionList; dp; dp = dp->next) {
6576 struct afs_stat_st status;
6577 strcpy(path, VPartitionPath(dp));
6579 if (afs_stat(path, &status) == 0) {
6580 strcpy(partition, dp->name);
6587 *partitionp = *namep = NULL;
6589 *partitionp = partition;
6595 * extract a volume number from a volume header filename string.
6597 * @param[in] name volume header filename string
6599 * @return volume number
6601 * @note the string must be of the form VFORMAT. the only permissible
6602 * deviation is a leading OS_DIRSEPC character.
6607 VolumeNumber(char *name)
6609 if (*name == OS_DIRSEPC)
6611 return strtoul(name + 1, NULL, 10);
6615 * compute the volume header filename.
6617 * @param[in] volumeId
6619 * @return volume header filename
6621 * @post volume header filename string is constructed
6623 * @warning this function is NOT re-entrant -- the returned string is
6624 * stored in a static char array. see VolumeExternalName_r
6625 * for a re-entrant equivalent.
6627 * @see VolumeExternalName_r
6629 * @deprecated due to the above re-entrancy warning, this interface should
6630 * be considered deprecated. Please use VolumeExternalName_r
6634 VolumeExternalName(VolumeId volumeId)
6636 static char name[VMAXPATHLEN];
6637 snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6642 * compute the volume header filename.
6644 * @param[in] volumeId
6645 * @param[inout] name array in which to store filename
6646 * @param[in] len length of name array
6648 * @return result code from afs_snprintf
6650 * @see VolumeExternalName
6653 * @note re-entrant equivalent of VolumeExternalName
6656 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6658 return snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6662 /***************************************************/
6663 /* Volume Usage Statistics routines */
6664 /***************************************************/
6666 #define OneDay (86400) /* 24 hours' worth of seconds */
6669 Midnight(time_t t) {
6670 struct tm local, *l;
6673 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6674 l = localtime_r(&t, &local);
6680 /* the following is strictly speaking problematic on the
6681 switching day to daylight saving time, after the switch,
6682 as tm_isdst does not match. Similarly, on the looong day when
6683 switching back the OneDay check will not do what naively expected!
6684 The effects are minor, though, and more a matter of interpreting
6686 #ifndef AFS_PTHREAD_ENV
6689 local.tm_hour = local.tm_min=local.tm_sec = 0;
6690 midnight = mktime(&local);
6691 if (midnight != (time_t) -1) return(midnight);
6693 return( (t/OneDay)*OneDay );
6697 /*------------------------------------------------------------------------
6698 * [export] VAdjustVolumeStatistics
6701 * If we've passed midnight, we need to update all the day use
6702 * statistics as well as zeroing the detailed volume statistics
6703 * (if we are implementing them).
6706 * vp : Pointer to the volume structure describing the lucky
6707 * volume being considered for update.
6713 * Nothing interesting.
6717 *------------------------------------------------------------------------*/
6720 VAdjustVolumeStatistics_r(Volume * vp)
6722 unsigned int now = FT_ApproxTime();
6724 if (now - V_dayUseDate(vp) > OneDay) {
6727 ndays = (now - V_dayUseDate(vp)) / OneDay;
6728 for (i = 6; i > ndays - 1; i--)
6729 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6730 for (i = 0; i < ndays - 1 && i < 7; i++)
6731 V_weekUse(vp)[i] = 0;
6733 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6735 V_dayUseDate(vp) = Midnight(now);
6738 * All we need to do is bzero the entire VOL_STATS_BYTES of
6739 * the detailed volume statistics area.
6741 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6744 /*It's been more than a day of collection */
6746 * Always return happily.
6749 } /*VAdjustVolumeStatistics */
6752 VAdjustVolumeStatistics(Volume * vp)
6756 retVal = VAdjustVolumeStatistics_r(vp);
6762 VBumpVolumeUsage_r(Volume * vp)
6764 unsigned int now = FT_ApproxTime();
6765 V_accessDate(vp) = now;
6766 if (now - V_dayUseDate(vp) > OneDay)
6767 VAdjustVolumeStatistics_r(vp);
6769 * Save the volume header image to disk after a threshold of bumps to dayUse,
6770 * at most every usage_rate_limit seconds.
6773 vp->usage_bumps_outstanding++;
6774 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6775 && vp->usage_bumps_next_write <= now) {
6777 vp->usage_bumps_outstanding = 0;
6778 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6779 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6784 VBumpVolumeUsage(Volume * vp)
6787 VBumpVolumeUsage_r(vp);
6792 VSetDiskUsage_r(void)
6794 #ifndef AFS_DEMAND_ATTACH_FS
6795 static int FifteenMinuteCounter = 0;
6799 /* NOTE: Don't attempt to access the partitions list until the
6800 * initialization level indicates that all volumes are attached,
6801 * which implies that all partitions are initialized. */
6802 #ifdef AFS_PTHREAD_ENV
6803 VOL_CV_WAIT(&vol_vinit_cond);
6804 #else /* AFS_PTHREAD_ENV */
6806 #endif /* AFS_PTHREAD_ENV */
6809 VResetDiskUsage_r();
6811 #ifndef AFS_DEMAND_ATTACH_FS
6812 if (++FifteenMinuteCounter == 3) {
6813 FifteenMinuteCounter = 0;
6816 #endif /* !AFS_DEMAND_ATTACH_FS */
6828 /***************************************************/
6829 /* Volume Update List routines */
6830 /***************************************************/
6832 /* The number of minutes that a volume hasn't been updated before the
6833 * "Dont salvage" flag in the volume header will be turned on */
6834 #define SALVAGE_INTERVAL (10*60)
6839 * volume update list functionality has been moved into the VLRU
6840 * the DONT_SALVAGE flag is now set during VLRU demotion
6843 #ifndef AFS_DEMAND_ATTACH_FS
6844 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6845 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6846 static int updateSize = 0; /* number of entries possible */
6847 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6848 #endif /* !AFS_DEMAND_ATTACH_FS */
6851 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6854 vp->updateTime = FT_ApproxTime();
6855 if (V_dontSalvage(vp) == 0)
6857 V_dontSalvage(vp) = 0;
6858 VSyncVolume_r(ec, vp, 0);
6859 #ifdef AFS_DEMAND_ATTACH_FS
6860 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6861 #else /* !AFS_DEMAND_ATTACH_FS */
6864 if (UpdateList == NULL) {
6865 updateSize = UPDATE_LIST_SIZE;
6866 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6868 if (nUpdatedVolumes == updateSize) {
6870 if (updateSize > 524288) {
6871 Log("warning: there is likely a bug in the volume update scanner\n");
6874 UpdateList = realloc(UpdateList,
6875 sizeof(VolumeId) * updateSize);
6878 opr_Assert(UpdateList != NULL);
6879 UpdateList[nUpdatedVolumes++] = V_id(vp);
6880 #endif /* !AFS_DEMAND_ATTACH_FS */
6883 #ifndef AFS_DEMAND_ATTACH_FS
6885 VScanUpdateList(void)
6890 afs_uint32 now = FT_ApproxTime();
6891 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6892 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6894 UpdateList[i - gap] = UpdateList[i];
6896 /* XXX this routine needlessly messes up the Volume LRU by
6897 * breaking the LRU temporal-locality assumptions.....
6898 * we should use a special volume header allocator here */
6899 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6902 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6903 V_dontSalvage(vp) = DONT_SALVAGE;
6904 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6912 #ifndef AFS_PTHREAD_ENV
6914 #endif /* !AFS_PTHREAD_ENV */
6916 nUpdatedVolumes -= gap;
6918 #endif /* !AFS_DEMAND_ATTACH_FS */
6921 /***************************************************/
6922 /* Volume LRU routines */
6923 /***************************************************/
6928 * with demand attach fs, we attempt to soft detach(1)
6929 * volumes which have not been accessed in a long time
6930 * in order to speed up fileserver shutdown
6932 * (1) by soft detach we mean a process very similar
6933 * to VOffline, except the final state of the
6934 * Volume will be VOL_STATE_PREATTACHED, instead
6935 * of the usual VOL_STATE_UNATTACHED
6937 #ifdef AFS_DEMAND_ATTACH_FS
6939 /* implementation is reminiscent of a generational GC
6941 * queue 0 is newly attached volumes. this queue is
6942 * sorted by attach timestamp
6944 * queue 1 is volumes that have been around a bit
6945 * longer than queue 0. this queue is sorted by
6948 * queue 2 is volumes tha have been around the longest.
6949 * this queue is unsorted
6951 * queue 3 is volumes that have been marked as
6952 * candidates for soft detachment. this queue is
6955 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6956 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6959 * definition of a VLRU queue.
6962 volatile struct rx_queue q;
6969 * main VLRU data structure.
6972 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6975 /** time interval (in seconds) between promotion passes for
6976 * each young generation queue. */
6977 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6979 /** time interval (in seconds) between soft detach candidate
6980 * scans for each generation queue.
6982 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6983 * we perform a soft detach pass. */
6984 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6986 /* scheduler state */
6987 int next_idx; /**< next queue to receive attention */
6988 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6989 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6991 int scanner_state; /**< state of scanner thread */
6992 pthread_cond_t cv; /**< state transition CV */
6995 /** global VLRU state */
6996 static struct VLRU volume_LRU;
6999 * defined states for VLRU scanner thread.
7002 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7003 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7004 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7005 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7006 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7007 } vlru_thread_state_t;
7009 /* vlru disk data header stuff */
7010 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7011 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7013 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7014 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7017 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7018 * soft detachment. */
7019 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7021 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7022 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7024 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7025 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7027 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7028 static afs_uint32 VLRU_enabled = 1;
7030 /* queue synchronization routines */
7031 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7032 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7033 static void VLRU_Wait_r(struct VLRU_q * q);
7036 * set VLRU subsystem tunable parameters.
7038 * @param[in] option tunable option to modify
7039 * @param[in] val new value for tunable parameter
7041 * @pre @c VInitVolumePackage2 has not yet been called.
7043 * @post tunable parameter is modified
7047 * @note valid option parameters are:
7048 * @arg @c VLRU_SET_THRESH
7049 * set the period of inactivity after which
7050 * volumes are eligible for soft detachment
7051 * @arg @c VLRU_SET_INTERVAL
7052 * set the time interval between calls
7053 * to the volume LRU "garbage collector"
7054 * @arg @c VLRU_SET_MAX
7055 * set the max number of volumes to deallocate
7059 VLRU_SetOptions(int option, afs_uint32 val)
7061 if (option == VLRU_SET_THRESH) {
7062 VLRU_offline_thresh = val;
7063 } else if (option == VLRU_SET_INTERVAL) {
7064 VLRU_offline_interval = val;
7065 } else if (option == VLRU_SET_MAX) {
7066 VLRU_offline_max = val;
7067 } else if (option == VLRU_SET_ENABLED) {
7070 VLRU_ComputeConstants();
7074 * compute VLRU internal timing parameters.
7076 * @post VLRU scanner thread internal timing parameters are computed
7078 * @note computes internal timing parameters based upon user-modifiable
7079 * tunable parameters.
7083 * @internal volume package internal use only.
7086 VLRU_ComputeConstants(void)
7088 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7090 /* compute the candidate scan interval */
7091 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7093 /* compute the promotion intervals */
7094 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7095 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7098 /* compute the gen 0 scan interval */
7099 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7101 /* compute the gen 0 scan interval */
7102 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7107 * initialize VLRU subsystem.
7109 * @pre this function has not yet been called
7111 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7115 * @internal volume package internal use only.
7121 pthread_attr_t attrs;
7124 if (!VLRU_enabled) {
7125 Log("VLRU: disabled\n");
7129 /* initialize each of the VLRU queues */
7130 for (i = 0; i < VLRU_QUEUES; i++) {
7131 queue_Init(&volume_LRU.q[i]);
7132 volume_LRU.q[i].len = 0;
7133 volume_LRU.q[i].busy = 0;
7134 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7137 /* setup the timing constants */
7138 VLRU_ComputeConstants();
7140 /* XXX put inside LogLevel check? */
7141 Log("VLRU: starting scanner with the following configuration parameters:\n");
7142 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7143 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7144 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7145 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7146 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7147 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7149 /* start up the VLRU scanner */
7150 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7151 if (programType == fileServer) {
7152 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7153 opr_Verify(pthread_attr_init(&attrs) == 0);
7154 opr_Verify(pthread_attr_setdetachstate(&attrs,
7155 PTHREAD_CREATE_DETACHED) == 0);
7156 opr_Verify(pthread_create(&tid, &attrs,
7157 &VLRU_ScannerThread, NULL) == 0);
7162 * initialize the VLRU-related fields of a newly allocated volume object.
7164 * @param[in] vp pointer to volume object
7167 * @arg @c VOL_LOCK is held.
7168 * @arg volume object is not on a VLRU queue.
7170 * @post VLRU fields are initialized to indicate that volume object is not
7171 * currently registered with the VLRU subsystem
7175 * @internal volume package interal use only.
7178 VLRU_Init_Node_r(Volume * vp)
7183 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7184 vp->vlru.idx = VLRU_QUEUE_INVALID;
7188 * add a volume object to a VLRU queue.
7190 * @param[in] vp pointer to volume object
7193 * @arg @c VOL_LOCK is held.
7194 * @arg caller MUST hold a lightweight ref on @p vp.
7195 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7197 * @post the volume object is added to the appropriate VLRU queue
7199 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7200 * then the volume is added to that queue. Otherwise, the value
7201 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7202 * volume is added to the NEW generation queue.
7204 * @note @c VOL_LOCK may be dropped internally
7206 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7207 * during the add operation, and is restored to the previous
7208 * state prior to return.
7212 * @internal volume package internal use only.
7215 VLRU_Add_r(Volume * vp)
7218 VolState state_save;
7223 if (queue_IsOnQueue(&vp->vlru))
7226 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7229 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7230 idx = VLRU_QUEUE_NEW;
7233 VLRU_Wait_r(&volume_LRU.q[idx]);
7235 /* repeat check since VLRU_Wait_r may have dropped
7237 if (queue_IsNotOnQueue(&vp->vlru)) {
7239 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7240 volume_LRU.q[idx].len++;
7241 V_attachFlags(vp) |= VOL_ON_VLRU;
7242 vp->stats.last_promote = FT_ApproxTime();
7245 VChangeState_r(vp, state_save);
7249 * delete a volume object from a VLRU queue.
7251 * @param[in] vp pointer to volume object
7254 * @arg @c VOL_LOCK is held.
7255 * @arg caller MUST hold a lightweight ref on @p vp.
7256 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7258 * @post volume object is removed from the VLRU queue
7260 * @note @c VOL_LOCK may be dropped internally
7264 * @todo We should probably set volume state to something exlcusive
7265 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7267 * @internal volume package internal use only.
7270 VLRU_Delete_r(Volume * vp)
7277 if (queue_IsNotOnQueue(&vp->vlru))
7283 if (idx == VLRU_QUEUE_INVALID)
7285 VLRU_Wait_r(&volume_LRU.q[idx]);
7286 } while (idx != vp->vlru.idx);
7288 /* now remove from the VLRU and update
7289 * the appropriate counter */
7290 queue_Remove(&vp->vlru);
7291 volume_LRU.q[idx].len--;
7292 vp->vlru.idx = VLRU_QUEUE_INVALID;
7293 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7297 * tell the VLRU subsystem that a volume was just accessed.
7299 * @param[in] vp pointer to volume object
7302 * @arg @c VOL_LOCK is held
7303 * @arg caller MUST hold a lightweight ref on @p vp
7304 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7306 * @post volume VLRU access statistics are updated. If the volume was on
7307 * the VLRU soft detach candidate queue, it is moved to the NEW
7310 * @note @c VOL_LOCK may be dropped internally
7314 * @internal volume package internal use only.
7317 VLRU_UpdateAccess_r(Volume * vp)
7319 Volume * rvp = NULL;
7324 if (queue_IsNotOnQueue(&vp->vlru))
7327 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7329 /* update the access timestamp */
7330 vp->stats.last_get = FT_ApproxTime();
7333 * if the volume is on the soft detach candidate
7334 * list, we need to safely move it back to a
7335 * regular generation. this has to be done
7336 * carefully so we don't race against the scanner
7340 /* if this volume is on the soft detach candidate queue,
7341 * then grab exclusive access to the necessary queues */
7342 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7344 VCreateReservation_r(rvp);
7346 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7347 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7348 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7349 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7352 /* make sure multiple threads don't race to update */
7353 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7354 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7358 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7359 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7360 VCancelReservation_r(rvp);
7365 * switch a volume between two VLRU queues.
7367 * @param[in] vp pointer to volume object
7368 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7369 * @param[in] append controls whether the volume will be appended or
7370 * prepended to the queue. A nonzero value means it will
7371 * be appended; zero means it will be prepended.
7373 * @pre The new (and old, if applicable) queue(s) must either be owned
7374 * exclusively by the calling thread for asynchronous manipulation,
7375 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7376 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7377 * for further details of the queue asynchronous processing mechanism.
7379 * @post If the volume object was already on a VLRU queue, it is
7380 * removed from the queue. Depending on the value of the append
7381 * parameter, the volume object is either appended or prepended
7382 * to the VLRU queue referenced by the new_idx parameter.
7386 * @see VLRU_BeginExclusive_r
7387 * @see VLRU_EndExclusive_r
7390 * @internal volume package internal use only.
7393 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7395 if (queue_IsNotOnQueue(&vp->vlru))
7398 queue_Remove(&vp->vlru);
7399 volume_LRU.q[vp->vlru.idx].len--;
7401 /* put the volume back on the correct generational queue */
7403 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7405 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7408 volume_LRU.q[new_idx].len++;
7409 vp->vlru.idx = new_idx;
7413 * VLRU background thread.
7415 * The VLRU Scanner Thread is responsible for periodically scanning through
7416 * each VLRU queue looking for volumes which should be moved to another
7417 * queue, or soft detached.
7419 * @param[in] args unused thread arguments parameter
7421 * @return unused thread return value
7422 * @retval NULL always
7424 * @internal volume package internal use only.
7427 VLRU_ScannerThread(void * args)
7429 afs_uint32 now, min_delay, delay;
7430 int i, min_idx, min_op, overdue, state;
7432 /* set t=0 for promotion cycle to be
7433 * fileserver startup */
7434 now = FT_ApproxTime();
7435 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7436 volume_LRU.last_promotion[i] = now;
7439 /* don't start the scanner until VLRU_offline_thresh
7440 * plus a small delay for VInitVolumePackage2 to finish
7443 sleep(VLRU_offline_thresh + 60);
7445 /* set t=0 for scan cycle to be now */
7446 now = FT_ApproxTime();
7447 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7448 volume_LRU.last_scan[i] = now;
7452 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7453 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7456 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7457 /* check to see if we've been asked to pause */
7458 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7459 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7460 CV_BROADCAST(&volume_LRU.cv);
7462 VOL_CV_WAIT(&volume_LRU.cv);
7463 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7466 /* scheduling can happen outside the glock */
7469 /* figure out what is next on the schedule */
7471 /* figure out a potential schedule for the new generation first */
7473 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7476 if (min_delay > volume_LRU.scan_interval[0]) {
7477 /* unsigned overflow -- we're overdue to run this scan */
7482 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7484 i = VLRU_QUEUE_CANDIDATE;
7485 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7486 if (delay < min_delay) {
7490 if (delay > volume_LRU.scan_interval[i]) {
7491 /* unsigned overflow -- we're overdue to run this scan */
7498 /* if we're still not overdue for something, figure out schedules for promotions */
7499 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7500 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7501 if (delay < min_delay) {
7506 if (delay > volume_LRU.promotion_interval[i]) {
7507 /* unsigned overflow -- we're overdue to run this promotion */
7516 /* sleep as needed */
7521 /* do whatever is next */
7524 VLRU_Promote_r(min_idx);
7525 VLRU_Demote_r(min_idx+1);
7527 VLRU_Scan_r(min_idx);
7529 now = FT_ApproxTime();
7532 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7534 /* signal that scanner is down */
7535 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7536 CV_BROADCAST(&volume_LRU.cv);
7542 * promote volumes from one VLRU generation to the next.
7544 * This routine scans a VLRU generation looking for volumes which are
7545 * eligible to be promoted to the next generation. All volumes which
7546 * meet the eligibility requirement are promoted.
7548 * Promotion eligibility is based upon meeting both of the following
7551 * @arg The volume has been accessed since the last promotion:
7552 * @c (vp->stats.last_get >= vp->stats.last_promote)
7553 * @arg The last promotion occurred at least
7554 * @c volume_LRU.promotion_interval[idx] seconds ago
7556 * As a performance optimization, promotions are "globbed". In other
7557 * words, we promote arbitrarily large contiguous sublists of elements
7560 * @param[in] idx VLRU queue index to scan
7564 * @internal VLRU internal use only.
7567 VLRU_Promote_r(int idx)
7569 int len, chaining, promote;
7570 afs_uint32 now, thresh;
7571 struct rx_queue *qp, *nqp;
7572 Volume * vp, *start = NULL, *end = NULL;
7574 /* get exclusive access to two chains, and drop the glock */
7575 VLRU_Wait_r(&volume_LRU.q[idx]);
7576 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7577 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7578 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7581 thresh = volume_LRU.promotion_interval[idx];
7582 now = FT_ApproxTime();
7585 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7586 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7587 promote = (((vp->stats.last_promote + thresh) <= now) &&
7588 (vp->stats.last_get >= vp->stats.last_promote));
7596 /* promote and prepend chain */
7597 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7611 /* promote and prepend */
7612 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7616 volume_LRU.q[idx].len -= len;
7617 volume_LRU.q[idx+1].len += len;
7620 /* release exclusive access to the two chains */
7622 volume_LRU.last_promotion[idx] = now;
7623 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7624 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7627 /* run the demotions */
7629 VLRU_Demote_r(int idx)
7632 int len, chaining, demote;
7633 afs_uint32 now, thresh;
7634 struct rx_queue *qp, *nqp;
7635 Volume * vp, *start = NULL, *end = NULL;
7636 Volume ** salv_flag_vec = NULL;
7637 int salv_vec_offset = 0;
7639 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7641 /* get exclusive access to two chains, and drop the glock */
7642 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7643 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7644 VLRU_Wait_r(&volume_LRU.q[idx]);
7645 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7648 /* no big deal if this allocation fails */
7649 if (volume_LRU.q[idx].len) {
7650 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7653 now = FT_ApproxTime();
7654 thresh = volume_LRU.promotion_interval[idx-1];
7657 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7658 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7659 demote = (((vp->stats.last_promote + thresh) <= now) &&
7660 (vp->stats.last_get < (now - thresh)));
7662 /* we now do volume update list DONT_SALVAGE flag setting during
7663 * demotion passes */
7664 if (salv_flag_vec &&
7665 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7667 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7668 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7669 salv_flag_vec[salv_vec_offset++] = vp;
7670 VCreateReservation_r(vp);
7679 /* demote and append chain */
7680 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7694 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7698 volume_LRU.q[idx].len -= len;
7699 volume_LRU.q[idx-1].len += len;
7702 /* release exclusive access to the two chains */
7704 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7705 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7707 /* now go back and set the DONT_SALVAGE flags as appropriate */
7708 if (salv_flag_vec) {
7710 for (i = 0; i < salv_vec_offset; i++) {
7711 vp = salv_flag_vec[i];
7712 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7713 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7714 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7717 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7718 V_dontSalvage(vp) = DONT_SALVAGE;
7719 VUpdateVolume_r(&ec, vp, 0);
7723 VCancelReservation_r(vp);
7725 free(salv_flag_vec);
7729 /* run a pass of the VLRU GC scanner */
7731 VLRU_Scan_r(int idx)
7733 afs_uint32 now, thresh;
7734 struct rx_queue *qp, *nqp;
7738 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7740 /* gain exclusive access to the idx VLRU */
7741 VLRU_Wait_r(&volume_LRU.q[idx]);
7742 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7744 if (idx != VLRU_QUEUE_CANDIDATE) {
7745 /* gain exclusive access to the candidate VLRU */
7746 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7747 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7750 now = FT_ApproxTime();
7751 thresh = now - VLRU_offline_thresh;
7753 /* perform candidate selection and soft detaching */
7754 if (idx == VLRU_QUEUE_CANDIDATE) {
7755 /* soft detach some volumes from the candidate pool */
7759 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7760 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7761 if (i >= VLRU_offline_max) {
7764 /* check timestamp to see if it's a candidate for soft detaching */
7765 if (vp->stats.last_get <= thresh) {
7767 if (VCheckSoftDetach(vp, thresh))
7773 /* scan for volumes to become soft detach candidates */
7774 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7775 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7777 /* check timestamp to see if it's a candidate for soft detaching */
7778 if (vp->stats.last_get <= thresh) {
7779 VCheckSoftDetachCandidate(vp, thresh);
7782 if (!(i&0x7f)) { /* lock coarsening optimization */
7790 /* relinquish exclusive access to the VLRU chains */
7794 volume_LRU.last_scan[idx] = now;
7795 if (idx != VLRU_QUEUE_CANDIDATE) {
7796 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7798 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7801 /* check whether volume is safe to soft detach
7802 * caller MUST NOT hold a ref count on vp */
7804 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7808 if (vp->nUsers || vp->nWaiters)
7811 if (vp->stats.last_get <= thresh) {
7812 ret = VSoftDetachVolume_r(vp, thresh);
7818 /* check whether volume should be made a
7819 * soft detach candidate */
7821 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7824 if (vp->nUsers || vp->nWaiters)
7829 opr_Assert(idx == VLRU_QUEUE_NEW);
7831 if (vp->stats.last_get <= thresh) {
7832 /* move to candidate pool */
7833 queue_Remove(&vp->vlru);
7834 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7835 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7836 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7837 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7845 /* begin exclusive access on VLRU */
7847 VLRU_BeginExclusive_r(struct VLRU_q * q)
7849 opr_Assert(q->busy == 0);
7853 /* end exclusive access on VLRU */
7855 VLRU_EndExclusive_r(struct VLRU_q * q)
7857 opr_Assert(q->busy);
7859 CV_BROADCAST(&q->cv);
7862 /* wait for another thread to end exclusive access on VLRU */
7864 VLRU_Wait_r(struct VLRU_q * q)
7867 VOL_CV_WAIT(&q->cv);
7872 * volume soft detach
7874 * caller MUST NOT hold a ref count on vp */
7876 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7881 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7883 ts_save = vp->stats.last_get;
7884 if (ts_save > thresh)
7887 if (vp->nUsers || vp->nWaiters)
7890 if (VIsExclusiveState(V_attachState(vp))) {
7894 switch (V_attachState(vp)) {
7895 case VOL_STATE_UNATTACHED:
7896 case VOL_STATE_PREATTACHED:
7897 case VOL_STATE_ERROR:
7898 case VOL_STATE_GOING_OFFLINE:
7899 case VOL_STATE_SHUTTING_DOWN:
7900 case VOL_STATE_SALVAGING:
7901 case VOL_STATE_DELETED:
7902 volume_LRU.q[vp->vlru.idx].len--;
7904 /* create and cancel a reservation to
7905 * give the volume an opportunity to
7907 VCreateReservation_r(vp);
7908 queue_Remove(&vp->vlru);
7909 vp->vlru.idx = VLRU_QUEUE_INVALID;
7910 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7911 VCancelReservation_r(vp);
7917 /* hold the volume and take it offline.
7918 * no need for reservations, as VHold_r
7919 * takes care of that internally. */
7920 if (VHold_r(vp) == 0) {
7921 /* vhold drops the glock, so now we should
7922 * check to make sure we aren't racing against
7923 * other threads. if we are racing, offlining vp
7924 * would be wasteful, and block the scanner for a while
7928 (vp->shuttingDown) ||
7929 (vp->goingOffline) ||
7930 (vp->stats.last_get != ts_save)) {
7931 /* looks like we're racing someone else. bail */
7935 /* pull it off the VLRU */
7936 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7937 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7938 queue_Remove(&vp->vlru);
7939 vp->vlru.idx = VLRU_QUEUE_INVALID;
7940 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7942 /* take if offline */
7943 VOffline_r(vp, "volume has been soft detached");
7945 /* invalidate the volume header cache */
7946 FreeVolumeHeader(vp);
7949 IncUInt64(&VStats.soft_detaches);
7950 vp->stats.soft_detaches++;
7952 /* put in pre-attached state so demand
7953 * attacher can work on it */
7954 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7960 #endif /* AFS_DEMAND_ATTACH_FS */
7963 /***************************************************/
7964 /* Volume Header Cache routines */
7965 /***************************************************/
7968 * volume header cache.
7970 struct volume_hdr_LRU_t volume_hdr_LRU;
7973 * initialize the volume header cache.
7975 * @param[in] howMany number of header cache entries to preallocate
7977 * @pre VOL_LOCK held. Function has never been called before.
7979 * @post howMany cache entries are allocated, initialized, and added
7980 * to the LRU list. Header cache statistics are initialized.
7982 * @note only applicable to fileServer program type. Should only be
7983 * called once during volume package initialization.
7985 * @internal volume package internal use only.
7988 VInitVolumeHeaderCache(afs_uint32 howMany)
7990 struct volHeader *hp;
7991 if (programType != fileServer)
7993 queue_Init(&volume_hdr_LRU);
7994 volume_hdr_LRU.stats.free = 0;
7995 volume_hdr_LRU.stats.used = howMany;
7996 volume_hdr_LRU.stats.attached = 0;
7997 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7998 opr_Assert(hp != NULL);
8001 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8002 * to ensure they have the right values
8004 ReleaseVolumeHeader(hp++);
8007 /* get a volume header off of the volume header LRU.
8009 * @return volume header
8010 * @retval NULL no usable volume header is available on the LRU
8012 * @pre VOL_LOCK held
8014 * @post for DAFS, if the returned header is associated with a volume, that
8015 * volume is NOT in an exclusive state
8017 * @internal volume package internal use only.
8019 #ifdef AFS_DEMAND_ATTACH_FS
8020 static struct volHeader*
8021 GetVolHeaderFromLRU(void)
8023 struct volHeader *hd = NULL, *qh, *nqh;
8024 /* Usually, a volume in an exclusive state will not have its header on
8025 * the LRU. However, it is possible for this to occur when a salvage
8026 * request is received over FSSYNC, and possibly in other corner cases.
8027 * So just skip over headers whose volumes are in an exclusive state. We
8028 * could VWaitExclusiveState_r instead, but not waiting is faster and
8030 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8031 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8039 #else /* AFS_DEMAND_ATTACH_FS */
8040 static struct volHeader*
8041 GetVolHeaderFromLRU(void)
8043 struct volHeader *hd = NULL;
8044 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8045 hd = queue_First(&volume_hdr_LRU, volHeader);
8050 #endif /* !AFS_DEMAND_ATTACH_FS */
8053 * get a volume header and attach it to the volume object.
8055 * @param[in] vp pointer to volume object
8057 * @return cache entry status
8058 * @retval 0 volume header was newly attached; cache data is invalid
8059 * @retval 1 volume header was previously attached; cache data is valid
8061 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8063 * @post volume header attached to volume object. if necessary, header cache
8064 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8066 * @note VOL_LOCK may be dropped
8068 * @warning this interface does not load header data from disk. it merely
8069 * attaches a header object to the volume object, and may sync the old
8070 * header cache data out to disk in the process.
8072 * @internal volume package internal use only.
8075 GetVolumeHeader(Volume * vp)
8078 struct volHeader *hd;
8080 static int everLogged = 0;
8082 #ifdef AFS_DEMAND_ATTACH_FS
8083 VolState vp_save = 0, back_save = 0;
8085 /* XXX debug 9/19/05 we've apparently got
8086 * a ref counting bug somewhere that's
8087 * breaking the nUsers == 0 => header on LRU
8089 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8090 Log("nUsers == 0, but header not on LRU\n");
8095 old = (vp->header != NULL); /* old == volume already has a header */
8097 if (programType != fileServer) {
8098 /* for volume utilities, we allocate volHeaders as needed */
8100 hd = calloc(1, sizeof(*vp->header));
8101 opr_Assert(hd != NULL);
8104 #ifdef AFS_DEMAND_ATTACH_FS
8105 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8109 /* for the fileserver, we keep a volume header cache */
8111 /* the header we previously dropped in the lru is
8112 * still available. pull it off the lru and return */
8115 opr_Assert(hd->back == vp);
8116 #ifdef AFS_DEMAND_ATTACH_FS
8117 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8120 hd = GetVolHeaderFromLRU();
8122 /* LRU is empty, so allocate a new volHeader
8123 * this is probably indicative of a leak, so let the user know */
8124 hd = calloc(1, sizeof(struct volHeader));
8125 opr_Assert(hd != NULL);
8127 Log("****Allocated more volume headers, probably leak****\n");
8130 volume_hdr_LRU.stats.free++;
8133 /* this header used to belong to someone else.
8134 * we'll need to check if the header needs to
8135 * be sync'd out to disk */
8137 #ifdef AFS_DEMAND_ATTACH_FS
8138 /* GetVolHeaderFromLRU had better not give us back a header
8139 * with a volume in exclusive state... */
8140 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8143 if (hd->diskstuff.inUse) {
8144 /* volume was in use, so we'll need to sync
8145 * its header to disk */
8147 #ifdef AFS_DEMAND_ATTACH_FS
8148 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8149 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8150 VCreateReservation_r(hd->back);
8154 WriteVolumeHeader_r(&error, hd->back);
8155 /* Ignore errors; catch them later */
8157 #ifdef AFS_DEMAND_ATTACH_FS
8162 hd->back->header = NULL;
8163 #ifdef AFS_DEMAND_ATTACH_FS
8164 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8166 if (hd->diskstuff.inUse) {
8167 VChangeState_r(hd->back, back_save);
8168 VCancelReservation_r(hd->back);
8169 VChangeState_r(vp, vp_save);
8173 volume_hdr_LRU.stats.attached++;
8177 #ifdef AFS_DEMAND_ATTACH_FS
8178 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8181 volume_hdr_LRU.stats.free--;
8182 volume_hdr_LRU.stats.used++;
8184 IncUInt64(&VStats.hdr_gets);
8185 #ifdef AFS_DEMAND_ATTACH_FS
8186 IncUInt64(&vp->stats.hdr_gets);
8187 vp->stats.last_hdr_get = FT_ApproxTime();
8194 * make sure volume header is attached and contains valid cache data.
8196 * @param[out] ec outbound error code
8197 * @param[in] vp pointer to volume object
8199 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8201 * @post header cache entry attached, and loaded with valid data, or
8202 * *ec is nonzero, and the header is released back into the LRU.
8204 * @internal volume package internal use only.
8207 LoadVolumeHeader(Error * ec, Volume * vp)
8209 #ifdef AFS_DEMAND_ATTACH_FS
8210 VolState state_save;
8214 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8215 IncUInt64(&VStats.hdr_loads);
8216 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8219 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8220 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8222 IncUInt64(&vp->stats.hdr_loads);
8223 now = FT_ApproxTime();
8227 V_attachFlags(vp) |= VOL_HDR_LOADED;
8228 vp->stats.last_hdr_load = now;
8230 VChangeState_r(vp, state_save);
8232 #else /* AFS_DEMAND_ATTACH_FS */
8234 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8235 IncUInt64(&VStats.hdr_loads);
8237 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8238 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8241 #endif /* AFS_DEMAND_ATTACH_FS */
8243 /* maintain (nUsers==0) => header in LRU invariant */
8244 FreeVolumeHeader(vp);
8249 * release a header cache entry back into the LRU list.
8251 * @param[in] hd pointer to volume header cache object
8253 * @pre VOL_LOCK held.
8255 * @post header cache object appended onto end of LRU list.
8257 * @note only applicable to fileServer program type.
8259 * @note used to place a header cache entry back into the
8260 * LRU pool without invalidating it as a cache entry.
8262 * @internal volume package internal use only.
8265 ReleaseVolumeHeader(struct volHeader *hd)
8267 if (programType != fileServer)
8269 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8271 queue_Append(&volume_hdr_LRU, hd);
8272 #ifdef AFS_DEMAND_ATTACH_FS
8274 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8277 volume_hdr_LRU.stats.free++;
8278 volume_hdr_LRU.stats.used--;
8282 * free/invalidate a volume header cache entry.
8284 * @param[in] vp pointer to volume object
8286 * @pre VOL_LOCK is held.
8288 * @post For fileserver, header cache entry is returned to LRU, and it is
8289 * invalidated as a cache entry. For volume utilities, the header
8290 * cache entry is freed.
8292 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8293 * whenever it is necessary to invalidate the header cache entry.
8295 * @see ReleaseVolumeHeader
8297 * @internal volume package internal use only.
8300 FreeVolumeHeader(Volume * vp)
8302 struct volHeader *hd = vp->header;
8305 if (programType == fileServer) {
8306 ReleaseVolumeHeader(hd);
8311 #ifdef AFS_DEMAND_ATTACH_FS
8312 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8314 volume_hdr_LRU.stats.attached--;
8319 /***************************************************/
8320 /* Volume Hash Table routines */
8321 /***************************************************/
8324 * set size of volume object hash table.
8326 * @param[in] logsize log(2) of desired hash table size
8328 * @return operation status
8330 * @retval -1 failure
8332 * @pre MUST be called prior to VInitVolumePackage2
8334 * @post Volume Hash Table will have 2^logsize buckets
8337 VSetVolHashSize(int logsize)
8339 /* 64 to 268435456 hash buckets seems like a reasonable range */
8340 if ((logsize < 6 ) || (logsize > 28)) {
8345 VolumeHashTable.Size = 1 << logsize;
8346 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8348 /* we can't yet support runtime modification of this
8349 * parameter. we'll need a configuration rwlock to
8350 * make runtime modification feasible.... */
8357 * initialize dynamic data structures for volume hash table.
8359 * @post hash table is allocated, and fields are initialized.
8361 * @internal volume package internal use only.
8364 VInitVolumeHash(void)
8368 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8369 sizeof(VolumeHashChainHead));
8370 opr_Assert(VolumeHashTable.Table != NULL);
8372 for (i=0; i < VolumeHashTable.Size; i++) {
8373 queue_Init(&VolumeHashTable.Table[i]);
8374 #ifdef AFS_DEMAND_ATTACH_FS
8375 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8376 #endif /* AFS_DEMAND_ATTACH_FS */
8381 * add a volume object to the hash table.
8383 * @param[in] vp pointer to volume object
8384 * @param[in] hashid hash of volume id
8386 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8389 * @post volume is added to hash chain.
8391 * @internal volume package internal use only.
8393 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8394 * asynchronous hash chain reordering to finish.
8397 AddVolumeToHashTable(Volume * vp, int hashid)
8399 VolumeHashChainHead * head;
8401 if (queue_IsOnQueue(vp))
8404 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8406 #ifdef AFS_DEMAND_ATTACH_FS
8407 /* wait for the hash chain to become available */
8410 V_attachFlags(vp) |= VOL_IN_HASH;
8411 vp->chainCacheCheck = ++head->cacheCheck;
8412 #endif /* AFS_DEMAND_ATTACH_FS */
8415 vp->hashid = hashid;
8416 queue_Append(head, vp);
8417 vp->vnodeHashOffset = VolumeHashOffset_r();
8421 * delete a volume object from the hash table.
8423 * @param[in] vp pointer to volume object
8425 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8428 * @post volume is removed from hash chain.
8430 * @internal volume package internal use only.
8432 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8433 * asynchronous hash chain reordering to finish.
8436 DeleteVolumeFromHashTable(Volume * vp)
8438 VolumeHashChainHead * head;
8440 if (!queue_IsOnQueue(vp))
8443 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8445 #ifdef AFS_DEMAND_ATTACH_FS
8446 /* wait for the hash chain to become available */
8449 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8451 #endif /* AFS_DEMAND_ATTACH_FS */
8455 /* do NOT reset hashid to zero, as the online
8456 * salvager package may need to know the volume id
8457 * after the volume is removed from the hash */
8461 * lookup a volume object in the hash table given a volume id.
8463 * @param[out] ec error code return
8464 * @param[in] volumeId volume id
8465 * @param[in] hint volume object which we believe could be the correct
8468 * @return volume object pointer
8469 * @retval NULL no such volume id is registered with the hash table.
8471 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8474 * @post volume object with the given id is returned. volume object and
8475 * hash chain access statistics are updated. hash chain may have
8478 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8479 * asynchronous hash chain reordering operation to finish, or
8480 * in order for us to perform an asynchronous chain reordering.
8482 * @note Hash chain reorderings occur when the access count for the
8483 * volume object being looked up exceeds the sum of the previous
8484 * node's (the node ahead of it in the hash chain linked list)
8485 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8487 * @note For DAFS, the hint parameter allows us to short-circuit if the
8488 * cacheCheck fields match between the hash chain head and the
8489 * hint volume object.
8492 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8496 #ifdef AFS_DEMAND_ATTACH_FS
8499 VolumeHashChainHead * head;
8502 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8504 #ifdef AFS_DEMAND_ATTACH_FS
8505 /* wait for the hash chain to become available */
8508 /* check to see if we can short circuit without walking the hash chain */
8509 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8510 IncUInt64(&hint->stats.hash_short_circuits);
8513 #endif /* AFS_DEMAND_ATTACH_FS */
8515 /* someday we need to either do per-chain locks, RWlocks,
8516 * or both for volhash access.
8517 * (and move to a data structure with better cache locality) */
8519 /* search the chain for this volume id */
8520 for(queue_Scan(head, vp, np, Volume)) {
8522 if (vp->hashid == volumeId) {
8527 if (queue_IsEnd(head, vp)) {
8531 #ifdef AFS_DEMAND_ATTACH_FS
8532 /* update hash chain statistics */
8535 FillInt64(lks, 0, looks);
8536 AddUInt64(head->looks, lks, &head->looks);
8537 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8538 IncUInt64(&head->gets);
8543 IncUInt64(&vp->stats.hash_lookups);
8545 /* for demand attach fileserver, we permit occasional hash chain reordering
8546 * so that frequently looked up volumes move towards the head of the chain */
8547 pp = queue_Prev(vp, Volume);
8548 if (!queue_IsEnd(head, pp)) {
8549 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8550 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8551 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8552 VReorderHash_r(head, pp, vp);
8556 /* update the short-circuit cache check */
8557 vp->chainCacheCheck = head->cacheCheck;
8559 #endif /* AFS_DEMAND_ATTACH_FS */
8564 #ifdef AFS_DEMAND_ATTACH_FS
8565 /* perform volume hash chain reordering.
8567 * advance a subchain beginning at vp ahead of
8568 * the adjacent subchain ending at pp */
8570 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8572 Volume *tp, *np, *lp;
8573 afs_uint64 move_thresh;
8575 /* this should never be called if the chain is already busy, so
8576 * no need to wait for other exclusive chain ops to finish */
8578 /* this is a rather heavy set of operations,
8579 * so let's set the chain busy flag and drop
8581 VHashBeginExclusive_r(head);
8584 /* scan forward in the chain from vp looking for the last element
8585 * in the chain we want to advance */
8586 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8587 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8588 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8589 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8593 lp = queue_Prev(tp, Volume);
8595 /* scan backwards from pp to determine where to splice and
8596 * insert the subchain we're advancing */
8597 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8598 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8602 tp = queue_Next(tp, Volume);
8604 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8605 queue_MoveChainBefore(tp,vp,lp);
8608 IncUInt64(&VStats.hash_reorders);
8610 IncUInt64(&head->reorders);
8612 /* wake up any threads waiting for the hash chain */
8613 VHashEndExclusive_r(head);
8617 /* demand-attach fs volume hash
8618 * asynchronous exclusive operations */
8621 * begin an asynchronous exclusive operation on a volume hash chain.
8623 * @param[in] head pointer to volume hash chain head object
8625 * @pre VOL_LOCK held. hash chain is quiescent.
8627 * @post hash chain marked busy.
8629 * @note this interface is used in conjunction with VHashEndExclusive_r and
8630 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8631 * volume hash chain. Its main use case is hash chain reordering, which
8632 * has the potential to be a highly latent operation.
8634 * @see VHashEndExclusive_r
8639 * @internal volume package internal use only.
8642 VHashBeginExclusive_r(VolumeHashChainHead * head)
8644 opr_Assert(head->busy == 0);
8649 * relinquish exclusive ownership of a volume hash chain.
8651 * @param[in] head pointer to volume hash chain head object
8653 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8655 * @post hash chain is marked quiescent. threads awaiting use of
8656 * chain are awakened.
8658 * @see VHashBeginExclusive_r
8663 * @internal volume package internal use only.
8666 VHashEndExclusive_r(VolumeHashChainHead * head)
8668 opr_Assert(head->busy);
8670 CV_BROADCAST(&head->chain_busy_cv);
8674 * wait for all asynchronous operations on a hash chain to complete.
8676 * @param[in] head pointer to volume hash chain head object
8678 * @pre VOL_LOCK held.
8680 * @post hash chain object is quiescent.
8682 * @see VHashBeginExclusive_r
8683 * @see VHashEndExclusive_r
8687 * @note This interface should be called before any attempt to
8688 * traverse the hash chain. It is permissible for a thread
8689 * to gain exclusive access to the chain, and then perform
8690 * latent operations on the chain asynchronously wrt the
8693 * @warning if waiting is necessary, VOL_LOCK is dropped
8695 * @internal volume package internal use only.
8698 VHashWait_r(VolumeHashChainHead * head)
8700 while (head->busy) {
8701 VOL_CV_WAIT(&head->chain_busy_cv);
8704 #endif /* AFS_DEMAND_ATTACH_FS */
8707 /***************************************************/
8708 /* Volume by Partition List routines */
8709 /***************************************************/
8712 * demand attach fileserver adds a
8713 * linked list of volumes to each
8714 * partition object, thus allowing
8715 * for quick enumeration of all
8716 * volumes on a partition
8719 #ifdef AFS_DEMAND_ATTACH_FS
8721 * add a volume to its disk partition VByPList.
8723 * @param[in] vp pointer to volume object
8725 * @pre either the disk partition VByPList is owned exclusively
8726 * by the calling thread, or the list is quiescent and
8729 * @post volume is added to disk partition VByPList
8733 * @warning it is the caller's responsibility to ensure list
8736 * @see VVByPListWait_r
8737 * @see VVByPListBeginExclusive_r
8738 * @see VVByPListEndExclusive_r
8740 * @internal volume package internal use only.
8743 AddVolumeToVByPList_r(Volume * vp)
8745 if (queue_IsNotOnQueue(&vp->vol_list)) {
8746 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8747 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8748 vp->partition->vol_list.len++;
8753 * delete a volume from its disk partition VByPList.
8755 * @param[in] vp pointer to volume object
8757 * @pre either the disk partition VByPList is owned exclusively
8758 * by the calling thread, or the list is quiescent and
8761 * @post volume is removed from the disk partition VByPList
8765 * @warning it is the caller's responsibility to ensure list
8768 * @see VVByPListWait_r
8769 * @see VVByPListBeginExclusive_r
8770 * @see VVByPListEndExclusive_r
8772 * @internal volume package internal use only.
8775 DeleteVolumeFromVByPList_r(Volume * vp)
8777 if (queue_IsOnQueue(&vp->vol_list)) {
8778 queue_Remove(&vp->vol_list);
8779 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8780 vp->partition->vol_list.len--;
8785 * begin an asynchronous exclusive operation on a VByPList.
8787 * @param[in] dp pointer to disk partition object
8789 * @pre VOL_LOCK held. VByPList is quiescent.
8791 * @post VByPList marked busy.
8793 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8794 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8797 * @see VVByPListEndExclusive_r
8798 * @see VVByPListWait_r
8802 * @internal volume package internal use only.
8804 /* take exclusive control over the list */
8806 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8808 opr_Assert(dp->vol_list.busy == 0);
8809 dp->vol_list.busy = 1;
8813 * relinquish exclusive ownership of a VByPList.
8815 * @param[in] dp pointer to disk partition object
8817 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8819 * @post VByPList is marked quiescent. threads awaiting use of
8820 * the list are awakened.
8822 * @see VVByPListBeginExclusive_r
8823 * @see VVByPListWait_r
8827 * @internal volume package internal use only.
8830 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8832 opr_Assert(dp->vol_list.busy);
8833 dp->vol_list.busy = 0;
8834 CV_BROADCAST(&dp->vol_list.cv);
8838 * wait for all asynchronous operations on a VByPList to complete.
8840 * @param[in] dp pointer to disk partition object
8842 * @pre VOL_LOCK is held.
8844 * @post disk partition's VByP list is quiescent
8848 * @note This interface should be called before any attempt to
8849 * traverse the VByPList. It is permissible for a thread
8850 * to gain exclusive access to the list, and then perform
8851 * latent operations on the list asynchronously wrt the
8854 * @warning if waiting is necessary, VOL_LOCK is dropped
8856 * @see VVByPListEndExclusive_r
8857 * @see VVByPListBeginExclusive_r
8859 * @internal volume package internal use only.
8862 VVByPListWait_r(struct DiskPartition64 * dp)
8864 while (dp->vol_list.busy) {
8865 VOL_CV_WAIT(&dp->vol_list.cv);
8868 #endif /* AFS_DEMAND_ATTACH_FS */
8870 /***************************************************/
8871 /* Volume Cache Statistics routines */
8872 /***************************************************/
8875 VPrintCacheStats_r(void)
8877 struct VnodeClassInfo *vcp;
8878 vcp = &VnodeClassInfo[vLarge];
8879 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);
8880 vcp = &VnodeClassInfo[vSmall];
8881 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);
8882 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8883 "%"AFS_INT64_FMT" replacements\n",
8884 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8888 VPrintCacheStats(void)
8891 VPrintCacheStats_r();
8895 #ifdef AFS_DEMAND_ATTACH_FS
8897 UInt64ToDouble(afs_uint64 * x)
8899 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8901 SplitInt64(*x, h, l);
8902 return (((double)h) * c32) + ((double) l);
8906 DoubleToPrintable(double x, char * buf, int len)
8908 static double billion = 1000000000.0;
8911 y[0] = (afs_uint32) (x / (billion * billion));
8912 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8913 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8916 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8918 snprintf(buf, len, "%d%09d", y[1], y[2]);
8920 snprintf(buf, len, "%d", y[2]);
8926 struct VLRUExtStatsEntry {
8930 struct VLRUExtStats {
8936 } queue_info[VLRU_QUEUE_INVALID];
8937 struct VLRUExtStatsEntry * vec;
8941 * add a 256-entry fudge factor onto the vector in case state changes
8942 * out from under us.
8944 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8947 * collect extended statistics for the VLRU subsystem.
8949 * @param[out] stats pointer to stats structure to be populated
8950 * @param[in] nvols number of volumes currently known to exist
8952 * @pre VOL_LOCK held
8954 * @post stats->vec allocated and populated
8956 * @return operation status
8961 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8963 afs_uint32 cur, idx, len;
8964 struct rx_queue * qp, * nqp;
8966 struct VLRUExtStatsEntry * vec;
8968 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8969 vec = stats->vec = calloc(len,
8970 sizeof(struct VLRUExtStatsEntry));
8976 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8977 VLRU_Wait_r(&volume_LRU.q[idx]);
8978 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8981 stats->queue_info[idx].start = cur;
8983 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8985 /* out of space in vec */
8988 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8989 vec[cur].volid = vp->hashid;
8993 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8996 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9004 #define ENUMTOSTRING(en) #en
9005 #define ENUMCASE(en) \
9006 case en: return ENUMTOSTRING(en)
9009 vlru_idx_to_string(int idx)
9012 ENUMCASE(VLRU_QUEUE_NEW);
9013 ENUMCASE(VLRU_QUEUE_MID);
9014 ENUMCASE(VLRU_QUEUE_OLD);
9015 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9016 ENUMCASE(VLRU_QUEUE_HELD);
9017 ENUMCASE(VLRU_QUEUE_INVALID);
9019 return "**UNKNOWN**";
9024 VPrintExtendedCacheStats_r(int flags)
9027 afs_uint32 vol_sum = 0;
9034 struct stats looks, gets, reorders, len;
9035 struct stats ch_looks, ch_gets, ch_reorders;
9037 VolumeHashChainHead *head;
9039 struct VLRUExtStats vlru_stats;
9041 /* zero out stats */
9042 memset(&looks, 0, sizeof(struct stats));
9043 memset(&gets, 0, sizeof(struct stats));
9044 memset(&reorders, 0, sizeof(struct stats));
9045 memset(&len, 0, sizeof(struct stats));
9046 memset(&ch_looks, 0, sizeof(struct stats));
9047 memset(&ch_gets, 0, sizeof(struct stats));
9048 memset(&ch_reorders, 0, sizeof(struct stats));
9050 for (i = 0; i < VolumeHashTable.Size; i++) {
9051 head = &VolumeHashTable.Table[i];
9054 VHashBeginExclusive_r(head);
9057 ch_looks.sum = UInt64ToDouble(&head->looks);
9058 ch_gets.sum = UInt64ToDouble(&head->gets);
9059 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9061 /* update global statistics */
9063 looks.sum += ch_looks.sum;
9064 gets.sum += ch_gets.sum;
9065 reorders.sum += ch_reorders.sum;
9066 len.sum += (double)head->len;
9067 vol_sum += head->len;
9070 len.min = (double) head->len;
9071 len.max = (double) head->len;
9072 looks.min = ch_looks.sum;
9073 looks.max = ch_looks.sum;
9074 gets.min = ch_gets.sum;
9075 gets.max = ch_gets.sum;
9076 reorders.min = ch_reorders.sum;
9077 reorders.max = ch_reorders.sum;
9079 if (((double)head->len) < len.min)
9080 len.min = (double) head->len;
9081 if (((double)head->len) > len.max)
9082 len.max = (double) head->len;
9083 if (ch_looks.sum < looks.min)
9084 looks.min = ch_looks.sum;
9085 else if (ch_looks.sum > looks.max)
9086 looks.max = ch_looks.sum;
9087 if (ch_gets.sum < gets.min)
9088 gets.min = ch_gets.sum;
9089 else if (ch_gets.sum > gets.max)
9090 gets.max = ch_gets.sum;
9091 if (ch_reorders.sum < reorders.min)
9092 reorders.min = ch_reorders.sum;
9093 else if (ch_reorders.sum > reorders.max)
9094 reorders.max = ch_reorders.sum;
9098 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9099 /* compute detailed per-chain stats */
9100 struct stats hdr_loads, hdr_gets;
9101 double v_looks, v_loads, v_gets;
9103 /* initialize stats with data from first element in chain */
9104 vp = queue_First(head, Volume);
9105 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9106 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9107 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9108 ch_gets.min = ch_gets.max = v_looks;
9109 hdr_loads.min = hdr_loads.max = v_loads;
9110 hdr_gets.min = hdr_gets.max = v_gets;
9111 hdr_loads.sum = hdr_gets.sum = 0;
9113 vp = queue_Next(vp, Volume);
9115 /* pull in stats from remaining elements in chain */
9116 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9117 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9118 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9119 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9121 hdr_loads.sum += v_loads;
9122 hdr_gets.sum += v_gets;
9124 if (v_looks < ch_gets.min)
9125 ch_gets.min = v_looks;
9126 else if (v_looks > ch_gets.max)
9127 ch_gets.max = v_looks;
9129 if (v_loads < hdr_loads.min)
9130 hdr_loads.min = v_loads;
9131 else if (v_loads > hdr_loads.max)
9132 hdr_loads.max = v_loads;
9134 if (v_gets < hdr_gets.min)
9135 hdr_gets.min = v_gets;
9136 else if (v_gets > hdr_gets.max)
9137 hdr_gets.max = v_gets;
9140 /* compute per-chain averages */
9141 ch_gets.avg = ch_gets.sum / ((double)head->len);
9142 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9143 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9145 /* dump per-chain stats */
9146 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9148 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9149 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9150 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9151 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9152 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9153 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9154 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9155 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9156 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9157 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9158 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9159 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9160 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9161 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9162 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9163 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9164 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9165 } else if (flags & VOL_STATS_PER_CHAIN) {
9166 /* dump simple per-chain stats */
9167 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9169 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9170 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9171 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9175 VHashEndExclusive_r(head);
9180 /* compute global averages */
9181 len.avg = len.sum / ((double)VolumeHashTable.Size);
9182 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9183 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9184 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9186 /* dump global stats */
9187 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9188 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9189 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9190 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9191 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9192 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9193 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9194 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9195 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9196 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9197 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9198 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9199 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9200 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9201 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9202 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9203 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9204 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9205 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9206 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9207 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9209 /* print extended disk related statistics */
9211 struct DiskPartition64 * diskP;
9212 afs_uint32 vol_count[VOLMAXPARTS+1];
9213 byte part_exists[VOLMAXPARTS+1];
9217 memset(vol_count, 0, sizeof(vol_count));
9218 memset(part_exists, 0, sizeof(part_exists));
9222 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9224 vol_count[id] = diskP->vol_list.len;
9225 part_exists[id] = 1;
9229 for (i = 0; i <= VOLMAXPARTS; i++) {
9230 if (part_exists[i]) {
9231 /* XXX while this is currently safe, it is a violation
9232 * of the VGetPartitionById_r interface contract. */
9233 diskP = VGetPartitionById_r(i, 0);
9235 Log("Partition %s has %d online volumes\n",
9236 VPartitionPath(diskP), diskP->vol_list.len);
9243 /* print extended VLRU statistics */
9244 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9245 afs_uint32 idx, cur, lpos;
9250 Log("VLRU State Dump:\n\n");
9252 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9253 Log("\t%s:\n", vlru_idx_to_string(idx));
9256 for (cur = vlru_stats.queue_info[idx].start;
9257 cur < vlru_stats.queue_info[idx].len;
9259 line[lpos++] = vlru_stats.vec[cur].volid;
9261 Log("\t\t%u, %u, %u, %u, %u,\n",
9262 line[0], line[1], line[2], line[3], line[4]);
9271 Log("\t\t%u, %u, %u, %u, %u\n",
9272 line[0], line[1], line[2], line[3], line[4]);
9277 free(vlru_stats.vec);
9284 VPrintExtendedCacheStats(int flags)
9287 VPrintExtendedCacheStats_r(flags);
9290 #endif /* AFS_DEMAND_ATTACH_FS */
9293 VCanScheduleSalvage(void)
9295 return vol_opts.canScheduleSalvage;
9301 return vol_opts.canUseFSSYNC;
9305 VCanUseSALVSYNC(void)
9307 return vol_opts.canUseSALVSYNC;
9311 VCanUnsafeAttach(void)
9313 return vol_opts.unsafe_attach;