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
34 #ifdef AFS_PTHREAD_ENV
35 # include <opr/lock.h>
37 # include <opr/lockstub.h>
40 #include <opr/jhash.h>
42 #include <afs/afsint.h>
44 #include <rx/rx_queue.h>
47 #if !defined(AFS_SGI_ENV)
50 #else /* AFS_OSF_ENV */
51 #ifdef AFS_VFSINCL_ENV
54 #include <sys/fs/ufs_fs.h>
56 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
57 #include <ufs/ufs/dinode.h>
58 #include <ufs/ffs/fs.h>
63 #else /* AFS_VFSINCL_ENV */
64 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
67 #endif /* AFS_VFSINCL_ENV */
68 #endif /* AFS_OSF_ENV */
69 #endif /* AFS_SGI_ENV */
70 #endif /* !AFS_NT40_ENV */
78 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
80 #include <sys/mnttab.h>
81 #include <sys/mntent.h>
87 #if defined(AFS_SGI_ENV)
90 #ifndef AFS_LINUX20_ENV
91 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
94 #endif /* AFS_SGI_ENV */
96 #endif /* AFS_HPUX_ENV */
100 #include <afs/errors.h>
103 #include <afs/afssyscalls.h>
105 #include <afs/afsutil.h>
106 #include "daemon_com.h"
108 #include "salvsync.h"
111 #include "partition.h"
112 #include "volume_inline.h"
117 #ifdef AFS_PTHREAD_ENV
118 pthread_mutex_t vol_glock_mutex;
119 pthread_mutex_t vol_trans_mutex;
120 pthread_cond_t vol_put_volume_cond;
121 pthread_cond_t vol_sleep_cond;
122 pthread_cond_t vol_init_attach_cond;
123 pthread_cond_t vol_vinit_cond;
124 int vol_attach_threads = 1;
125 #endif /* AFS_PTHREAD_ENV */
127 /* start-time configurable I/O parameters */
128 ih_init_params vol_io_params;
130 #ifdef AFS_DEMAND_ATTACH_FS
131 pthread_mutex_t vol_salvsync_mutex;
134 * Set this to 1 to disallow SALVSYNC communication in all threads; used
135 * during shutdown, since the salvageserver may have gone away.
137 static volatile sig_atomic_t vol_disallow_salvsync = 0;
138 #endif /* AFS_DEMAND_ATTACH_FS */
141 * has VShutdown_r been called / is VShutdown_r running?
143 static int vol_shutting_down = 0;
146 extern void *calloc(), *realloc();
149 /* Forward declarations */
150 static Volume *attach2(Error * ec, VolumeId volumeId, char *path,
151 struct DiskPartition64 *partp, Volume * vp,
152 int isbusy, int mode, int *acheckedOut);
153 static void ReallyFreeVolume(Volume * vp);
154 #ifdef AFS_DEMAND_ATTACH_FS
155 static void FreeVolume(Volume * vp);
156 #else /* !AFS_DEMAND_ATTACH_FS */
157 #define FreeVolume(vp) ReallyFreeVolume(vp)
158 static void VScanUpdateList(void);
159 #endif /* !AFS_DEMAND_ATTACH_FS */
160 static void VInitVolumeHeaderCache(afs_uint32 howMany);
161 static int GetVolumeHeader(Volume * vp);
162 static void ReleaseVolumeHeader(struct volHeader *hd);
163 static void FreeVolumeHeader(Volume * vp);
164 static void AddVolumeToHashTable(Volume * vp, VolumeId hashid);
165 static void DeleteVolumeFromHashTable(Volume * vp);
167 static int VHold(Volume * vp);
169 static int VHold_r(Volume * vp);
170 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
171 static void VReleaseVolumeHandles_r(Volume * vp);
172 static void VCloseVolumeHandles_r(Volume * vp);
173 static void LoadVolumeHeader(Error * ec, Volume * vp);
174 static int VCheckOffline(Volume * vp);
175 static int VCheckDetach(Volume * vp);
176 static Volume * GetVolume(Error * ec, Error * client_ec, VolumeId volumeId,
177 Volume * hint, const struct timespec *ts);
179 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
180 * defined when not linked with vice, XXXX */
181 ProgramType programType; /* The type of program using the package */
182 static VolumePackageOptions vol_opts;
184 /* extended volume package statistics */
187 #ifdef VOL_LOCK_DEBUG
188 pthread_t vol_glock_holder = 0;
192 /* this parameter needs to be tunable at runtime.
193 * 128 was really inadequate for largish servers -- at 16384 volumes this
194 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
195 * talk about bad spatial locality...
197 * an AVL or splay tree might work a lot better, but we'll just increase
198 * the default hash table size for now
200 #define DEFAULT_VOLUME_HASH_BITS 10
201 #define DEFAULT_VOLUME_HASH_SIZE opr_jhash_size(DEFAULT_VOLUME_HASH_BITS)
202 #define DEFAULT_VOLUME_HASH_MASK opr_jhash_mask(DEFAULT_VOLUME_HASH_BITS)
203 #define VOLUME_HASH(volumeId) \
204 (opr_jhash_int(volumeId, 0) & VolumeHashTable.Mask)
207 * turn volume hash chains into partially ordered lists.
208 * when the threshold is exceeded between two adjacent elements,
209 * perform a chain rebalancing operation.
211 * keep the threshold high in order to keep cache line invalidates
212 * low "enough" on SMPs
214 #define VOLUME_HASH_REORDER_THRESHOLD 200
217 * when possible, don't just reorder single elements, but reorder
218 * entire chains of elements at once. a chain of elements that
219 * exceed the element previous to the pivot by at least CHAIN_THRESH
220 * accesses are moved in front of the chain whose elements have at
221 * least CHAIN_THRESH less accesses than the pivot element
223 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
226 * The per volume uniquifier is bumped by 200 and and written to disk
227 * every 200 file creates.
229 #define VOLUME_UPDATE_UNIQUIFIER_BUMP 200
231 #include "rx/rx_queue.h"
234 VolumeHashTable_t VolumeHashTable = {
235 DEFAULT_VOLUME_HASH_SIZE,
236 DEFAULT_VOLUME_HASH_MASK,
241 static void VInitVolumeHash(void);
244 #ifdef AFS_PTHREAD_ENV
246 * disk partition queue element
248 typedef struct diskpartition_queue_t {
249 struct rx_queue queue; /**< queue header */
250 struct DiskPartition64 *diskP; /**< disk partition table entry */
251 } diskpartition_queue_t;
253 #ifndef AFS_DEMAND_ATTACH_FS
255 typedef struct vinitvolumepackage_thread_t {
256 struct rx_queue queue;
257 pthread_cond_t thread_done_cv;
258 int n_threads_complete;
259 } vinitvolumepackage_thread_t;
260 static void * VInitVolumePackageThread(void * args);
262 #else /* !AFS_DEMAND_ATTTACH_FS */
263 #define VINIT_BATCH_MAX_SIZE 512
266 * disk partition work queue
268 struct partition_queue {
269 struct rx_queue head; /**< diskpartition_queue_t queue */
270 pthread_mutex_t mutex;
275 * volumes parameters for preattach
277 struct volume_init_batch {
278 struct rx_queue queue; /**< queue header */
279 int thread; /**< posting worker thread */
280 int last; /**< indicates thread is done */
281 int size; /**< number of volume ids in batch */
282 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
286 * volume parameters work queue
288 struct volume_init_queue {
289 struct rx_queue head; /**< volume_init_batch queue */
290 pthread_mutex_t mutex;
295 * volume init worker thread parameters
297 struct vinitvolumepackage_thread_param {
298 int nthreads; /**< total number of worker threads */
299 int thread; /**< thread number for this worker thread */
300 struct partition_queue *pq; /**< queue partitions to scan */
301 struct volume_init_queue *vq; /**< queue of volume to preattach */
304 static void *VInitVolumePackageThread(void *args);
305 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
306 static VolumeId VInitNextVolumeId(DIR *dirp);
307 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
309 #endif /* !AFS_DEMAND_ATTACH_FS */
310 #endif /* AFS_PTHREAD_ENV */
312 #ifndef AFS_DEMAND_ATTACH_FS
313 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
314 int * nAttached, int * nUnattached);
315 #endif /* AFS_DEMAND_ATTACH_FS */
318 #ifdef AFS_DEMAND_ATTACH_FS
319 /* demand attach fileserver extensions */
322 * in the future we will support serialization of VLRU state into the fs_state
325 * these structures are the beginning of that effort
327 struct VLRU_DiskHeader {
328 struct versionStamp stamp; /* magic and structure version number */
329 afs_uint32 mtime; /* time of dump to disk */
330 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
333 struct VLRU_DiskEntry {
334 VolumeId vid; /* volume ID */
335 afs_uint32 idx; /* generation */
336 afs_uint32 last_get; /* timestamp of last get */
339 struct VLRU_StartupQueue {
340 struct VLRU_DiskEntry * entry;
345 typedef struct vshutdown_thread_t {
347 pthread_mutex_t lock;
349 pthread_cond_t master_cv;
351 int n_threads_complete;
353 int schedule_version;
356 byte n_parts_done_pass;
357 byte part_thread_target[VOLMAXPARTS+1];
358 byte part_done_pass[VOLMAXPARTS+1];
359 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
360 int stats[4][VOLMAXPARTS+1];
361 } vshutdown_thread_t;
362 static void * VShutdownThread(void * args);
365 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
366 static int VCheckFree(Volume * vp);
369 static void AddVolumeToVByPList_r(Volume * vp);
370 static void DeleteVolumeFromVByPList_r(Volume * vp);
371 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
372 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
373 static void VVByPListWait_r(struct DiskPartition64 * dp);
375 /* online salvager */
377 VCHECK_SALVAGE_OK = 0, /**< no pending salvage */
378 VCHECK_SALVAGE_SCHEDULED = 1, /**< salvage has been scheduled */
379 VCHECK_SALVAGE_ASYNC = 2, /**< salvage being scheduled */
380 VCHECK_SALVAGE_DENIED = 3, /**< salvage not scheduled; denied */
381 VCHECK_SALVAGE_FAIL = 4 /**< salvage not scheduled; failed */
383 static int VCheckSalvage(Volume * vp);
384 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
385 static int VScheduleSalvage_r(Volume * vp);
388 /* Volume hash table */
389 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
390 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
391 static void VHashEndExclusive_r(VolumeHashChainHead * head);
392 static void VHashWait_r(VolumeHashChainHead * head);
395 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
396 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
397 struct rx_queue ** idx);
398 static void ShutdownController(vshutdown_thread_t * params);
399 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
402 static void VLRU_ComputeConstants(void);
403 static void VInitVLRU(void);
404 static void VLRU_Init_Node_r(Volume * vp);
405 static void VLRU_Add_r(Volume * vp);
406 static void VLRU_Delete_r(Volume * vp);
407 static void VLRU_UpdateAccess_r(Volume * vp);
408 static void * VLRU_ScannerThread(void * args);
409 static void VLRU_Scan_r(int idx);
410 static void VLRU_Promote_r(int idx);
411 static void VLRU_Demote_r(int idx);
412 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
415 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
416 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
417 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
420 pthread_key_t VThread_key;
421 VThreadOptions_t VThread_defaults = {
422 0 /**< allow salvsync */
424 #endif /* AFS_DEMAND_ATTACH_FS */
427 struct Lock vol_listLock; /* Lock obtained when listing volumes:
428 * prevents a volume from being missed
429 * if the volume is attached during a
433 /* Common message used when the volume goes off line */
434 char *VSalvageMessage =
435 "Files in this volume are currently unavailable; call operations";
437 int VInit; /* 0 - uninitialized,
438 * 1 - initialized but not all volumes have been attached,
439 * 2 - initialized and all volumes have been attached,
440 * 3 - initialized, all volumes have been attached, and
441 * VConnectFS() has completed. */
443 static int vinit_attach_abort = 0;
445 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
446 * used to stamp volume headers and in-core
447 * vnodes. When the volume goes on-line the
448 * vnode will be invalidated
449 * access only with VOL_LOCK held */
454 /***************************************************/
455 /* Startup routines */
456 /***************************************************/
458 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
459 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
460 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
464 * assign default values to a VolumePackageOptions struct.
466 * Always call this on a VolumePackageOptions struct first, then set any
467 * specific options you want, then call VInitVolumePackage2.
469 * @param[in] pt caller's program type
470 * @param[out] opts volume package options
473 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
475 opts->nLargeVnodes = opts->nSmallVnodes = 5;
478 opts->canScheduleSalvage = 0;
479 opts->canUseFSSYNC = 0;
480 opts->canUseSALVSYNC = 0;
482 opts->interrupt_rxcall = NULL;
483 opts->offline_timeout = -1;
484 opts->offline_shutdown_timeout = -1;
485 opts->usage_threshold = 128;
486 opts->usage_rate_limit = 5;
489 opts->unsafe_attach = 1;
490 #else /* !FAST_RESTART */
491 opts->unsafe_attach = 0;
492 #endif /* !FAST_RESTART */
496 opts->canScheduleSalvage = 1;
497 opts->canUseSALVSYNC = 1;
501 opts->canUseFSSYNC = 1;
505 opts->nLargeVnodes = 0;
506 opts->nSmallVnodes = 0;
508 opts->canScheduleSalvage = 1;
509 opts->canUseFSSYNC = 1;
519 * Set VInit to a certain value, and signal waiters.
521 * @param[in] value the value to set VInit to
526 VSetVInit_r(int value)
529 opr_cv_broadcast(&vol_vinit_cond);
533 VLogOfflineTimeout(const char *type, afs_int32 timeout)
539 Log("VInitVolumePackage: Interrupting clients accessing %s "
540 "immediately\n", type);
542 Log("VInitVolumePackage: Interrupting clients accessing %s "
543 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
548 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
550 int errors = 0; /* Number of errors while finding vice partitions. */
555 #ifndef AFS_PTHREAD_ENV
556 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
557 Log("VInitVolumePackage: offline_timeout and/or "
558 "offline_shutdown_timeout was specified, but the volume package "
559 "does not support these for LWP builds\n");
563 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
564 VLogOfflineTimeout("volumes going offline during shutdown",
565 opts->offline_shutdown_timeout);
567 memset(&VStats, 0, sizeof(VStats));
568 VStats.hdr_cache_size = 200;
570 VInitPartitionPackage();
572 #ifdef AFS_DEMAND_ATTACH_FS
573 if (programType == fileServer) {
576 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
578 opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
581 opr_mutex_init(&vol_glock_mutex);
582 opr_mutex_init(&vol_trans_mutex);
583 opr_cv_init(&vol_put_volume_cond);
584 opr_cv_init(&vol_sleep_cond);
585 opr_cv_init(&vol_init_attach_cond);
586 opr_cv_init(&vol_vinit_cond);
587 #ifndef AFS_PTHREAD_ENV
589 #endif /* AFS_PTHREAD_ENV */
590 Lock_Init(&vol_listLock);
592 srandom(time(0)); /* For VGetVolumeInfo */
594 #ifdef AFS_DEMAND_ATTACH_FS
595 opr_mutex_init(&vol_salvsync_mutex);
596 #endif /* AFS_DEMAND_ATTACH_FS */
598 /* Ok, we have done enough initialization that fileserver can
599 * start accepting calls, even though the volumes may not be
600 * available just yet.
604 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
605 if (programType == salvageServer) {
608 #endif /* AFS_DEMAND_ATTACH_FS */
609 #ifdef FSSYNC_BUILD_SERVER
610 if (programType == fileServer) {
614 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
615 if (VCanUseSALVSYNC()) {
616 /* establish a connection to the salvager at this point */
617 opr_Verify(VConnectSALV() != 0);
619 #endif /* AFS_DEMAND_ATTACH_FS */
621 if (opts->volcache > VStats.hdr_cache_size)
622 VStats.hdr_cache_size = opts->volcache;
623 VInitVolumeHeaderCache(VStats.hdr_cache_size);
625 VInitVnodes(vLarge, opts->nLargeVnodes);
626 VInitVnodes(vSmall, opts->nSmallVnodes);
629 errors = VAttachPartitions();
633 if (programType != fileServer) {
634 errors = VInitAttachVolumes(programType);
640 #ifdef FSSYNC_BUILD_CLIENT
641 if (VCanUseFSSYNC()) {
643 #ifdef AFS_DEMAND_ATTACH_FS
644 if (programType == salvageServer) {
645 Log("Unable to connect to file server; aborted\n");
648 #endif /* AFS_DEMAND_ATTACH_FS */
649 Log("Unable to connect to file server; will retry at need\n");
652 #endif /* FSSYNC_BUILD_CLIENT */
657 #if !defined(AFS_PTHREAD_ENV)
659 * Attach volumes in vice partitions
661 * @param[in] pt calling program type
664 * @note This is the original, non-threaded version of attach parititions.
666 * @post VInit state is 2
669 VInitAttachVolumes(ProgramType pt)
671 opr_Assert(VInit==1);
672 if (pt == fileServer) {
673 struct DiskPartition64 *diskP;
674 /* Attach all the volumes in this partition */
675 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
676 int nAttached = 0, nUnattached = 0;
677 opr_Verify(VAttachVolumesByPartition(diskP,
678 &nAttached, &nUnattached)
683 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
684 LWP_NoYieldSignal(VInitAttachVolumes);
688 #endif /* !AFS_PTHREAD_ENV */
690 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
692 * Attach volumes in vice partitions
694 * @param[in] pt calling program type
697 * @note Threaded version of attach parititions.
699 * @post VInit state is 2
702 VInitAttachVolumes(ProgramType pt)
704 opr_Assert(VInit==1);
705 if (pt == fileServer) {
706 struct DiskPartition64 *diskP;
707 struct vinitvolumepackage_thread_t params;
708 struct diskpartition_queue_t * dpq;
709 int i, threads, parts;
711 pthread_attr_t attrs;
713 opr_cv_init(¶ms.thread_done_cv);
715 params.n_threads_complete = 0;
717 /* create partition work queue */
718 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
719 dpq = malloc(sizeof(struct diskpartition_queue_t));
720 opr_Assert(dpq != NULL);
722 queue_Append(¶ms,dpq);
725 threads = min(parts, vol_attach_threads);
728 /* spawn off a bunch of initialization threads */
729 opr_Verify(pthread_attr_init(&attrs) == 0);
730 opr_Verify(pthread_attr_setdetachstate(&attrs,
731 PTHREAD_CREATE_DETACHED)
734 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
735 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
739 for (i=0; i < threads; i++) {
742 opr_Verify(pthread_create(&tid, &attrs,
743 &VInitVolumePackageThread,
745 AFS_SIGSET_RESTORE();
748 while(params.n_threads_complete < threads) {
749 VOL_CV_WAIT(¶ms.thread_done_cv);
753 opr_Verify(pthread_attr_destroy(&attrs) == 0);
755 /* if we're only going to run one init thread, don't bother creating
757 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
758 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
761 VInitVolumePackageThread(¶ms);
764 opr_cv_destroy(¶ms.thread_done_cv);
767 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
768 opr_cv_broadcast(&vol_init_attach_cond);
774 VInitVolumePackageThread(void * args) {
776 struct DiskPartition64 *diskP;
777 struct vinitvolumepackage_thread_t * params;
778 struct diskpartition_queue_t * dpq;
780 params = (vinitvolumepackage_thread_t *) args;
784 /* Attach all the volumes in this partition */
785 while (queue_IsNotEmpty(params)) {
786 int nAttached = 0, nUnattached = 0;
788 if (vinit_attach_abort) {
789 Log("Aborting initialization\n");
793 dpq = queue_First(params,diskpartition_queue_t);
799 opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
806 params->n_threads_complete++;
807 opr_cv_signal(¶ms->thread_done_cv);
811 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
813 #if defined(AFS_DEMAND_ATTACH_FS)
815 * Attach volumes in vice partitions
817 * @param[in] pt calling program type
820 * @note Threaded version of attach partitions.
822 * @post VInit state is 2
825 VInitAttachVolumes(ProgramType pt)
827 opr_Assert(VInit==1);
828 if (pt == fileServer) {
830 struct DiskPartition64 *diskP;
831 struct partition_queue pq;
832 struct volume_init_queue vq;
834 int i, threads, parts;
836 pthread_attr_t attrs;
838 /* create partition work queue */
841 opr_mutex_init(&pq.mutex);
842 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
843 struct diskpartition_queue_t *dp;
844 dp = malloc(sizeof(struct diskpartition_queue_t));
845 opr_Assert(dp != NULL);
847 queue_Append(&pq, dp);
850 /* number of worker threads; at least one, not to exceed the number of partitions */
851 threads = min(parts, vol_attach_threads);
853 /* create volume work queue */
856 opr_mutex_init(&vq.mutex);
858 opr_Verify(pthread_attr_init(&attrs) == 0);
859 opr_Verify(pthread_attr_setdetachstate(&attrs,
860 PTHREAD_CREATE_DETACHED) == 0);
862 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
863 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
866 /* create threads to scan disk partitions. */
867 for (i=0; i < threads; i++) {
868 struct vinitvolumepackage_thread_param *params;
871 params = malloc(sizeof(struct vinitvolumepackage_thread_param));
875 params->nthreads = threads;
876 params->thread = i+1;
879 opr_Verify(pthread_create(&tid, &attrs,
880 &VInitVolumePackageThread,
881 (void*)params) == 0);
882 AFS_SIGSET_RESTORE();
885 VInitPreAttachVolumes(threads, &vq);
887 opr_Verify(pthread_attr_destroy(&attrs) == 0);
888 opr_cv_destroy(&pq.cv);
889 opr_mutex_destroy(&pq.mutex);
890 opr_cv_destroy(&vq.cv);
891 opr_mutex_destroy(&vq.mutex);
895 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
896 opr_cv_broadcast(&vol_init_attach_cond);
903 * Volume package initialization worker thread. Scan partitions for volume
904 * header files. Gather batches of volume ids and dispatch them to
905 * the main thread to be preattached. The volume preattachement is done
906 * in the main thread to avoid global volume lock contention.
909 VInitVolumePackageThread(void *args)
911 struct vinitvolumepackage_thread_param *params;
912 struct DiskPartition64 *partition;
913 struct partition_queue *pq;
914 struct volume_init_queue *vq;
915 struct volume_init_batch *vb;
918 params = (struct vinitvolumepackage_thread_param *)args;
924 vb = malloc(sizeof(struct volume_init_batch));
926 vb->thread = params->thread;
930 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
931 while((partition = VInitNextPartition(pq))) {
935 Log("Partition %s: pre-attaching volumes\n", partition->name);
936 dirp = opendir(VPartitionPath(partition));
938 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
941 while ((vid = VInitNextVolumeId(dirp))) {
942 Volume *vp = calloc(1, sizeof(Volume));
944 vp->device = partition->device;
945 vp->partition = partition;
947 queue_Init(&vp->vnode_list);
948 queue_Init(&vp->rx_call_list);
949 opr_cv_init(&V_attachCV(vp));
951 vb->batch[vb->size++] = vp;
952 if (vb->size == VINIT_BATCH_MAX_SIZE) {
953 opr_mutex_enter(&vq->mutex);
954 queue_Append(vq, vb);
955 opr_cv_broadcast(&vq->cv);
956 opr_mutex_exit(&vq->mutex);
958 vb = malloc(sizeof(struct volume_init_batch));
960 vb->thread = params->thread;
969 opr_mutex_enter(&vq->mutex);
970 queue_Append(vq, vb);
971 opr_cv_broadcast(&vq->cv);
972 opr_mutex_exit(&vq->mutex);
974 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
980 * Read next element from the pre-populated partition list.
982 static struct DiskPartition64*
983 VInitNextPartition(struct partition_queue *pq)
985 struct DiskPartition64 *partition;
986 struct diskpartition_queue_t *dp; /* queue element */
988 if (vinit_attach_abort) {
989 Log("Aborting volume preattach thread.\n");
993 /* get next partition to scan */
994 opr_mutex_enter(&pq->mutex);
995 if (queue_IsEmpty(pq)) {
996 opr_mutex_exit(&pq->mutex);
999 dp = queue_First(pq, diskpartition_queue_t);
1001 opr_mutex_exit(&pq->mutex);
1004 opr_Assert(dp->diskP);
1006 partition = dp->diskP;
1012 * Find next volume id on the partition.
1015 VInitNextVolumeId(DIR *dirp)
1021 while((d = readdir(dirp))) {
1022 if (vinit_attach_abort) {
1023 Log("Aborting volume preattach thread.\n");
1026 ext = strrchr(d->d_name, '.');
1027 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1028 vid = VolumeNumber(d->d_name);
1032 Log("Warning: bogus volume header file: %s\n", d->d_name);
1039 * Preattach volumes in batches to avoid lock contention.
1042 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1044 struct volume_init_batch *vb;
1048 /* dequeue next volume */
1049 opr_mutex_enter(&vq->mutex);
1050 if (queue_IsEmpty(vq)) {
1051 opr_cv_wait(&vq->cv, &vq->mutex);
1053 vb = queue_First(vq, volume_init_batch);
1055 opr_mutex_exit(&vq->mutex);
1059 for (i = 0; i<vb->size; i++) {
1065 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1067 Log("Error looking up volume, code=%d\n", ec);
1070 Log("Warning: Duplicate volume id %" AFS_VOLID_FMT " detected.\n", afs_printable_VolumeId_lu(vp->hashid));
1073 /* put pre-attached volume onto the hash table
1074 * and bring it up to the pre-attached state */
1075 AddVolumeToHashTable(vp, vp->hashid);
1076 AddVolumeToVByPList_r(vp);
1077 VLRU_Init_Node_r(vp);
1078 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1091 #endif /* AFS_DEMAND_ATTACH_FS */
1093 #if !defined(AFS_DEMAND_ATTACH_FS)
1095 * attach all volumes on a given disk partition
1098 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1104 Log("Partition %s: attaching volumes\n", diskP->name);
1105 dirp = opendir(VPartitionPath(diskP));
1107 Log("opendir on Partition %s failed!\n", diskP->name);
1111 while ((dp = readdir(dirp))) {
1113 p = strrchr(dp->d_name, '.');
1115 if (vinit_attach_abort) {
1116 Log("Partition %s: abort attach volumes\n", diskP->name);
1120 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1123 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1125 (*(vp ? nAttached : nUnattached))++;
1126 if (error == VOFFLINE)
1127 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1128 else if (LogLevel >= 5) {
1129 Log("Partition %s: attached volume %d (%s)\n",
1130 diskP->name, VolumeNumber(dp->d_name),
1139 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1144 #endif /* !AFS_DEMAND_ATTACH_FS */
1146 /***************************************************/
1147 /* Shutdown routines */
1148 /***************************************************/
1152 * highly multithreaded volume package shutdown
1154 * with the demand attach fileserver extensions,
1155 * VShutdown has been modified to be multithreaded.
1156 * In order to achieve optimal use of many threads,
1157 * the shutdown code involves one control thread and
1158 * n shutdown worker threads. The control thread
1159 * periodically examines the number of volumes available
1160 * for shutdown on each partition, and produces a worker
1161 * thread allocation schedule. The idea is to eliminate
1162 * redundant scheduling computation on the workers by
1163 * having a single master scheduler.
1165 * The scheduler's objectives are:
1167 * each partition with volumes remaining gets allocated
1168 * at least 1 thread (assuming sufficient threads)
1170 * threads are allocated proportional to the number of
1171 * volumes remaining to be offlined. This ensures that
1172 * the OS I/O scheduler has many requests to elevator
1173 * seek on partitions that will (presumably) take the
1174 * longest amount of time (from now) to finish shutdown
1175 * (3) keep threads busy
1176 * when there are extra threads, they are assigned to
1177 * partitions using a simple round-robin algorithm
1179 * In the future, we may wish to add the ability to adapt
1180 * to the relative performance patterns of each disk
1185 * multi-step shutdown process
1187 * demand attach shutdown is a four-step process. Each
1188 * shutdown "pass" shuts down increasingly more difficult
1189 * volumes. The main purpose is to achieve better cache
1190 * utilization during shutdown.
1193 * shutdown volumes in the unattached, pre-attached
1196 * shutdown attached volumes with cached volume headers
1198 * shutdown all volumes in non-exclusive states
1200 * shutdown all remaining volumes
1203 #ifdef AFS_DEMAND_ATTACH_FS
1209 struct DiskPartition64 * diskP;
1210 struct diskpartition_queue_t * dpq;
1211 vshutdown_thread_t params;
1213 pthread_attr_t attrs;
1215 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1218 Log("VShutdown: aborting attach volumes\n");
1219 vinit_attach_abort = 1;
1220 VOL_CV_WAIT(&vol_init_attach_cond);
1223 for (params.n_parts=0, diskP = DiskPartitionList;
1224 diskP; diskP = diskP->next, params.n_parts++);
1226 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1227 params.n_parts, params.n_parts > 1 ? "s" : "");
1229 vol_shutting_down = 1;
1231 if (vol_attach_threads > 1) {
1232 /* prepare for parallel shutdown */
1233 params.n_threads = vol_attach_threads;
1234 opr_mutex_init(¶ms.lock);
1235 opr_cv_init(¶ms.cv);
1236 opr_cv_init(¶ms.master_cv);
1237 opr_Verify(pthread_attr_init(&attrs) == 0);
1238 opr_Verify(pthread_attr_setdetachstate(&attrs,
1239 PTHREAD_CREATE_DETACHED) == 0);
1240 queue_Init(¶ms);
1242 /* setup the basic partition information structures for
1243 * parallel shutdown */
1244 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1246 struct rx_queue * qp, * nqp;
1250 VVByPListWait_r(diskP);
1251 VVByPListBeginExclusive_r(diskP);
1254 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1255 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1259 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1260 VPartitionPath(diskP), count);
1263 /* build up the pass 0 shutdown work queue */
1264 dpq = malloc(sizeof(struct diskpartition_queue_t));
1265 opr_Assert(dpq != NULL);
1267 queue_Prepend(¶ms, dpq);
1269 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1272 Log("VShutdown: beginning parallel fileserver shutdown\n");
1273 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1274 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1276 /* do pass 0 shutdown */
1277 opr_mutex_enter(¶ms.lock);
1278 for (i=0; i < params.n_threads; i++) {
1279 opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1283 /* wait for all the pass 0 shutdowns to complete */
1284 while (params.n_threads_complete < params.n_threads) {
1285 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1287 params.n_threads_complete = 0;
1289 opr_cv_broadcast(¶ms.cv);
1290 opr_mutex_exit(¶ms.lock);
1292 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1293 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1295 /* run the parallel shutdown scheduler. it will drop the glock internally */
1296 ShutdownController(¶ms);
1298 /* wait for all the workers to finish pass 3 and terminate */
1299 while (params.pass < 4) {
1300 VOL_CV_WAIT(¶ms.cv);
1303 opr_Verify(pthread_attr_destroy(&attrs) == 0);
1304 opr_cv_destroy(¶ms.cv);
1305 opr_cv_destroy(¶ms.master_cv);
1306 opr_mutex_destroy(¶ms.lock);
1308 /* drop the VByPList exclusive reservations */
1309 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1310 VVByPListEndExclusive_r(diskP);
1311 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1312 VPartitionPath(diskP),
1313 params.stats[0][diskP->index],
1314 params.stats[1][diskP->index],
1315 params.stats[2][diskP->index],
1316 params.stats[3][diskP->index]);
1319 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1321 /* if we're only going to run one shutdown thread, don't bother creating
1323 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1325 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1326 VShutdownByPartition_r(diskP);
1330 Log("VShutdown: complete.\n");
1333 #else /* AFS_DEMAND_ATTACH_FS */
1343 Log("VShutdown: aborting attach volumes\n");
1344 vinit_attach_abort = 1;
1345 #ifdef AFS_PTHREAD_ENV
1346 VOL_CV_WAIT(&vol_init_attach_cond);
1348 LWP_WaitProcess(VInitAttachVolumes);
1349 #endif /* AFS_PTHREAD_ENV */
1352 Log("VShutdown: shutting down on-line volumes...\n");
1353 vol_shutting_down = 1;
1354 for (i = 0; i < VolumeHashTable.Size; i++) {
1355 /* try to hold first volume in the hash table */
1356 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1360 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1361 afs_printable_VolumeId_lu(vp->hashid));
1363 /* next, take the volume offline (drops reference count) */
1364 VOffline_r(vp, "File server was shut down");
1368 Log("VShutdown: complete.\n");
1370 #endif /* AFS_DEMAND_ATTACH_FS */
1376 opr_Assert(VInit>0);
1383 * stop new activity (e.g. SALVSYNC) from occurring
1385 * Use this to make the volume package less busy; for example, during
1386 * shutdown. This doesn't actually shutdown/detach anything in the
1387 * volume package, but prevents certain processes from ocurring. For
1388 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1389 * could also use this to prevent new volume attachment, or prevent
1390 * other programs from checking out volumes, etc.
1395 #ifdef AFS_DEMAND_ATTACH_FS
1396 /* make sure we don't try to contact the salvageserver, since it may
1397 * not be around anymore */
1398 vol_disallow_salvsync = 1;
1402 #ifdef AFS_DEMAND_ATTACH_FS
1405 * shutdown control thread
1408 ShutdownController(vshutdown_thread_t * params)
1411 struct DiskPartition64 * diskP;
1413 vshutdown_thread_t shadow;
1415 ShutdownCreateSchedule(params);
1417 while ((params->pass < 4) &&
1418 (params->n_threads_complete < params->n_threads)) {
1419 /* recompute schedule once per second */
1421 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1425 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1426 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1427 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1428 shadow.n_threads_complete, shadow.n_parts_done_pass);
1429 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1431 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1433 diskP->vol_list.len,
1434 shadow.part_thread_target[id],
1435 shadow.part_done_pass[id],
1436 shadow.part_pass_head[id]);
1442 ShutdownCreateSchedule(params);
1446 /* create the shutdown thread work schedule.
1447 * this scheduler tries to implement fairness
1448 * by allocating at least 1 thread to each
1449 * partition with volumes to be shutdown,
1450 * and then it attempts to allocate remaining
1451 * threads based upon the amount of work left
1454 ShutdownCreateSchedule(vshutdown_thread_t * params)
1456 struct DiskPartition64 * diskP;
1457 int sum, thr_workload, thr_left;
1458 int part_residue[VOLMAXPARTS+1];
1461 /* compute the total number of outstanding volumes */
1463 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1464 sum += diskP->vol_list.len;
1467 params->schedule_version++;
1468 params->vol_remaining = sum;
1473 /* compute average per-thread workload */
1474 thr_workload = sum / params->n_threads;
1475 if (sum % params->n_threads)
1478 thr_left = params->n_threads;
1479 memset(&part_residue, 0, sizeof(part_residue));
1481 /* for fairness, give every partition with volumes remaining
1482 * at least one thread */
1483 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1485 if (diskP->vol_list.len) {
1486 params->part_thread_target[id] = 1;
1489 params->part_thread_target[id] = 0;
1493 if (thr_left && thr_workload) {
1494 /* compute length-weighted workloads */
1497 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1499 delta = (diskP->vol_list.len / thr_workload) -
1500 params->part_thread_target[id];
1504 if (delta < thr_left) {
1505 params->part_thread_target[id] += delta;
1508 params->part_thread_target[id] += thr_left;
1516 /* try to assign any leftover threads to partitions that
1517 * had volume lengths closer to needing thread_target+1 */
1518 int max_residue, max_id = 0;
1520 /* compute the residues */
1521 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1523 part_residue[id] = diskP->vol_list.len -
1524 (params->part_thread_target[id] * thr_workload);
1527 /* now try to allocate remaining threads to partitions with the
1528 * highest residues */
1531 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1533 if (part_residue[id] > max_residue) {
1534 max_residue = part_residue[id];
1543 params->part_thread_target[max_id]++;
1545 part_residue[max_id] = 0;
1550 /* punt and give any remaining threads equally to each partition */
1552 if (thr_left >= params->n_parts) {
1553 alloc = thr_left / params->n_parts;
1554 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1556 params->part_thread_target[id] += alloc;
1561 /* finish off the last of the threads */
1562 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1564 params->part_thread_target[id]++;
1570 /* worker thread for parallel shutdown */
1572 VShutdownThread(void * args)
1574 vshutdown_thread_t * params;
1575 int found, pass, schedule_version_save, count;
1576 struct DiskPartition64 *diskP;
1577 struct diskpartition_queue_t * dpq;
1580 params = (vshutdown_thread_t *) args;
1582 /* acquire the shutdown pass 0 lock */
1583 opr_mutex_enter(¶ms->lock);
1585 /* if there's still pass 0 work to be done,
1586 * get a work entry, and do a pass 0 shutdown */
1587 if (queue_IsNotEmpty(params)) {
1588 dpq = queue_First(params, diskpartition_queue_t);
1590 opr_mutex_exit(¶ms->lock);
1596 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1598 params->stats[0][diskP->index] = count;
1599 opr_mutex_enter(¶ms->lock);
1602 params->n_threads_complete++;
1603 if (params->n_threads_complete == params->n_threads) {
1604 /* notify control thread that all workers have completed pass 0 */
1605 opr_cv_signal(¶ms->master_cv);
1607 while (params->pass == 0) {
1608 opr_cv_wait(¶ms->cv, ¶ms->lock);
1612 opr_mutex_exit(¶ms->lock);
1615 pass = params->pass;
1616 opr_Assert(pass > 0);
1618 /* now escalate through the more complicated shutdowns */
1620 schedule_version_save = params->schedule_version;
1622 /* find a disk partition to work on */
1623 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1625 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1626 params->part_thread_target[id]--;
1633 /* hmm. for some reason the controller thread couldn't find anything for
1634 * us to do. let's see if there's anything we can do */
1635 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1637 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1640 } else if (!params->part_done_pass[id]) {
1641 params->part_done_pass[id] = 1;
1642 params->n_parts_done_pass++;
1644 Log("VShutdown: done shutting down volumes on partition %s.\n",
1645 VPartitionPath(diskP));
1651 /* do work on this partition until either the controller
1652 * creates a new schedule, or we run out of things to do
1653 * on this partition */
1656 while (!params->part_done_pass[id] &&
1657 (schedule_version_save == params->schedule_version)) {
1658 /* ShutdownVolumeWalk_r will drop the glock internally */
1659 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1660 if (!params->part_done_pass[id]) {
1661 params->part_done_pass[id] = 1;
1662 params->n_parts_done_pass++;
1664 Log("VShutdown: done shutting down volumes on partition %s.\n",
1665 VPartitionPath(diskP));
1673 params->stats[pass][id] += count;
1675 /* ok, everyone is done this pass, proceed */
1678 params->n_threads_complete++;
1679 while (params->pass == pass) {
1680 if (params->n_threads_complete == params->n_threads) {
1681 /* we are the last thread to complete, so we will
1682 * reinitialize worker pool state for the next pass */
1683 params->n_threads_complete = 0;
1684 params->n_parts_done_pass = 0;
1686 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1688 params->part_done_pass[id] = 0;
1689 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1692 /* compute a new thread schedule before releasing all the workers */
1693 ShutdownCreateSchedule(params);
1695 /* wake up all the workers */
1696 opr_cv_broadcast(¶ms->cv);
1699 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1700 pass, params->n_threads, params->n_parts);
1703 VOL_CV_WAIT(¶ms->cv);
1706 pass = params->pass;
1720 /* shut down all volumes on a given disk partition
1722 * note that this function will not allow mp-fast
1723 * shutdown of a partition */
1725 VShutdownByPartition_r(struct DiskPartition64 * dp)
1731 /* wait for other exclusive ops to finish */
1732 VVByPListWait_r(dp);
1734 /* begin exclusive access */
1735 VVByPListBeginExclusive_r(dp);
1737 /* pick the low-hanging fruit first,
1738 * then do the complicated ones last
1739 * (has the advantage of keeping
1740 * in-use volumes up until the bitter end) */
1741 for (pass = 0, total=0; pass < 4; pass++) {
1742 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1743 total += pass_stats[pass];
1746 /* end exclusive access */
1747 VVByPListEndExclusive_r(dp);
1749 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1750 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1755 /* internal shutdown functionality
1757 * for multi-pass shutdown:
1758 * 0 to only "shutdown" {pre,un}attached and error state volumes
1759 * 1 to also shutdown attached volumes w/ volume header loaded
1760 * 2 to also shutdown attached volumes w/o volume header loaded
1761 * 3 to also shutdown exclusive state volumes
1763 * caller MUST hold exclusive access on the hash chain
1764 * because we drop vol_glock_mutex internally
1766 * this function is reentrant for passes 1--3
1767 * (e.g. multiple threads can cooperate to
1768 * shutdown a partition mp-fast)
1770 * pass 0 is not scaleable because the volume state data is
1771 * synchronized by vol_glock mutex, and the locking overhead
1772 * is too high to drop the lock long enough to do linked list
1776 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1778 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1780 const char *pass_strs[4] = {"{un/pre}attached vols", "vols w/ vol header loaded", "vols w/o vol header loaded", "vols with exclusive state"};
1782 while (ShutdownVolumeWalk_r(dp, pass, &q)) {
1785 Log("VShutdownByPartition: ... shut down %d volumes on %s in pass %d (%s)\n", i, VPartitionPath(dp), pass, pass_strs[pass]);
1792 /* conditionally shutdown one volume on partition dp
1793 * returns 1 if a volume was shutdown in this pass,
1796 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1797 struct rx_queue ** idx)
1799 struct rx_queue *qp, *nqp;
1804 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1805 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1809 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1810 (V_attachState(vp) != VOL_STATE_ERROR) &&
1811 (V_attachState(vp) != VOL_STATE_DELETED) &&
1812 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1816 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1817 (vp->header == NULL)) {
1821 if (VIsExclusiveState(V_attachState(vp))) {
1826 DeleteVolumeFromVByPList_r(vp);
1827 VShutdownVolume_r(vp);
1837 * shutdown a specific volume
1839 /* caller MUST NOT hold a heavyweight ref on vp */
1841 VShutdownVolume_r(Volume * vp)
1845 VCreateReservation_r(vp);
1847 if (LogLevel >= 5) {
1848 Log("VShutdownVolume_r: vid=%" AFS_VOLID_FMT ", device=%d, state=%u\n",
1849 afs_printable_VolumeId_lu(vp->hashid), vp->partition->device,
1850 (unsigned int) V_attachState(vp));
1853 /* wait for other blocking ops to finish */
1854 VWaitExclusiveState_r(vp);
1856 opr_Assert(VIsValidState(V_attachState(vp)));
1858 switch(V_attachState(vp)) {
1859 case VOL_STATE_SALVAGING:
1860 /* Leave salvaging volumes alone. Any in-progress salvages will
1861 * continue working after viced shuts down. This is intentional.
1864 case VOL_STATE_PREATTACHED:
1865 case VOL_STATE_ERROR:
1866 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1867 case VOL_STATE_UNATTACHED:
1868 case VOL_STATE_DELETED:
1870 case VOL_STATE_GOING_OFFLINE:
1871 case VOL_STATE_SHUTTING_DOWN:
1872 case VOL_STATE_ATTACHED:
1876 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1877 afs_printable_VolumeId_lu(vp->hashid));
1879 /* take the volume offline (drops reference count) */
1880 VOffline_r(vp, "File server was shut down");
1887 VCancelReservation_r(vp);
1891 #endif /* AFS_DEMAND_ATTACH_FS */
1894 /***************************************************/
1895 /* Header I/O routines */
1896 /***************************************************/
1899 HeaderName(bit32 magic)
1902 case VOLUMEINFOMAGIC:
1903 return "volume info";
1904 case SMALLINDEXMAGIC:
1905 return "small index";
1906 case LARGEINDEXMAGIC:
1907 return "large index";
1908 case LINKTABLEMAGIC:
1909 return "link table";
1914 /* open a descriptor for the inode (h),
1915 * read in an on-disk structure into buffer (to) of size (size),
1916 * verify versionstamp in structure has magic (magic) and
1917 * optionally verify version (version) if (version) is nonzero
1920 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1923 struct versionStamp *vsn;
1925 afs_sfsize_t nbytes;
1930 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1938 Log("ReadHeader: Failed to open %s header file "
1939 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1940 PrintInode(stmp, h->ih_ino), errno);
1945 vsn = (struct versionStamp *)to;
1946 nbytes = FDH_PREAD(fdP, to, size, 0);
1948 Log("ReadHeader: Failed to read %s header file "
1949 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1950 PrintInode(stmp, h->ih_ino), errno);
1952 FDH_REALLYCLOSE(fdP);
1955 if (nbytes != size) {
1956 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1957 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%d, read=%d\n",
1958 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1959 PrintInode(stmp, h->ih_ino), size, (int)nbytes);
1961 FDH_REALLYCLOSE(fdP);
1964 if (vsn->magic != magic) {
1965 Log("ReadHeader: Incorrect magic for %s header file "
1966 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=0x%x, read=0x%x\n",
1967 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1968 PrintInode(stmp, h->ih_ino), magic, vsn->magic);
1970 FDH_REALLYCLOSE(fdP);
1976 /* Check is conditional, in case caller wants to inspect version himself */
1977 if (version && vsn->version != version) {
1978 Log("ReadHeader: Incorrect version for %s header file "
1979 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%x, read=%x\n",
1980 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid), PrintInode(stmp, h->ih_ino),
1981 version, vsn->version);
1987 WriteVolumeHeader_r(Error * ec, Volume * vp)
1989 IHandle_t *h = V_diskDataHandle(vp);
1999 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
2000 != sizeof(V_disk(vp))) {
2002 FDH_REALLYCLOSE(fdP);
2008 /* VolumeHeaderToDisk
2009 * Allows for storing 64 bit inode numbers in on-disk volume header
2012 /* convert in-memory representation of a volume header to the
2013 * on-disk representation of a volume header */
2015 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2018 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2019 dh->stamp = h->stamp;
2021 dh->parent = h->parent;
2023 #ifdef AFS_64BIT_IOPS_ENV
2024 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2025 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2026 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2027 dh->smallVnodeIndex_hi =
2028 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2029 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2030 dh->largeVnodeIndex_hi =
2031 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2032 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2033 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2035 dh->volumeInfo_lo = h->volumeInfo;
2036 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2037 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2038 dh->linkTable_lo = h->linkTable;
2042 /* DiskToVolumeHeader
2043 * Converts an on-disk representation of a volume header to
2044 * the in-memory representation of a volume header.
2046 * Makes the assumption that AFS has *always*
2047 * zero'd the volume header file so that high parts of inode
2048 * numbers are 0 in older (SGI EFS) volume header files.
2051 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2053 memset(h, 0, sizeof(VolumeHeader_t));
2054 h->stamp = dh->stamp;
2056 h->parent = dh->parent;
2058 #ifdef AFS_64BIT_IOPS_ENV
2060 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2062 h->smallVnodeIndex =
2063 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2064 smallVnodeIndex_hi << 32);
2066 h->largeVnodeIndex =
2067 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2068 largeVnodeIndex_hi << 32);
2070 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2072 h->volumeInfo = dh->volumeInfo_lo;
2073 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2074 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2075 h->linkTable = dh->linkTable_lo;
2080 /***************************************************/
2081 /* Volume Attachment routines */
2082 /***************************************************/
2084 #ifdef AFS_DEMAND_ATTACH_FS
2086 * pre-attach a volume given its path.
2088 * @param[out] ec outbound error code
2089 * @param[in] partition partition path string
2090 * @param[in] name volume id string
2092 * @return volume object pointer
2094 * @note A pre-attached volume will only have its partition
2095 * and hashid fields initialized. At first call to
2096 * VGetVolume, the volume will be fully attached.
2100 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2104 vp = VPreAttachVolumeByName_r(ec, partition, name);
2110 * pre-attach a volume given its path.
2112 * @param[out] ec outbound error code
2113 * @param[in] partition path to vice partition
2114 * @param[in] name volume id string
2116 * @return volume object pointer
2118 * @pre VOL_LOCK held
2120 * @internal volume package internal use only.
2123 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2125 return VPreAttachVolumeById_r(ec,
2127 VolumeNumber(name));
2131 * pre-attach a volume given its path and numeric volume id.
2133 * @param[out] ec error code return
2134 * @param[in] partition path to vice partition
2135 * @param[in] volumeId numeric volume id
2137 * @return volume object pointer
2139 * @pre VOL_LOCK held
2141 * @internal volume package internal use only.
2144 VPreAttachVolumeById_r(Error * ec,
2149 struct DiskPartition64 *partp;
2153 opr_Assert(programType == fileServer);
2155 if (!(partp = VGetPartition_r(partition, 0))) {
2157 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2161 /* ensure that any vp we pass to VPreAttachVolumeByVp_r
2162 * is NOT in exclusive state.
2165 vp = VLookupVolume_r(ec, volumeId, NULL);
2171 if (vp && VIsExclusiveState(V_attachState(vp))) {
2172 VCreateReservation_r(vp);
2173 VWaitExclusiveState_r(vp);
2174 VCancelReservation_r(vp);
2176 goto retry; /* look up volume again */
2179 /* vp == NULL or vp not exclusive both OK */
2181 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2185 * preattach a volume.
2187 * @param[out] ec outbound error code
2188 * @param[in] partp pointer to partition object
2189 * @param[in] vp pointer to volume object
2190 * @param[in] vid volume id
2192 * @return volume object pointer
2194 * @pre VOL_LOCK is held.
2196 * @pre vp (if specified) must not be in exclusive state.
2198 * @warning Returned volume object pointer does not have to
2199 * equal the pointer passed in as argument vp. There
2200 * are potential race conditions which can result in
2201 * the pointers having different values. It is up to
2202 * the caller to make sure that references are handled
2203 * properly in this case.
2205 * @note If there is already a volume object registered with
2206 * the same volume id, its pointer MUST be passed as
2207 * argument vp. Failure to do so will result in a silent
2208 * failure to preattach.
2210 * @internal volume package internal use only.
2213 VPreAttachVolumeByVp_r(Error * ec,
2214 struct DiskPartition64 * partp,
2222 /* don't proceed unless it's safe */
2224 opr_Assert(!VIsExclusiveState(V_attachState(vp)));
2227 /* check to see if pre-attach already happened */
2229 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2230 (V_attachState(vp) != VOL_STATE_DELETED) &&
2231 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2232 !VIsErrorState(V_attachState(vp))) {
2234 * pre-attach is a no-op in all but the following cases:
2236 * - volume is unattached
2237 * - volume is in an error state
2238 * - volume is pre-attached
2240 Log("VPreattachVolumeByVp_r: volume %" AFS_VOLID_FMT " not in quiescent state (state %u flags 0x%x)\n",
2241 afs_printable_VolumeId_lu(vid), V_attachState(vp),
2245 /* we're re-attaching a volume; clear out some old state */
2246 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2248 if (V_partition(vp) != partp) {
2249 /* XXX potential race */
2250 DeleteVolumeFromVByPList_r(vp);
2253 /* if we need to allocate a new Volume struct,
2254 * go ahead and drop the vol glock, otherwise
2255 * do the basic setup synchronised, as it's
2256 * probably not worth dropping the lock */
2259 /* allocate the volume structure */
2260 vp = nvp = calloc(1, sizeof(Volume));
2261 opr_Assert(vp != NULL);
2262 queue_Init(&vp->vnode_list);
2263 queue_Init(&vp->rx_call_list);
2264 opr_cv_init(&V_attachCV(vp));
2267 /* link the volume with its associated vice partition */
2268 vp->device = partp->device;
2269 vp->partition = partp;
2272 vp->specialStatus = 0;
2274 /* if we dropped the lock, reacquire the lock,
2275 * check for pre-attach races, and then add
2276 * the volume to the hash table */
2279 nvp = VLookupVolume_r(ec, vid, NULL);
2284 } else if (nvp) { /* race detected */
2289 /* hack to make up for VChangeState_r() decrementing
2290 * the old state counter */
2291 VStats.state_levels[0]++;
2295 /* put pre-attached volume onto the hash table
2296 * and bring it up to the pre-attached state */
2297 AddVolumeToHashTable(vp, vp->hashid);
2298 AddVolumeToVByPList_r(vp);
2299 VLRU_Init_Node_r(vp);
2300 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2303 Log("VPreAttachVolumeByVp_r: volume %" AFS_VOLID_FMT " pre-attached\n", afs_printable_VolumeId_lu(vp->hashid));
2311 #endif /* AFS_DEMAND_ATTACH_FS */
2313 /* Attach an existing volume, given its pathname, and return a
2314 pointer to the volume header information. The volume also
2315 normally goes online at this time. An offline volume
2316 must be reattached to make it go online */
2318 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2322 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2328 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2331 struct DiskPartition64 *partp;
2336 #ifdef AFS_DEMAND_ATTACH_FS
2337 VolumeStats stats_save;
2339 #endif /* AFS_DEMAND_ATTACH_FS */
2343 volumeId = VolumeNumber(name);
2345 if (!(partp = VGetPartition_r(partition, 0))) {
2347 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2351 if (VRequiresPartLock()) {
2352 opr_Assert(VInit == 3);
2353 VLockPartition_r(partition);
2354 } else if (programType == fileServer) {
2355 #ifdef AFS_DEMAND_ATTACH_FS
2356 /* lookup the volume in the hash table */
2357 vp = VLookupVolume_r(ec, volumeId, NULL);
2363 /* save any counters that are supposed to
2364 * be monotonically increasing over the
2365 * lifetime of the fileserver */
2366 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2368 memset(&stats_save, 0, sizeof(VolumeStats));
2371 /* if there's something in the hash table, and it's not
2372 * in the pre-attach state, then we may need to detach
2373 * it before proceeding */
2374 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2375 VCreateReservation_r(vp);
2376 VWaitExclusiveState_r(vp);
2378 /* at this point state must be one of:
2388 if (vp->specialStatus == VBUSY)
2391 /* if it's already attached, see if we can return it */
2392 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2393 VGetVolumeByVp_r(ec, vp);
2394 if (V_inUse(vp) == fileServer) {
2395 VCancelReservation_r(vp);
2399 /* otherwise, we need to detach, and attempt to re-attach */
2400 VDetachVolume_r(ec, vp);
2402 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2405 /* if it isn't fully attached, delete from the hash tables,
2406 and let the refcounter handle the rest */
2407 DeleteVolumeFromHashTable(vp);
2408 DeleteVolumeFromVByPList_r(vp);
2411 VCancelReservation_r(vp);
2415 /* pre-attach volume if it hasn't been done yet */
2417 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2418 (V_attachState(vp) == VOL_STATE_DELETED) ||
2419 (V_attachState(vp) == VOL_STATE_ERROR)) {
2421 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2427 opr_Assert(vp != NULL);
2429 /* handle pre-attach races
2431 * multiple threads can race to pre-attach a volume,
2432 * but we can't let them race beyond that
2434 * our solution is to let the first thread to bring
2435 * the volume into an exclusive state win; the other
2436 * threads just wait until it finishes bringing the
2437 * volume online, and then they do a vgetvolumebyvp
2439 if (svp && (svp != vp)) {
2440 /* wait for other exclusive ops to finish */
2441 VCreateReservation_r(vp);
2442 VWaitExclusiveState_r(vp);
2444 /* get a heavyweight ref, kill the lightweight ref, and return */
2445 VGetVolumeByVp_r(ec, vp);
2446 VCancelReservation_r(vp);
2450 /* at this point, we are chosen as the thread to do
2451 * demand attachment for this volume. all other threads
2452 * doing a getvolume on vp->hashid will block until we finish */
2454 /* make sure any old header cache entries are invalidated
2455 * before proceeding */
2456 FreeVolumeHeader(vp);
2458 VChangeState_r(vp, VOL_STATE_ATTACHING);
2460 /* restore any saved counters */
2461 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2462 #else /* AFS_DEMAND_ATTACH_FS */
2463 vp = VGetVolume_r(ec, volumeId);
2465 if (V_inUse(vp) == fileServer)
2467 if (vp->specialStatus == VBUSY)
2469 VDetachVolume_r(ec, vp);
2471 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2475 #endif /* AFS_DEMAND_ATTACH_FS */
2479 strcpy(path, VPartitionPath(partp));
2483 strcat(path, OS_DIRSEP);
2487 vp = (Volume *) calloc(1, sizeof(Volume));
2488 opr_Assert(vp != NULL);
2489 vp->hashid = volumeId;
2490 vp->device = partp->device;
2491 vp->partition = partp;
2492 queue_Init(&vp->vnode_list);
2493 queue_Init(&vp->rx_call_list);
2494 #ifdef AFS_DEMAND_ATTACH_FS
2495 opr_cv_init(&V_attachCV(vp));
2496 #endif /* AFS_DEMAND_ATTACH_FS */
2499 /* attach2 is entered without any locks, and returns
2500 * with vol_glock_mutex held */
2501 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2503 if (VCanUseFSSYNC() && vp) {
2504 #ifdef AFS_DEMAND_ATTACH_FS
2505 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2506 /* mark volume header as in use so that volser crashes lead to a
2507 * salvage attempt */
2508 VUpdateVolume_r(ec, vp, 0);
2510 /* for dafs, we should tell the fileserver, except for V_PEEK
2511 * where we know it is not necessary */
2512 if (mode == V_PEEK) {
2513 vp->needsPutBack = 0;
2515 vp->needsPutBack = VOL_PUTBACK;
2517 #else /* !AFS_DEMAND_ATTACH_FS */
2518 /* duplicate computation in fssync.c about whether the server
2519 * takes the volume offline or not. If the volume isn't
2520 * offline, we must not return it when we detach the volume,
2521 * or the server will abort */
2522 if (mode == V_READONLY || mode == V_PEEK
2523 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2524 vp->needsPutBack = 0;
2526 vp->needsPutBack = VOL_PUTBACK;
2527 #endif /* !AFS_DEMAND_ATTACH_FS */
2529 #ifdef FSSYNC_BUILD_CLIENT
2530 /* Only give back the vol to the fileserver if we checked it out; attach2
2531 * will set checkedOut only if we successfully checked it out from the
2533 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2535 #ifdef AFS_DEMAND_ATTACH_FS
2536 /* If we couldn't attach but we scheduled a salvage, we already
2537 * notified the fileserver; don't online it now */
2538 if (*ec != VSALVAGING)
2539 #endif /* AFS_DEMAND_ATTACH_FS */
2540 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2543 if (programType == fileServer && vp) {
2544 #ifdef AFS_DEMAND_ATTACH_FS
2546 * we can get here in cases where we don't "own"
2547 * the volume (e.g. volume owned by a utility).
2548 * short circuit around potential disk header races.
2550 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2554 VUpdateVolume_r(ec, vp, 0);
2556 Log("VAttachVolume: Error updating volume\n");
2561 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2562 #ifndef AFS_DEMAND_ATTACH_FS
2563 /* This is a hack: by temporarily setting the incore
2564 * dontSalvage flag ON, the volume will be put back on the
2565 * Update list (with dontSalvage OFF again). It will then
2566 * come back in N minutes with DONT_SALVAGE eventually
2567 * set. This is the way that volumes that have never had
2568 * it set get it set; or that volumes that have been
2569 * offline without DONT SALVAGE having been set also
2570 * eventually get it set */
2571 V_dontSalvage(vp) = DONT_SALVAGE;
2572 #endif /* !AFS_DEMAND_ATTACH_FS */
2573 VAddToVolumeUpdateList_r(ec, vp);
2575 Log("VAttachVolume: Error adding volume to update list\n");
2582 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n", afs_printable_VolumeId_lu(V_id(vp)),
2587 if (VRequiresPartLock()) {
2588 VUnlockPartition_r(partition);
2591 #ifdef AFS_DEMAND_ATTACH_FS
2592 /* attach failed; make sure we're in error state */
2593 if (vp && !VIsErrorState(V_attachState(vp))) {
2594 VChangeState_r(vp, VOL_STATE_ERROR);
2596 #endif /* AFS_DEMAND_ATTACH_FS */
2603 #ifdef AFS_DEMAND_ATTACH_FS
2604 /* VAttachVolumeByVp_r
2606 * finish attaching a volume that is
2607 * in a less than fully attached state
2609 /* caller MUST hold a ref count on vp */
2611 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2613 char name[VMAXPATHLEN];
2615 struct DiskPartition64 *partp;
2619 Volume * nvp = NULL;
2620 VolumeStats stats_save;
2624 /* volume utility should never call AttachByVp */
2625 opr_Assert(programType == fileServer);
2627 volumeId = vp->hashid;
2628 partp = vp->partition;
2629 VolumeExternalName_r(volumeId, name, sizeof(name));
2632 /* if another thread is performing a blocking op, wait */
2633 VWaitExclusiveState_r(vp);
2635 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2637 /* if it's already attached, see if we can return it */
2638 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2639 VGetVolumeByVp_r(ec, vp);
2640 if (V_inUse(vp) == fileServer) {
2643 if (vp->specialStatus == VBUSY)
2645 VDetachVolume_r(ec, vp);
2647 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2653 /* pre-attach volume if it hasn't been done yet */
2655 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2656 (V_attachState(vp) == VOL_STATE_DELETED) ||
2657 (V_attachState(vp) == VOL_STATE_ERROR)) {
2658 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2664 VCreateReservation_r(nvp);
2669 opr_Assert(vp != NULL);
2670 VChangeState_r(vp, VOL_STATE_ATTACHING);
2672 /* restore monotonically increasing stats */
2673 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2677 /* compute path to disk header */
2678 strcpy(path, VPartitionPath(partp));
2682 strcat(path, OS_DIRSEP);
2687 * NOTE: attach2 is entered without any locks, and returns
2688 * with vol_glock_mutex held */
2689 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2692 * the event that an error was encountered, or
2693 * the volume was not brought to an attached state
2694 * for any reason, skip to the end. We cannot
2695 * safely call VUpdateVolume unless we "own" it.
2699 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2703 VUpdateVolume_r(ec, vp, 0);
2705 Log("VAttachVolume: Error updating volume %" AFS_VOLID_FMT "\n",
2706 afs_printable_VolumeId_lu(vp->hashid));
2710 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2711 #ifndef AFS_DEMAND_ATTACH_FS
2712 /* This is a hack: by temporarily setting the incore
2713 * dontSalvage flag ON, the volume will be put back on the
2714 * Update list (with dontSalvage OFF again). It will then
2715 * come back in N minutes with DONT_SALVAGE eventually
2716 * set. This is the way that volumes that have never had
2717 * it set get it set; or that volumes that have been
2718 * offline without DONT SALVAGE having been set also
2719 * eventually get it set */
2720 V_dontSalvage(vp) = DONT_SALVAGE;
2721 #endif /* !AFS_DEMAND_ATTACH_FS */
2722 VAddToVolumeUpdateList_r(ec, vp);
2724 Log("VAttachVolume: Error adding volume %" AFS_VOLID_FMT " to update list\n",
2725 afs_printable_VolumeId_lu(vp->hashid));
2732 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n",
2733 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
2736 VCancelReservation_r(nvp);
2739 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2740 if (vp && !VIsErrorState(V_attachState(vp))) {
2741 VChangeState_r(vp, VOL_STATE_ERROR);
2750 * lock a volume on disk (non-blocking).
2752 * @param[in] vp The volume to lock
2753 * @param[in] locktype READ_LOCK or WRITE_LOCK
2755 * @return operation status
2756 * @retval 0 success, lock was obtained
2757 * @retval EBUSY a conflicting lock was held by another process
2758 * @retval EIO error acquiring lock
2760 * @pre If we're in the fileserver, vp is in an exclusive state
2762 * @pre vp is not already locked
2765 VLockVolumeNB(Volume *vp, int locktype)
2769 opr_Assert(programType != fileServer
2770 || VIsExclusiveState(V_attachState(vp)));
2771 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2773 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2775 V_attachFlags(vp) |= VOL_LOCKED;
2782 * unlock a volume on disk that was locked with VLockVolumeNB.
2784 * @param[in] vp volume to unlock
2786 * @pre If we're in the fileserver, vp is in an exclusive state
2788 * @pre vp has already been locked
2791 VUnlockVolume(Volume *vp)
2793 opr_Assert(programType != fileServer
2794 || VIsExclusiveState(V_attachState(vp)));
2795 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2797 VUnlockVolumeById(vp->hashid, vp->partition);
2799 V_attachFlags(vp) &= ~VOL_LOCKED;
2801 #endif /* AFS_DEMAND_ATTACH_FS */
2804 * read in a vol header, possibly lock the vol header, and possibly check out
2805 * the vol header from the fileserver, as part of volume attachment.
2807 * @param[out] ec error code
2808 * @param[in] vp volume pointer object
2809 * @param[in] partp disk partition object of the attaching partition
2810 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2812 * @param[in] peek 1 to just try to read in the volume header and make sure
2813 * we don't try to lock the vol, or check it out from
2814 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2816 * @param[out] acheckedOut If we successfully checked-out the volume from
2817 * the fileserver (if we needed to), this is set
2818 * to 1, otherwise it is untouched.
2820 * @note As part of DAFS volume attachment, the volume header may be either
2821 * read- or write-locked to ensure mutual exclusion of certain volume
2822 * operations. In some cases in order to determine whether we need to
2823 * read- or write-lock the header, we need to read in the header to see
2824 * if the volume is RW or not. So, if we read in the header under a
2825 * read-lock and determine that we actually need a write-lock on the
2826 * volume header, this function will drop the read lock, acquire a write
2827 * lock, and read the header in again.
2830 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2831 int mode, int peek, int *acheckedOut)
2833 struct VolumeDiskHeader diskHeader;
2834 struct VolumeHeader header;
2837 int lock_tries = 0, checkout_tries = 0;
2839 VolumeId volid = vp->hashid;
2840 #ifdef FSSYNC_BUILD_CLIENT
2841 int checkout, done_checkout = 0;
2842 #endif /* FSSYNC_BUILD_CLIENT */
2843 #ifdef AFS_DEMAND_ATTACH_FS
2844 int locktype = 0, use_locktype = -1;
2845 #endif /* AFS_DEMAND_ATTACH_FS */
2851 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2852 Log("VAttachVolume: retried too many times trying to lock header for "
2853 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2854 VPartitionPath(partp));
2858 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2859 Log("VAttachVolume: retried too many times trying to checkout "
2860 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2861 VPartitionPath(partp));
2866 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2867 /* short-circuit the 'volume does not exist' case */
2872 #ifdef FSSYNC_BUILD_CLIENT
2873 checkout = !done_checkout;
2875 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2877 memset(&res, 0, sizeof(res));
2879 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2882 if (res.hdr.reason == FSYNC_SALVAGE) {
2883 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2884 afs_printable_uint32_lu(volid));
2887 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2888 afs_printable_uint32_lu(volid));
2889 *ec = VNOVOL; /* XXXX */
2897 #ifdef AFS_DEMAND_ATTACH_FS
2898 if (use_locktype < 0) {
2899 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2900 * if it turns out to be RW */
2901 locktype = VVolLockType(mode, 0);
2904 /* a previous try says we should use use_locktype to lock the volume,
2906 locktype = use_locktype;
2909 if (!peek && locktype) {
2910 code = VLockVolumeNB(vp, locktype);
2912 if (code == EBUSY) {
2913 Log("VAttachVolume: another program has vol %lu locked\n",
2914 afs_printable_uint32_lu(volid));
2916 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2917 code, afs_printable_uint32_lu(volid));
2924 #endif /* AFS_DEMAND_ATTACH_FS */
2926 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2936 DiskToVolumeHeader(&header, &diskHeader);
2938 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2939 header.largeVnodeIndex);
2940 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2941 header.smallVnodeIndex);
2942 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2944 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2947 /* only need to do this once */
2949 GetVolumeHeader(vp);
2953 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2954 /* demand attach changes the V_PEEK mechanism
2956 * we can now suck the current disk data structure over
2957 * the fssync interface without going to disk
2959 * (technically, we don't need to restrict this feature
2960 * to demand attach fileservers. However, I'm trying
2961 * to limit the number of common code changes)
2963 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2965 res.payload.len = sizeof(VolumeDiskData);
2966 res.payload.buf = &(V_disk(vp));
2968 if (FSYNC_VolOp(vp->hashid,
2970 FSYNC_VOL_QUERY_HDR,
2973 goto disk_header_loaded;
2976 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2977 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2978 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2980 #ifdef AFS_DEMAND_ATTACH_FS
2983 IncUInt64(&VStats.hdr_loads);
2984 IncUInt64(&vp->stats.hdr_loads);
2986 #endif /* AFS_DEMAND_ATTACH_FS */
2989 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2990 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2994 #ifdef AFS_DEMAND_ATTACH_FS
2995 # ifdef FSSYNC_BUILD_CLIENT
2997 # endif /* FSSYNC_BUILD_CLIENT */
2999 /* if the lock type we actually used to lock the volume is different than
3000 * the lock type we should have used, retry with the lock type we should
3002 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
3003 if (locktype != use_locktype) {
3007 #endif /* AFS_DEMAND_ATTACH_FS */
3012 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
3013 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
3015 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
3017 if (code == SYNC_DENIED) {
3018 /* must retry checkout; fileserver no longer thinks we have
3024 } else if (code != SYNC_OK) {
3028 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3031 /* either we are going to be called again for a second pass, or we
3032 * encountered an error; clean up in either case */
3034 #ifdef AFS_DEMAND_ATTACH_FS
3035 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3038 #endif /* AFS_DEMAND_ATTACH_FS */
3039 if (vp->linkHandle) {
3040 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3041 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3042 IH_RELEASE(vp->diskDataHandle);
3043 IH_RELEASE(vp->linkHandle);
3049 FreeVolumeHeader(vp);
3059 #ifdef AFS_DEMAND_ATTACH_FS
3061 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3062 Volume *vp, int *acheckedOut)
3066 if (vp->pending_vol_op) {
3070 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3072 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3074 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3075 } else if (code == 0) {
3076 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3079 /* we need the vol header to determine if the volume can be
3080 * left online for the vop, so... get the header */
3084 /* attach header with peek=1 to avoid checking out the volume
3085 * or locking it; we just want the header info, we're not
3086 * messing with the volume itself at all */
3087 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3094 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3095 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3097 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3100 /* make sure we grab a new vol header and re-open stuff on
3101 * actual attachment; we can't keep the data we grabbed, since
3102 * it was not done under a lock and thus not safe */
3103 FreeVolumeHeader(vp);
3104 VReleaseVolumeHandles_r(vp);
3107 /* see if the pending volume op requires exclusive access */
3108 switch (vp->pending_vol_op->vol_op_state) {
3109 case FSSYNC_VolOpPending:
3110 /* this should never happen */
3111 opr_Assert(vp->pending_vol_op->vol_op_state
3112 != FSSYNC_VolOpPending);
3115 case FSSYNC_VolOpRunningUnknown:
3116 /* this should never happen; we resolved 'unknown' above */
3117 opr_Assert(vp->pending_vol_op->vol_op_state
3118 != FSSYNC_VolOpRunningUnknown);
3121 case FSSYNC_VolOpRunningOffline:
3122 /* mark the volume down */
3124 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3126 /* do not set V_offlineMessage here; we don't have ownership of
3127 * the volume (and probably do not have the header loaded), so we
3128 * can't alter the disk header */
3130 /* check to see if we should set the specialStatus flag */
3131 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3132 /* don't overwrite specialStatus if it was already set to
3133 * something else (e.g. VMOVED) */
3134 if (!vp->specialStatus) {
3135 vp->specialStatus = VBUSY;
3147 #endif /* AFS_DEMAND_ATTACH_FS */
3150 * volume attachment helper function.
3152 * @param[out] ec error code
3153 * @param[in] volumeId volume ID of the attaching volume
3154 * @param[in] path full path to the volume header .vol file
3155 * @param[in] partp disk partition object for the attaching partition
3156 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3157 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3158 * DAFS) should already be initialized
3159 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3160 * if there is a volume operation running for this volume
3161 * that should set the volume to VBUSY during its run. 0
3162 * otherwise. (see VVolOpSetVBusy_r)
3163 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3165 * @param[out] acheckedOut If we successfully checked-out the volume from
3166 * the fileserver (if we needed to), this is set
3167 * to 1, otherwise it is 0.
3169 * @return pointer to the semi-attached volume pointer
3170 * @retval NULL an error occurred (check value of *ec)
3171 * @retval vp volume successfully attaching
3173 * @pre no locks held
3175 * @post VOL_LOCK held
3178 attach2(Error * ec, VolumeId volumeId, char *path, struct DiskPartition64 *partp,
3179 Volume * vp, int isbusy, int mode, int *acheckedOut)
3181 /* have we read in the header successfully? */
3182 int read_header = 0;
3184 #ifdef AFS_DEMAND_ATTACH_FS
3185 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3189 /* in the case of an error, to what state should the volume be
3191 VolState error_state = VOL_STATE_ERROR;
3192 #endif /* AFS_DEMAND_ATTACH_FS */
3196 vp->vnodeIndex[vLarge].handle = NULL;
3197 vp->vnodeIndex[vSmall].handle = NULL;
3198 vp->diskDataHandle = NULL;
3199 vp->linkHandle = NULL;
3203 #ifdef AFS_DEMAND_ATTACH_FS
3204 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3206 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3209 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3210 #endif /* !AFS_DEMAND_ATTACH_FS */
3212 if (*ec == VNOVOL) {
3213 /* if the volume doesn't exist, skip straight to 'error' so we don't
3214 * request a salvage */
3215 goto unlocked_error;
3221 /* ensure that we don't override specialStatus if it was set to
3222 * something else (e.g. VMOVED) */
3223 if (isbusy && !vp->specialStatus) {
3224 vp->specialStatus = VBUSY;
3226 vp->shuttingDown = 0;
3227 vp->goingOffline = 0;
3229 #ifdef AFS_DEMAND_ATTACH_FS
3230 vp->stats.last_attach = FT_ApproxTime();
3231 vp->stats.attaches++;
3235 IncUInt64(&VStats.attaches);
3236 vp->cacheCheck = ++VolumeCacheCheck;
3237 /* just in case this ever rolls over */
3238 if (!vp->cacheCheck)
3239 vp->cacheCheck = ++VolumeCacheCheck;
3242 #ifdef AFS_DEMAND_ATTACH_FS
3243 V_attachFlags(vp) |= VOL_HDR_LOADED;
3244 vp->stats.last_hdr_load = vp->stats.last_attach;
3245 #endif /* AFS_DEMAND_ATTACH_FS */
3249 struct IndexFileHeader iHead;
3252 * We just read in the diskstuff part of the header. If the detailed
3253 * volume stats area has not yet been initialized, we should bzero the
3254 * area and mark it as initialized.
3256 if (!(V_stat_initialized(vp))) {
3257 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3258 V_stat_initialized(vp) = 1;
3261 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3262 (char *)&iHead, sizeof(iHead),
3263 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3266 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3271 struct IndexFileHeader iHead;
3273 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3274 (char *)&iHead, sizeof(iHead),
3275 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3278 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3282 #ifdef AFS_NAMEI_ENV
3284 struct versionStamp stamp;
3286 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3287 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3290 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3293 #endif /* AFS_NAMEI_ENV */
3295 #if defined(AFS_DEMAND_ATTACH_FS)
3296 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3298 if (!VCanScheduleSalvage()) {
3299 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3301 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3306 /* volume operation in progress */
3308 /* we have already transitioned the vp away from ATTACHING state, so we
3309 * can go right to the end of attach2, and we do not need to transition
3311 goto error_notbroken;
3313 #else /* AFS_DEMAND_ATTACH_FS */
3315 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3316 goto unlocked_error;
3318 #endif /* AFS_DEMAND_ATTACH_FS */
3320 if (V_needsSalvaged(vp)) {
3321 if (vp->specialStatus)
3322 vp->specialStatus = 0;
3324 #if defined(AFS_DEMAND_ATTACH_FS)
3325 if (!VCanScheduleSalvage()) {
3326 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3328 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3331 #else /* AFS_DEMAND_ATTACH_FS */
3333 #endif /* AFS_DEMAND_ATTACH_FS */
3339 vp->nextVnodeUnique = V_uniquifier(vp);
3341 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3342 if (!V_needsSalvaged(vp)) {
3343 V_needsSalvaged(vp) = 1;
3344 VUpdateVolume_r(ec, vp, 0);
3346 #if defined(AFS_DEMAND_ATTACH_FS)
3347 if (!VCanScheduleSalvage()) {
3348 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3350 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3353 #else /* AFS_DEMAND_ATTACH_FS */
3354 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3356 #endif /* AFS_DEMAND_ATTACH_FS */
3361 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3362 /* Only check destroyMe if we are the fileserver, since the
3363 * volserver et al sometimes need to work with volumes with
3364 * destroyMe set. Examples are 'temporary' volumes the
3365 * volserver creates, and when we create a volume (destroyMe
3366 * is set on creation; sometimes a separate volserver
3367 * transaction is created to clear destroyMe).
3370 #if defined(AFS_DEMAND_ATTACH_FS)
3371 /* schedule a salvage so the volume goes away on disk */
3372 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3373 VChangeState_r(vp, VOL_STATE_ERROR);
3376 #endif /* AFS_DEMAND_ATTACH_FS */
3377 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3382 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3383 #ifndef BITMAP_LATER
3384 if (programType == fileServer && VolumeWriteable(vp)) {
3386 for (i = 0; i < nVNODECLASSES; i++) {
3387 VGetBitmap_r(ec, vp, i);
3389 #ifdef AFS_DEMAND_ATTACH_FS
3390 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3392 #endif /* AFS_DEMAND_ATTACH_FS */
3393 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3399 #endif /* BITMAP_LATER */
3401 if (VInit >= 2 && V_needsCallback(vp)) {
3402 if (V_BreakVolumeCallbacks) {
3403 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3404 afs_printable_uint32_lu(V_id(vp)));
3405 V_needsCallback(vp) = 0;
3407 (*V_BreakVolumeCallbacks) (V_id(vp));
3410 VUpdateVolume_r(ec, vp, 0);
3412 #ifdef FSSYNC_BUILD_CLIENT
3413 else if (VCanUseFSSYNC()) {
3414 afs_int32 fsync_code;
3416 V_needsCallback(vp) = 0;
3418 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3422 V_needsCallback(vp) = 1;
3423 Log("Error trying to tell the fileserver to break callbacks for "
3424 "changed volume %lu; error code %ld\n",
3425 afs_printable_uint32_lu(V_id(vp)),
3426 afs_printable_int32_ld(fsync_code));
3428 VUpdateVolume_r(ec, vp, 0);
3431 #endif /* FSSYNC_BUILD_CLIENT */
3434 Log("VAttachVolume: error %d clearing needsCallback on volume "
3435 "%lu; needs salvage\n", (int)*ec,
3436 afs_printable_uint32_lu(V_id(vp)));
3437 #ifdef AFS_DEMAND_ATTACH_FS
3438 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3440 #else /* !AFS_DEMAND_ATTACH_FS */
3442 #endif /* !AFS_DEMAND_ATTACh_FS */
3447 if (programType == fileServer) {
3448 if (vp->specialStatus)
3449 vp->specialStatus = 0;
3450 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3451 V_inUse(vp) = fileServer;
3452 V_offlineMessage(vp)[0] = '\0';
3454 #ifdef AFS_DEMAND_ATTACH_FS
3455 /* check if the volume is actually usable. only do this for DAFS; for
3456 * non-DAFS, volumes that are not inService/blessed can still be
3457 * attached, even if clients cannot access them. this is relevant
3458 * because for non-DAFS, we try to attach the volume when e.g.
3459 * volserver gives us back then vol when its done with it, but
3460 * volserver may give us back a volume that is not inService/blessed. */
3464 /* Put the vol into PREATTACHED state, so if someone tries to
3465 * access it again, we try to attach, see that we're not blessed,
3466 * and give a VNOVOL error again. Putting it into UNATTACHED state
3467 * would result in a VOFFLINE error instead. */
3468 error_state = VOL_STATE_PREATTACHED;
3470 /* mimic e.g. GetVolume errors */
3471 if (!V_blessed(vp)) {
3472 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3473 FreeVolumeHeader(vp);
3474 } else if (!V_inService(vp)) {
3475 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3476 FreeVolumeHeader(vp);
3478 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3480 error_state = VOL_STATE_ERROR;
3481 /* see if we can recover */
3482 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3487 #endif /* AFS_DEMAND_ATTACH_FS */
3489 #ifdef AFS_DEMAND_ATTACH_FS
3490 if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3491 V_inUse(vp) = programType;
3492 #endif /* AFS_DEMAND_ATTACH_FS */
3493 V_checkoutMode(vp) = mode;
3496 AddVolumeToHashTable(vp, vp->hashid);
3497 #ifdef AFS_DEMAND_ATTACH_FS
3498 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3501 if ((programType != fileServer) ||
3502 (V_inUse(vp) == fileServer)) {
3503 AddVolumeToVByPList_r(vp);
3505 VChangeState_r(vp, VOL_STATE_ATTACHED);
3507 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3516 #ifdef AFS_DEMAND_ATTACH_FS
3517 if (!VIsErrorState(V_attachState(vp))) {
3518 if (programType != fileServer && *ec == VNOVOL) {
3519 /* do not log anything in this case; it is common for
3520 * non-fileserver programs to fail here with VNOVOL, since that
3521 * is what happens when they simply try to use a volume, but that
3522 * volume doesn't exist. */
3524 } else if (VIsErrorState(error_state)) {
3525 Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3526 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3527 V_attachFlags(vp), *ec);
3529 VChangeState_r(vp, error_state);
3531 #endif /* AFS_DEMAND_ATTACH_FS */
3534 VReleaseVolumeHandles_r(vp);
3537 #ifdef AFS_DEMAND_ATTACH_FS
3539 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3540 /* The salvage could not be scheduled with the salvage server
3541 * due to a hard error. Reset the error code to prevent retry loops by
3543 if (*ec == VSALVAGING) {
3552 #else /* !AFS_DEMAND_ATTACH_FS */
3554 #endif /* !AFS_DEMAND_ATTACH_FS */
3558 /* Attach an existing volume.
3559 The volume also normally goes online at this time.
3560 An offline volume must be reattached to make it go online.
3564 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3568 retVal = VAttachVolume_r(ec, volumeId, mode);
3574 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3577 VGetVolumePath(ec, volumeId, &part, &name);
3581 vp = VGetVolume_r(&error, volumeId);
3583 opr_Assert(V_inUse(vp) == 0);
3584 VDetachVolume_r(ec, vp);
3588 return VAttachVolumeByName_r(ec, part, name, mode);
3591 /* Increment a reference count to a volume, sans context swaps. Requires
3592 * possibly reading the volume header in from the disk, since there's
3593 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3595 * N.B. This call can fail if we can't read in the header!! In this case
3596 * we still guarantee we won't context swap, but the ref count won't be
3597 * incremented (otherwise we'd violate the invariant).
3599 /* NOTE: with the demand attach fileserver extensions, the global lock
3600 * is dropped within VHold */
3601 #ifdef AFS_DEMAND_ATTACH_FS
3603 VHold_r(Volume * vp)
3607 VCreateReservation_r(vp);
3608 VWaitExclusiveState_r(vp);
3610 LoadVolumeHeader(&error, vp);
3612 VCancelReservation_r(vp);
3616 VCancelReservation_r(vp);
3619 #else /* AFS_DEMAND_ATTACH_FS */
3621 VHold_r(Volume * vp)
3625 LoadVolumeHeader(&error, vp);
3631 #endif /* AFS_DEMAND_ATTACH_FS */
3633 /**** volume timeout-related stuff ****/
3635 #ifdef AFS_PTHREAD_ENV
3637 static struct timespec *shutdown_timeout;
3638 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3641 VTimedOut(const struct timespec *ts)
3646 if (ts->tv_sec == 0) {
3647 /* short-circuit; this will have always timed out */
3651 code = gettimeofday(&tv, NULL);
3653 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3654 /* assume no timeout; failure mode is we just wait longer than normal
3655 * instead of returning errors when we shouldn't */
3659 if (tv.tv_sec < ts->tv_sec ||
3660 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3669 * Calculate an absolute timeout.
3671 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3672 * NULL, the memory is not touched
3673 * @param[in] timeout How long the timeout should be from now
3675 * @return timeout to use
3676 * @retval NULL no timeout; wait forever
3677 * @retval non-NULL the given value for "ts"
3681 static struct timespec *
3682 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3692 ts->tv_sec = ts->tv_nsec = 0;
3696 code = gettimeofday(&now, NULL);
3698 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3702 ts->tv_sec = now.tv_sec + timeout;
3703 ts->tv_nsec = now.tv_usec * 1000;
3709 * Initialize the shutdown_timeout global.
3712 VShutdownTimeoutInit(void)
3714 struct timespec *ts;
3716 ts = malloc(sizeof(*ts));
3718 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3720 if (!shutdown_timeout) {
3726 * Figure out the timeout that should be used for waiting for offline volumes.
3728 * @param[out] ats Storage space for a local timeout value if needed
3730 * @return The timeout value that should be used
3731 * @retval NULL No timeout; wait forever for offlining volumes
3732 * @retval non-NULL A pointer to the absolute time that should be used as
3733 * the deadline for waiting for offlining volumes.
3735 * @note If we return non-NULL, the pointer we return may or may not be the
3738 static const struct timespec *
3739 VOfflineTimeout(struct timespec *ats)
3741 if (vol_shutting_down) {
3742 opr_Verify(pthread_once(&shutdown_timeout_once,
3743 VShutdownTimeoutInit) == 0);
3744 return shutdown_timeout;
3746 return VCalcTimeout(ats, vol_opts.offline_timeout);
3750 #else /* AFS_PTHREAD_ENV */
3752 /* Waiting a certain amount of time for offlining volumes is not supported
3753 * for LWP due to a lack of primitives. So, we never time out */
3754 # define VTimedOut(x) (0)
3755 # define VOfflineTimeout(x) (NULL)
3757 #endif /* !AFS_PTHREAD_ENV */
3765 retVal = VHold_r(vp);
3772 VIsGoingOffline_r(struct Volume *vp)
3776 if (vp->goingOffline) {
3777 if (vp->specialStatus) {
3778 code = vp->specialStatus;
3779 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3790 * Tell the caller if a volume is waiting to go offline.
3792 * @param[in] vp The volume we want to know about
3794 * @return volume status
3795 * @retval 0 volume is not waiting to go offline, go ahead and use it
3796 * @retval nonzero volume is waiting to offline, and give the returned code
3797 * as an error to anyone accessing the volume
3799 * @pre VOL_LOCK is NOT held
3800 * @pre caller holds a heavyweight reference on vp
3803 VIsGoingOffline(struct Volume *vp)
3808 code = VIsGoingOffline_r(vp);
3815 * Register an RX call with a volume.
3817 * @param[inout] ec Error code; if unset when passed in, may be set if
3818 * the volume starts going offline
3819 * @param[out] client_ec @see GetVolume
3820 * @param[in] vp Volume struct
3821 * @param[in] cbv VCallByVol struct containing the RX call to register
3823 * @pre VOL_LOCK held
3824 * @pre caller holds heavy ref on vp
3829 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3832 #ifdef AFS_DEMAND_ATTACH_FS
3834 /* just in case the volume started going offline after we got the
3835 * reference to it... otherwise, if the volume started going
3836 * offline right at the end of GetVolume(), we might race with the
3837 * RX call scanner, and return success and add our cbv to the
3838 * rx_call_list _after_ the scanner has scanned the list. */
3839 *ec = VIsGoingOffline_r(vp);
3845 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3846 VWaitStateChange_r(vp);
3848 #endif /* AFS_DEMAND_ATTACH_FS */
3850 queue_Prepend(&vp->rx_call_list, cbv);
3855 * Deregister an RX call with a volume.
3857 * @param[in] vp Volume struct
3858 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3860 * @pre VOL_LOCK held
3861 * @pre caller holds heavy ref on vp
3866 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3868 if (cbv && queue_IsOnQueue(cbv)) {
3869 #ifdef AFS_DEMAND_ATTACH_FS
3870 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3871 VWaitStateChange_r(vp);
3873 #endif /* AFS_DEMAND_ATTACH_FS */
3879 /***************************************************/
3880 /* get and put volume routines */
3881 /***************************************************/
3884 * put back a heavyweight reference to a volume object.
3886 * @param[in] vp volume object pointer
3888 * @pre VOL_LOCK held
3890 * @post heavyweight volume reference put back.
3891 * depending on state, volume may have been taken offline,
3892 * detached, salvaged, freed, etc.
3894 * @internal volume package internal use only
3897 VPutVolume_r(Volume * vp)
3899 opr_Verify(--vp->nUsers >= 0);
3900 if (vp->nUsers == 0) {
3902 ReleaseVolumeHeader(vp->header);
3903 #ifdef AFS_DEMAND_ATTACH_FS
3904 if (!VCheckDetach(vp)) {
3908 #else /* AFS_DEMAND_ATTACH_FS */
3910 #endif /* AFS_DEMAND_ATTACH_FS */
3915 VPutVolume(Volume * vp)
3923 * Puts a volume reference obtained with VGetVolumeWithCall.
3925 * @param[in] vp Volume struct
3926 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3928 * @pre VOL_LOCK is NOT held
3931 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3934 VDeregisterCall_r(vp, cbv);
3939 /* Get a pointer to an attached volume. The pointer is returned regardless
3940 of whether or not the volume is in service or on/off line. An error
3941 code, however, is returned with an indication of the volume's status */
3943 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3947 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3953 * Get a volume reference associated with an RX call.
3955 * @param[out] ec @see GetVolume
3956 * @param[out] client_ec @see GetVolume
3957 * @param[in] volumeId @see GetVolume
3958 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3959 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3960 * with an error if the volume is going offline.
3961 * @param[in] cbv Contains an RX call to be associated with this volume
3962 * reference. This call may be interrupted if the volume is
3963 * requested to go offline while we hold a ref on it. Give NULL
3964 * to not associate an RX call with this reference.
3966 * @return @see GetVolume
3968 * @note for LWP builds, ts must be NULL
3970 * @note A reference obtained with this function MUST be put back with
3971 * VPutVolumeWithCall
3974 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3975 const struct timespec *ts, struct VCallByVol *cbv)
3979 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3980 VRegisterCall_r(ec, client_ec, retVal, cbv);
3986 VGetVolume_r(Error * ec, VolumeId volumeId)
3988 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3991 /* try to get a volume we've previously looked up */
3992 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3994 VGetVolumeByVp_r(Error * ec, Volume * vp)
3996 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
4000 * private interface for getting a volume handle
4002 * @param[out] ec error code (0 if no error)
4003 * @param[out] client_ec wire error code to be given to clients
4004 * @param[in] volumeId ID of the volume we want
4005 * @param[in] hint optional hint for hash lookups, or NULL
4006 * @param[in] timeout absolute deadline for waiting for the volume to go
4007 * offline, if it is going offline. NULL to wait forever.
4009 * @return a volume handle for the specified volume
4010 * @retval NULL an error occurred, or the volume is in such a state that
4011 * we cannot load a header or return any volume struct
4013 * @note for DAFS, caller must NOT hold a ref count on 'hint'
4015 * @note 'timeout' is only checked if the volume is actually going offline; so
4016 * if you pass timeout->tv_sec = 0, this will exhibit typical
4017 * nonblocking behavior.
4019 * @note for LWP builds, 'timeout' must be NULL
4022 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
4023 const struct timespec *timeout)
4026 /* pull this profiling/debugging code out of regular builds */
4028 #define VGET_CTR_INC(x) x++
4029 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
4030 0, V7 = 0, V8 = 0, V9 = 0;
4031 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
4033 #define VGET_CTR_INC(x)
4035 #ifdef AFS_DEMAND_ATTACH_FS
4036 Volume *avp, * rvp = hint;
4040 * if VInit is zero, the volume package dynamic
4041 * data structures have not been initialized yet,
4042 * and we must immediately return an error
4048 *client_ec = VOFFLINE;
4053 #ifdef AFS_DEMAND_ATTACH_FS
4055 VCreateReservation_r(rvp);
4057 #endif /* AFS_DEMAND_ATTACH_FS */
4065 vp = VLookupVolume_r(ec, volumeId, vp);
4071 #ifdef AFS_DEMAND_ATTACH_FS
4072 if (rvp && (rvp != vp)) {
4073 /* break reservation on old vp */
4074 VCancelReservation_r(rvp);
4077 #endif /* AFS_DEMAND_ATTACH_FS */
4083 /* Until we have reached an initialization level of 2
4084 * we don't know whether this volume exists or not.
4085 * We can't sleep and retry later because before a volume
4086 * is attached, the caller tries to get it first. Just
4087 * return VOFFLINE and the caller can choose whether to
4088 * retry the command or not. */
4098 IncUInt64(&VStats.hdr_gets);
4100 #ifdef AFS_DEMAND_ATTACH_FS
4101 /* block if someone else is performing an exclusive op on this volume */
4104 VCreateReservation_r(rvp);
4106 VWaitExclusiveState_r(vp);
4108 /* short circuit with VNOVOL in the following circumstances:
4111 * - VOL_STATE_SHUTTING_DOWN
4113 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4114 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4121 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4122 * VNOVOL for VOL_STATE_DELETED
4124 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4125 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4126 (V_attachState(vp) == VOL_STATE_DELETED)) {
4127 if (vp->specialStatus) {
4128 *ec = vp->specialStatus;
4129 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4138 /* allowable states:
4145 if (vp->salvage.requested) {
4146 VUpdateSalvagePriority_r(vp);
4149 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4150 if (vp->specialStatus) {
4151 *ec = vp->specialStatus;
4155 avp = VAttachVolumeByVp_r(ec, vp, 0);
4158 /* VAttachVolumeByVp_r can return a pointer
4159 * != the vp passed to it under certain
4160 * conditions; make sure we don't leak
4161 * reservations if that happens */
4163 VCancelReservation_r(rvp);
4165 VCreateReservation_r(rvp);
4176 if (vp->specialStatus) {
4177 *ec = vp->specialStatus;
4182 if (vp->specialStatus) {
4183 *ec = vp->specialStatus;
4196 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4198 /* see CheckVnode() in afsfileprocs.c for an explanation
4199 * of this error code logic */
4200 afs_uint32 now = FT_ApproxTime();
4201 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4204 *client_ec = VRESTARTING;
4212 if (VIsErrorState(V_attachState(vp))) {
4213 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4214 * it, or transition it out of that state */
4223 * this test MUST happen after VAttachVolymeByVp, so we have no
4224 * conflicting vol op. (attach2 would have errored out if we had one;
4225 * specifically attach_check_vop must have detected a conflicting vop)
4227 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4229 #endif /* AFS_DEMAND_ATTACH_FS */
4231 LoadVolumeHeader(ec, vp);
4234 /* Only log the error if it was a totally unexpected error. Simply
4235 * a missing inode is likely to be caused by the volume being deleted */
4236 if (errno != ENXIO || LogLevel)
4237 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4238 afs_printable_VolumeId_lu(vp->hashid));
4239 #ifdef AFS_DEMAND_ATTACH_FS
4240 if (VCanScheduleSalvage()) {
4241 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4246 #else /* AFS_DEMAND_ATTACH_FS */
4249 #endif /* AFS_DEMAND_ATTACH_FS */
4254 if (vp->shuttingDown) {
4261 if (programType == fileServer) {
4263 if (vp->goingOffline) {
4264 if (timeout && VTimedOut(timeout)) {
4265 /* we've timed out; don't wait for the vol */
4268 #ifdef AFS_DEMAND_ATTACH_FS
4269 /* wait for the volume to go offline */
4270 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4271 VTimedWaitStateChange_r(vp, timeout, NULL);
4273 #elif defined(AFS_PTHREAD_ENV)
4274 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4275 #else /* AFS_PTHREAD_ENV */
4276 /* LWP has no timed wait, so the caller better not be
4278 opr_Assert(!timeout);
4279 LWP_WaitProcess(VPutVolume);
4280 #endif /* AFS_PTHREAD_ENV */
4284 if (vp->specialStatus) {
4286 *ec = vp->specialStatus;
4287 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4290 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4301 #ifdef AFS_DEMAND_ATTACH_FS
4302 /* if no error, bump nUsers */
4305 VLRU_UpdateAccess_r(vp);
4308 VCancelReservation_r(rvp);
4311 if (client_ec && !*client_ec) {
4314 #else /* AFS_DEMAND_ATTACH_FS */
4315 /* if no error, bump nUsers */
4322 #endif /* AFS_DEMAND_ATTACH_FS */
4325 opr_Assert(vp || *ec);
4330 /***************************************************/
4331 /* Volume offline/detach routines */
4332 /***************************************************/
4334 /* caller MUST hold a heavyweight ref on vp */
4335 #ifdef AFS_DEMAND_ATTACH_FS
4337 VTakeOffline_r(Volume * vp)
4341 opr_Assert(vp->nUsers > 0);
4342 opr_Assert(programType == fileServer);
4344 VCreateReservation_r(vp);
4345 VWaitExclusiveState_r(vp);
4347 vp->goingOffline = 1;
4348 V_needsSalvaged(vp) = 1;
4350 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4351 VCancelReservation_r(vp);
4353 #else /* AFS_DEMAND_ATTACH_FS */
4355 VTakeOffline_r(Volume * vp)
4357 opr_Assert(vp->nUsers > 0);
4358 opr_Assert(programType == fileServer);
4360 vp->goingOffline = 1;
4361 V_needsSalvaged(vp) = 1;
4363 #endif /* AFS_DEMAND_ATTACH_FS */
4366 VTakeOffline(Volume * vp)
4374 * force a volume offline.
4376 * @param[in] vp volume object pointer
4377 * @param[in] flags flags (see note below)
4379 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4380 * used when VUpdateVolume_r needs to call VForceOffline_r
4381 * (which in turn would normally call VUpdateVolume_r)
4383 * @see VUpdateVolume_r
4385 * @pre VOL_LOCK must be held.
4386 * for DAFS, caller must hold ref.
4388 * @note for DAFS, it _is safe_ to call this function from an
4391 * @post needsSalvaged flag is set.
4392 * for DAFS, salvage is requested.
4393 * no further references to the volume through the volume
4394 * package will be honored.
4395 * all file descriptor and vnode caches are invalidated.
4397 * @warning this is a heavy-handed interface. it results in
4398 * a volume going offline regardless of the current
4399 * reference count state.
4401 * @internal volume package internal use only
4404 VForceOffline_r(Volume * vp, int flags)
4408 #ifdef AFS_DEMAND_ATTACH_FS
4409 VChangeState_r(vp, VOL_STATE_ERROR);
4414 strcpy(V_offlineMessage(vp),
4415 "Forced offline due to internal error: volume needs to be salvaged");
4416 Log("Volume %" AFS_VOLID_FMT " forced offline: it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4419 vp->goingOffline = 0;
4420 V_needsSalvaged(vp) = 1;
4421 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4422 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4425 #ifdef AFS_DEMAND_ATTACH_FS
4426 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4427 #endif /* AFS_DEMAND_ATTACH_FS */
4429 #ifdef AFS_PTHREAD_ENV
4430 opr_cv_broadcast(&vol_put_volume_cond);
4431 #else /* AFS_PTHREAD_ENV */
4432 LWP_NoYieldSignal(VPutVolume);
4433 #endif /* AFS_PTHREAD_ENV */
4435 VReleaseVolumeHandles_r(vp);
4439 * force a volume offline.
4441 * @param[in] vp volume object pointer
4443 * @see VForceOffline_r
4446 VForceOffline(Volume * vp)
4449 VForceOffline_r(vp, 0);
4454 * Iterate over the RX calls associated with a volume, and interrupt them.
4456 * @param[in] vp The volume whose RX calls we want to scan
4458 * @pre VOL_LOCK held
4461 VScanCalls_r(struct Volume *vp)
4463 struct VCallByVol *cbv, *ncbv;
4465 #ifdef AFS_DEMAND_ATTACH_FS
4466 VolState state_save;
4469 if (queue_IsEmpty(&vp->rx_call_list))
4470 return; /* no calls to interrupt */
4471 if (!vol_opts.interrupt_rxcall)
4472 return; /* we have no function with which to interrupt calls */
4473 err = VIsGoingOffline_r(vp);
4475 return; /* we're not going offline anymore */
4477 #ifdef AFS_DEMAND_ATTACH_FS
4478 VWaitExclusiveState_r(vp);
4479 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4481 #endif /* AFS_DEMAND_ATTACH_FS */
4483 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4485 struct rx_peer *peer;
4487 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4489 Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4490 "from it; kicking client off with error %ld\n",
4491 afs_printable_VolumeId_lu(vp->hashid),
4492 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4493 (unsigned) ntohs(rx_PortOf(peer)),
4496 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4499 #ifdef AFS_DEMAND_ATTACH_FS
4501 VChangeState_r(vp, state_save);
4502 #endif /* AFS_DEMAND_ATTACH_FS */
4505 #ifdef AFS_DEMAND_ATTACH_FS
4507 * Wait for a vp to go offline.
4509 * @param[out] ec 1 if a salvage on the volume has been requested and
4510 * salvok == 0, 0 otherwise
4511 * @param[in] vp The volume to wait for
4512 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4513 * has been requested to salvage. Otherwise we keep waiting
4514 * until the volume has gone offline.
4516 * @pre VOL_LOCK held
4517 * @pre caller holds a lightweight ref on vp
4522 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4524 struct timespec timeout_ts;
4525 const struct timespec *ts;
4528 ts = VOfflineTimeout(&timeout_ts);
4532 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4533 if (!salvok && vp->salvage.requested) {
4537 VTimedWaitStateChange_r(vp, ts, &timedout);
4540 /* we didn't time out, so the volume must be offline, so we're done */
4544 /* If we got here, we timed out waiting for the volume to go offline.
4545 * Kick off the accessing RX calls and wait again */
4549 while (!VIsOfflineState(V_attachState(vp))) {
4550 if (!salvok && vp->salvage.requested) {
4555 VWaitStateChange_r(vp);
4559 #else /* AFS_DEMAND_ATTACH_FS */
4562 * Wait for a volume to go offline.
4564 * @pre VOL_LOCK held
4566 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4569 VWaitForOffline_r(Error *ec, VolumeId volid)
4572 const struct timespec *ts;
4573 #ifdef AFS_PTHREAD_ENV
4574 struct timespec timeout_ts;
4577 ts = VOfflineTimeout(&timeout_ts);
4579 vp = GetVolume(ec, NULL, volid, NULL, ts);
4581 /* error occurred so bad that we can't even get a vp; we have no
4582 * information on the vol so we don't know whether to wait, so just
4586 if (!VIsGoingOffline_r(vp)) {
4587 /* volume is no longer going offline, so we're done */
4592 /* If we got here, we timed out waiting for the volume to go offline.
4593 * Kick off the accessing RX calls and wait again */
4599 vp = VGetVolume_r(ec, volid);
4601 /* In case it was reattached... */
4605 #endif /* !AFS_DEMAND_ATTACH_FS */
4607 /* The opposite of VAttachVolume. The volume header is written to disk, with
4608 the inUse bit turned off. A copy of the header is maintained in memory,
4609 however (which is why this is VOffline, not VDetach).
4612 VOffline_r(Volume * vp, char *message)
4615 #ifndef AFS_DEMAND_ATTACH_FS
4616 VolumeId vid = V_id(vp);
4619 opr_Assert(programType != volumeUtility && programType != volumeServer);
4624 if (V_offlineMessage(vp)[0] == '\0')
4625 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4626 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4628 vp->goingOffline = 1;
4629 #ifdef AFS_DEMAND_ATTACH_FS
4630 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4631 VCreateReservation_r(vp);
4633 VWaitForOfflineByVp_r(&error, vp, 1);
4634 VCancelReservation_r(vp);
4635 #else /* AFS_DEMAND_ATTACH_FS */
4637 VWaitForOffline_r(&error, vid);
4638 #endif /* AFS_DEMAND_ATTACH_FS */
4641 #ifdef AFS_DEMAND_ATTACH_FS
4643 * Take a volume offline in order to perform a volume operation.
4645 * @param[inout] ec address in which to store error code
4646 * @param[in] vp volume object pointer
4647 * @param[in] message volume offline status message
4650 * - VOL_LOCK is held
4651 * - caller MUST hold a heavyweight ref on vp
4654 * - volume is taken offline
4655 * - if possible, volume operation is promoted to running state
4656 * - on failure, *ec is set to nonzero
4658 * @note Although this function does not return any value, it may
4659 * still fail to promote our pending volume operation to
4660 * a running state. Any caller MUST check the value of *ec,
4661 * and MUST NOT blindly assume success.
4663 * @warning if the caller does not hold a lightweight ref on vp,
4664 * then it MUST NOT reference vp after this function
4665 * returns to the caller.
4667 * @internal volume package internal use only
4670 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4673 opr_Assert(vp->pending_vol_op);
4679 if (V_offlineMessage(vp)[0] == '\0')
4680 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4681 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4683 vp->goingOffline = 1;
4684 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4685 VCreateReservation_r(vp);
4688 if (vp->pending_vol_op->com.programType != salvageServer) {
4689 /* do not give corrupted volumes to the volserver */
4694 VWaitForOfflineByVp_r(ec, vp, salvok);
4696 VCancelReservation_r(vp);
4698 #endif /* AFS_DEMAND_ATTACH_FS */
4701 VOffline(Volume * vp, char *message)
4704 VOffline_r(vp, message);
4708 /* This gets used for the most part by utility routines that don't want
4709 * to keep all the volume headers around. Generally, the file server won't
4710 * call this routine, because then the offline message in the volume header
4711 * (or other information) won't be available to clients. For NAMEI, also
4712 * close the file handles. However, the fileserver does call this during
4713 * an attach following a volume operation.
4716 VDetachVolume_r(Error * ec, Volume * vp)
4718 #ifdef FSSYNC_BUILD_CLIENT
4720 struct DiskPartition64 *tpartp;
4721 int notifyServer = 0;
4722 int useDone = FSYNC_VOL_ON;
4724 if (VCanUseFSSYNC()) {
4725 notifyServer = vp->needsPutBack;
4726 if (V_destroyMe(vp) == DESTROY_ME)
4727 useDone = FSYNC_VOL_LEAVE_OFF;
4728 # ifdef AFS_DEMAND_ATTACH_FS
4729 else if (!V_blessed(vp) || !V_inService(vp))
4730 useDone = FSYNC_VOL_LEAVE_OFF;
4733 # ifdef AFS_DEMAND_ATTACH_FS
4734 if (V_needsSalvaged(vp)) {
4736 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4739 tpartp = vp->partition;
4741 #endif /* FSSYNC_BUILD_CLIENT */
4743 *ec = 0; /* always "succeeds" */
4744 DeleteVolumeFromHashTable(vp);
4745 vp->shuttingDown = 1;
4746 #ifdef AFS_DEMAND_ATTACH_FS
4747 DeleteVolumeFromVByPList_r(vp);
4749 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4751 if (programType != fileServer)
4753 #endif /* AFS_DEMAND_ATTACH_FS */
4755 /* Will be detached sometime in the future--this is OK since volume is offline */
4757 /* XXX the following code should really be moved to VCheckDetach() since the volume
4758 * is not technically detached until the refcounts reach zero
4760 #ifdef FSSYNC_BUILD_CLIENT
4761 if (VCanUseFSSYNC() && notifyServer) {
4762 if (notifyServer == VOL_PUTBACK_DELETE) {
4763 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4764 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4765 * to signify a deleted volume. */
4766 useDone = FSYNC_VOL_DONE;
4769 * Note: The server is not notified in the case of a bogus volume
4770 * explicitly to make it possible to create a volume, do a partial
4771 * restore, then abort the operation without ever putting the volume
4772 * online. This is essential in the case of a volume move operation
4773 * between two partitions on the same server. In that case, there
4774 * would be two instances of the same volume, one of them bogus,
4775 * which the file server would attempt to put on line
4777 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4778 /* XXX this code path is only hit by volume utilities, thus
4779 * V_BreakVolumeCallbacks will always be NULL. if we really
4780 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4782 /* Dettaching it so break all callbacks on it */
4783 if (V_BreakVolumeCallbacks) {
4784 Log("volume %u detached; breaking all call backs\n", volume);
4785 (*V_BreakVolumeCallbacks) (volume);
4789 #endif /* FSSYNC_BUILD_CLIENT */
4793 VDetachVolume(Error * ec, Volume * vp)
4796 VDetachVolume_r(ec, vp);
4801 /***************************************************/
4802 /* Volume fd/inode handle closing routines */
4803 /***************************************************/
4805 /* For VDetachVolume, we close all cached file descriptors, but keep
4806 * the Inode handles in case we need to read from a busy volume.
4808 /* for demand attach, caller MUST hold ref count on vp */
4810 VCloseVolumeHandles_r(Volume * vp)
4812 #ifdef AFS_DEMAND_ATTACH_FS
4813 VolState state_save;
4815 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4820 DFlushVolume(vp->hashid);
4822 #ifdef AFS_DEMAND_ATTACH_FS
4826 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4827 VCloseVnodeFiles_r(vp);
4829 #ifdef AFS_DEMAND_ATTACH_FS
4833 /* Too time consuming and unnecessary for the volserver */
4834 if (programType == fileServer) {
4835 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4836 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4837 IH_CONDSYNC(vp->diskDataHandle);
4838 #ifdef AFS_NAMEI_ENV
4839 IH_CONDSYNC(vp->linkHandle);
4840 #endif /* AFS_NAMEI_ENV */
4843 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4844 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4845 IH_REALLYCLOSE(vp->diskDataHandle);
4846 IH_REALLYCLOSE(vp->linkHandle);
4848 #ifdef AFS_DEMAND_ATTACH_FS
4849 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4854 VChangeState_r(vp, state_save);
4858 /* For both VForceOffline and VOffline, we close all relevant handles.
4859 * For VOffline, if we re-attach the volume, the files may possible be
4860 * different than before.
4862 /* for demand attach, caller MUST hold a ref count on vp */
4864 VReleaseVolumeHandles_r(Volume * vp)
4866 #ifdef AFS_DEMAND_ATTACH_FS
4867 VolState state_save;
4869 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4874 DFlushVolume(vp->hashid);
4876 #ifdef AFS_DEMAND_ATTACH_FS
4880 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4882 #ifdef AFS_DEMAND_ATTACH_FS
4886 /* Too time consuming and unnecessary for the volserver */
4887 if (programType == fileServer) {
4888 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4889 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4890 IH_CONDSYNC(vp->diskDataHandle);
4891 #ifdef AFS_NAMEI_ENV
4892 IH_CONDSYNC(vp->linkHandle);
4893 #endif /* AFS_NAMEI_ENV */
4896 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4897 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4898 IH_RELEASE(vp->diskDataHandle);
4899 IH_RELEASE(vp->linkHandle);
4901 #ifdef AFS_DEMAND_ATTACH_FS
4902 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4907 VChangeState_r(vp, state_save);
4912 /***************************************************/
4913 /* Volume write and fsync routines */
4914 /***************************************************/
4917 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4919 #ifdef AFS_DEMAND_ATTACH_FS
4920 VolState state_save;
4922 if (flags & VOL_UPDATE_WAIT) {
4923 VCreateReservation_r(vp);
4924 VWaitExclusiveState_r(vp);
4929 if (programType == fileServer) {
4931 V_uniquifier(vp) = V_nextVnodeUnique(vp);
4934 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4935 if (V_uniquifier(vp) < V_nextVnodeUnique(vp)) {
4936 /* uniquifier rolled over; reset the counters */
4937 V_nextVnodeUnique(vp) = 2; /* 1 is reserved for the root vnode */
4939 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4944 #ifdef AFS_DEMAND_ATTACH_FS
4945 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4949 WriteVolumeHeader_r(ec, vp);
4951 #ifdef AFS_DEMAND_ATTACH_FS
4953 VChangeState_r(vp, state_save);
4954 if (flags & VOL_UPDATE_WAIT) {
4955 VCancelReservation_r(vp);
4960 Log("VUpdateVolume: error updating volume header, volume %" AFS_VOLID_FMT " (%s)\n",
4961 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
4962 /* try to update on-disk header,
4963 * while preventing infinite recursion */
4964 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4965 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4971 VUpdateVolume(Error * ec, Volume * vp)
4974 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4979 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4983 #ifdef AFS_DEMAND_ATTACH_FS
4984 VolState state_save;
4987 if (flags & VOL_SYNC_WAIT) {
4988 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4990 VUpdateVolume_r(ec, vp, 0);
4993 #ifdef AFS_DEMAND_ATTACH_FS
4994 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4997 fdP = IH_OPEN(V_diskDataHandle(vp));
4998 opr_Assert(fdP != NULL);
4999 code = FDH_SYNC(fdP);
5000 opr_Assert(code == 0);
5002 #ifdef AFS_DEMAND_ATTACH_FS
5004 VChangeState_r(vp, state_save);
5010 VSyncVolume(Error * ec, Volume * vp)
5013 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
5018 /***************************************************/
5019 /* Volume dealloaction routines */
5020 /***************************************************/
5022 #ifdef AFS_DEMAND_ATTACH_FS
5024 FreeVolume(Volume * vp)
5026 /* free the heap space, iff it's safe.
5027 * otherwise, pull it out of the hash table, so it
5028 * will get deallocated when all refs to it go away */
5029 if (!VCheckFree(vp)) {
5030 DeleteVolumeFromHashTable(vp);
5031 DeleteVolumeFromVByPList_r(vp);
5033 /* make sure we invalidate the header cache entry */
5034 FreeVolumeHeader(vp);
5037 #endif /* AFS_DEMAND_ATTACH_FS */
5040 ReallyFreeVolume(Volume * vp)
5045 #ifdef AFS_DEMAND_ATTACH_FS
5047 VChangeState_r(vp, VOL_STATE_FREED);
5048 if (vp->pending_vol_op)
5049 free(vp->pending_vol_op);
5050 #endif /* AFS_DEMAND_ATTACH_FS */
5051 for (i = 0; i < nVNODECLASSES; i++)
5052 if (vp->vnodeIndex[i].bitmap)
5053 free(vp->vnodeIndex[i].bitmap);
5054 FreeVolumeHeader(vp);
5055 #ifndef AFS_DEMAND_ATTACH_FS
5056 DeleteVolumeFromHashTable(vp);
5057 #endif /* AFS_DEMAND_ATTACH_FS */
5061 /* check to see if we should shutdown this volume
5062 * returns 1 if volume was freed, 0 otherwise */
5063 #ifdef AFS_DEMAND_ATTACH_FS
5065 VCheckDetach(Volume * vp)
5070 if (vp->nUsers || vp->nWaiters)
5073 if (vp->shuttingDown) {
5075 if ((programType != fileServer) &&
5076 (V_inUse(vp) == programType) &&
5077 ((V_checkoutMode(vp) == V_VOLUPD) ||
5078 (V_checkoutMode(vp) == V_SECRETLY) ||
5079 ((V_checkoutMode(vp) == V_CLONE) &&
5080 (VolumeWriteable(vp))))) {
5082 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5084 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " "
5085 "failed with errno %d\n", afs_printable_VolumeId_lu(vp->hashid), errno);
5088 VReleaseVolumeHandles_r(vp);
5090 ReallyFreeVolume(vp);
5091 if (programType == fileServer) {
5092 opr_cv_broadcast(&vol_put_volume_cond);
5097 #else /* AFS_DEMAND_ATTACH_FS */
5099 VCheckDetach(Volume * vp)
5107 if (vp->shuttingDown) {
5109 if ((programType != fileServer) &&
5110 (V_inUse(vp) == programType) &&
5111 ((V_checkoutMode(vp) == V_VOLUPD) ||
5112 (V_checkoutMode(vp) == V_SECRETLY) ||
5113 ((V_checkoutMode(vp) == V_CLONE) &&
5114 (VolumeWriteable(vp))))) {
5116 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5118 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " failed with errno %d\n",
5119 afs_printable_VolumeId_lu(vp->hashid), errno);
5122 VReleaseVolumeHandles_r(vp);
5123 ReallyFreeVolume(vp);
5124 if (programType == fileServer) {
5125 #if defined(AFS_PTHREAD_ENV)
5126 opr_cv_broadcast(&vol_put_volume_cond);
5127 #else /* AFS_PTHREAD_ENV */
5128 LWP_NoYieldSignal(VPutVolume);
5129 #endif /* AFS_PTHREAD_ENV */
5134 #endif /* AFS_DEMAND_ATTACH_FS */
5136 /* check to see if we should offline this volume
5137 * return 1 if volume went offline, 0 otherwise */
5138 #ifdef AFS_DEMAND_ATTACH_FS
5140 VCheckOffline(Volume * vp)
5144 if (vp->goingOffline && !vp->nUsers) {
5146 opr_Assert(programType == fileServer);
5147 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5148 (V_attachState(vp) != VOL_STATE_FREED) &&
5149 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5150 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5151 (V_attachState(vp) != VOL_STATE_DELETED));
5155 * VOL_STATE_GOING_OFFLINE
5156 * VOL_STATE_SHUTTING_DOWN
5157 * VIsErrorState(V_attachState(vp))
5158 * VIsExclusiveState(V_attachState(vp))
5161 VCreateReservation_r(vp);
5162 VChangeState_r(vp, VOL_STATE_OFFLINING);
5165 /* must clear the goingOffline flag before we drop the glock */
5166 vp->goingOffline = 0;
5171 /* perform async operations */
5172 VUpdateVolume_r(&error, vp, 0);
5173 VCloseVolumeHandles_r(vp);
5176 if (V_offlineMessage(vp)[0]) {
5177 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5178 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5179 V_offlineMessage(vp));
5181 Log("VOffline: Volume %lu (%s) is now offline\n",
5182 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5186 /* invalidate the volume header cache entry */
5187 FreeVolumeHeader(vp);
5189 /* if nothing changed state to error or salvaging,
5190 * drop state to unattached */
5191 if (!VIsErrorState(V_attachState(vp))) {
5192 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5194 VCancelReservation_r(vp);
5195 /* no usage of vp is safe beyond this point */
5199 #else /* AFS_DEMAND_ATTACH_FS */
5201 VCheckOffline(Volume * vp)
5205 if (vp->goingOffline && !vp->nUsers) {
5207 opr_Assert(programType == fileServer);
5210 vp->goingOffline = 0;
5212 VUpdateVolume_r(&error, vp, 0);
5213 VCloseVolumeHandles_r(vp);
5215 if (V_offlineMessage(vp)[0]) {
5216 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5217 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5218 V_offlineMessage(vp));
5220 Log("VOffline: Volume %lu (%s) is now offline\n",
5221 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5224 FreeVolumeHeader(vp);
5225 #ifdef AFS_PTHREAD_ENV
5226 opr_cv_broadcast(&vol_put_volume_cond);
5227 #else /* AFS_PTHREAD_ENV */
5228 LWP_NoYieldSignal(VPutVolume);
5229 #endif /* AFS_PTHREAD_ENV */
5233 #endif /* AFS_DEMAND_ATTACH_FS */
5235 /***************************************************/
5236 /* demand attach fs ref counting routines */
5237 /***************************************************/
5239 #ifdef AFS_DEMAND_ATTACH_FS
5240 /* the following two functions handle reference counting for
5241 * asynchronous operations on volume structs.
5243 * their purpose is to prevent a VDetachVolume or VShutdown
5244 * from free()ing the Volume struct during an async i/o op */
5246 /* register with the async volume op ref counter */
5247 /* VCreateReservation_r moved into inline code header because it
5248 * is now needed in vnode.c -- tkeiser 11/20/2007
5252 * decrement volume-package internal refcount.
5254 * @param vp volume object pointer
5256 * @internal volume package internal use only
5259 * @arg VOL_LOCK is held
5260 * @arg lightweight refcount held
5262 * @post volume waiters refcount is decremented; volume may
5263 * have been deallocated/shutdown/offlined/salvaged/
5264 * whatever during the process
5266 * @warning once you have tossed your last reference (you can acquire
5267 * lightweight refs recursively) it is NOT SAFE to reference
5268 * a volume object pointer ever again
5270 * @see VCreateReservation_r
5272 * @note DEMAND_ATTACH_FS only
5275 VCancelReservation_r(Volume * vp)
5277 opr_Verify(--vp->nWaiters >= 0);
5278 if (vp->nWaiters == 0) {
5280 if (!VCheckDetach(vp)) {
5287 /* check to see if we should free this volume now
5288 * return 1 if volume was freed, 0 otherwise */
5290 VCheckFree(Volume * vp)
5293 if ((vp->nUsers == 0) &&
5294 (vp->nWaiters == 0) &&
5295 !(V_attachFlags(vp) & (VOL_IN_HASH |
5299 ReallyFreeVolume(vp);
5304 #endif /* AFS_DEMAND_ATTACH_FS */
5307 /***************************************************/
5308 /* online volume operations routines */
5309 /***************************************************/
5311 #ifdef AFS_DEMAND_ATTACH_FS
5313 * register a volume operation on a given volume.
5315 * @param[in] vp volume object
5316 * @param[in] vopinfo volume operation info object
5318 * @pre VOL_LOCK is held
5320 * @post volume operation info object attached to volume object.
5321 * volume operation statistics updated.
5323 * @note by "attached" we mean a copy of the passed in object is made
5325 * @internal volume package internal use only
5328 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5330 FSSYNC_VolOp_info * info;
5332 /* attach a vol op info node to the volume struct */
5333 info = malloc(sizeof(FSSYNC_VolOp_info));
5334 opr_Assert(info != NULL);
5335 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5336 vp->pending_vol_op = info;
5339 vp->stats.last_vol_op = FT_ApproxTime();
5340 vp->stats.vol_ops++;
5341 IncUInt64(&VStats.vol_ops);
5347 * deregister the volume operation attached to this volume.
5349 * @param[in] vp volume object pointer
5351 * @pre VOL_LOCK is held
5353 * @post the volume operation info object is detached from the volume object
5355 * @internal volume package internal use only
5358 VDeregisterVolOp_r(Volume * vp)
5360 if (vp->pending_vol_op) {
5361 free(vp->pending_vol_op);
5362 vp->pending_vol_op = NULL;
5366 #endif /* AFS_DEMAND_ATTACH_FS */
5369 * determine whether it is safe to leave a volume online during
5370 * the volume operation described by the vopinfo object.
5372 * @param[in] vp volume object
5373 * @param[in] vopinfo volume operation info object
5375 * @return whether it is safe to leave volume online
5376 * @retval 0 it is NOT SAFE to leave the volume online
5377 * @retval 1 it is safe to leave the volume online during the operation
5380 * @arg VOL_LOCK is held
5381 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5382 * this condition is met)
5384 * @internal volume package internal use only
5387 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5389 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5390 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5391 (vopinfo->com.reason == V_READONLY ||
5392 (!VolumeWriteable(vp) &&
5393 (vopinfo->com.reason == V_CLONE ||
5394 vopinfo->com.reason == V_DUMP)))));
5398 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5401 * @param[in] vp volume object
5402 * @param[in] vopinfo volume operation info object
5404 * @return whether it is safe to leave volume online
5405 * @retval 0 it is NOT SAFE to leave the volume online
5406 * @retval 1 it is safe to leave the volume online during the operation
5407 * @retval -1 unsure; volume header is required in order to know whether or
5408 * not is is safe to leave the volume online
5410 * @pre VOL_LOCK is held
5412 * @internal volume package internal use only
5415 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5417 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5418 * assume that we don't know VolumeWriteable; return -1 if the answer
5419 * depends on VolumeWriteable */
5421 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5424 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5425 vopinfo->com.reason == V_READONLY) {
5429 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5430 (vopinfo->com.reason == V_CLONE ||
5431 vopinfo->com.reason == V_DUMP)) {
5433 /* must know VolumeWriteable */
5440 * determine whether VBUSY should be set during this volume operation.
5442 * @param[in] vp volume object
5443 * @param[in] vopinfo volume operation info object
5445 * @return whether VBUSY should be set
5446 * @retval 0 VBUSY does NOT need to be set
5447 * @retval 1 VBUSY SHOULD be set
5449 * @pre VOL_LOCK is held
5451 * @internal volume package internal use only
5454 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5456 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5457 vopinfo->com.reason == FSYNC_SALVAGE) ||
5458 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5459 (vopinfo->com.reason == V_CLONE ||
5460 vopinfo->com.reason == V_DUMP)));
5464 /***************************************************/
5465 /* online salvager routines */
5466 /***************************************************/
5467 #if defined(AFS_DEMAND_ATTACH_FS)
5470 * offline a volume to let it be salvaged.
5472 * @param[in] vp Volume to offline
5474 * @return whether we offlined the volume successfully
5475 * @retval 0 volume was not offlined
5476 * @retval 1 volume is now offline
5478 * @note This is similar to VCheckOffline, but slightly different. We do not
5479 * deal with vp->goingOffline, and we try to avoid touching the volume
5480 * header except just to set needsSalvaged
5482 * @pre VOL_LOCK held
5483 * @pre vp->nUsers == 0
5484 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5487 VOfflineForSalvage_r(struct Volume *vp)
5491 VCreateReservation_r(vp);
5492 VWaitExclusiveState_r(vp);
5494 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5495 /* Someone's using the volume, or someone got to scheduling the salvage
5496 * before us. I don't think either of these should be possible, as we
5497 * should gain no new heavyweight references while we're trying to
5498 * salvage, but just to be sure... */
5499 VCancelReservation_r(vp);
5503 VChangeState_r(vp, VOL_STATE_OFFLINING);
5507 V_needsSalvaged(vp) = 1;
5508 /* ignore error; updating needsSalvaged is just best effort */
5509 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5511 VCloseVolumeHandles_r(vp);
5513 FreeVolumeHeader(vp);
5515 /* volume has been effectively offlined; we can mark it in the SALVAGING
5516 * state now, which lets FSSYNC give it away */
5517 VChangeState_r(vp, VOL_STATE_SALVAGING);
5519 VCancelReservation_r(vp);
5525 * check whether a salvage needs to be performed on this volume.
5527 * @param[in] vp pointer to volume object
5529 * @return status code
5530 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5531 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5532 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5533 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5534 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5536 * @pre VOL_LOCK is held
5538 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5539 * then a salvage will be requested
5541 * @note this is one of the event handlers called by VCancelReservation_r
5543 * @note the caller must check if the volume needs to be freed after calling
5544 * this; the volume may not have any references or be on any lists after
5545 * we return, and we do not free it
5547 * @see VCancelReservation_r
5549 * @internal volume package internal use only.
5552 VCheckSalvage(Volume * vp)
5554 int ret = VCHECK_SALVAGE_OK;
5556 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5557 if (!vp->salvage.requested) {
5558 return VCHECK_SALVAGE_OK;
5561 return VCHECK_SALVAGE_ASYNC;
5564 /* prevent recursion; some of the code below creates and removes
5565 * lightweight refs, which can call VCheckSalvage */
5566 if (vp->salvage.scheduling) {
5567 return VCHECK_SALVAGE_ASYNC;
5569 vp->salvage.scheduling = 1;
5571 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5572 if (!VOfflineForSalvage_r(vp)) {
5573 vp->salvage.scheduling = 0;
5574 return VCHECK_SALVAGE_FAIL;
5578 if (vp->salvage.requested) {
5579 ret = VScheduleSalvage_r(vp);
5581 vp->salvage.scheduling = 0;
5582 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5587 * request volume salvage.
5589 * @param[out] ec computed client error code
5590 * @param[in] vp volume object pointer
5591 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5592 * @param[in] flags see flags note below
5595 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5596 * not been fully attached
5598 * @pre VOL_LOCK is held.
5600 * @post volume state is changed.
5601 * for fileserver, salvage will be requested once refcount reaches zero.
5603 * @return operation status code
5604 * @retval 0 volume salvage will occur
5605 * @retval 1 volume salvage could not be scheduled
5609 * @note in the fileserver, this call does not synchronously schedule a volume
5610 * salvage. rather, it sets volume state so that when volume refcounts
5611 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5612 * nUsers and nWaiters must be zero.
5614 * @internal volume package internal use only.
5617 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5621 * for DAFS volume utilities that are not supposed to schedule salvages,
5622 * just transition to error state instead
5624 if (!VCanScheduleSalvage()) {
5625 VChangeState_r(vp, VOL_STATE_ERROR);
5630 if (programType != fileServer && !VCanUseFSSYNC()) {
5631 VChangeState_r(vp, VOL_STATE_ERROR);
5636 if (!vp->salvage.requested) {
5637 vp->salvage.requested = 1;
5638 vp->salvage.reason = reason;
5639 vp->stats.last_salvage = FT_ApproxTime();
5641 /* Note that it is not possible for us to reach this point if a
5642 * salvage is already running on this volume (even if the fileserver
5643 * was restarted during the salvage). If a salvage were running, the
5644 * salvager would have write-locked the volume header file, so when
5645 * we tried to lock the volume header, the lock would have failed,
5646 * and we would have failed during attachment prior to calling
5647 * VRequestSalvage. So we know that we can schedule salvages without
5648 * fear of a salvage already running for this volume. */
5650 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5652 /* if we don't need to offline the volume, we can go directly
5653 * to SALVAGING. SALVAGING says the volume is offline and is
5654 * either salvaging or ready to be handed to the salvager.
5655 * SALVAGE_REQ says that we want to salvage the volume, but we
5656 * are waiting for it to go offline first. */
5657 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5658 VChangeState_r(vp, VOL_STATE_SALVAGING);
5660 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5661 if (vp->nUsers == 0) {
5662 /* normally VOfflineForSalvage_r would be called from
5663 * PutVolume et al when nUsers reaches 0, but if
5664 * it's already 0, just do it ourselves, since PutVolume
5665 * isn't going to get called */
5666 VOfflineForSalvage_r(vp);
5669 /* If we are non-fileserver, we're telling the fileserver to
5670 * salvage the vol, so we don't need to give it back separately. */
5671 vp->needsPutBack = 0;
5675 Log("VRequestSalvage: volume %" AFS_VOLID_FMT " online salvaged too many times; forced offline.\n", afs_printable_VolumeId_lu(vp->hashid));
5677 /* make sure neither VScheduleSalvage_r nor
5678 * VUpdateSalvagePriority_r try to schedule another salvage */
5679 vp->salvage.requested = vp->salvage.scheduled = 0;
5681 VChangeState_r(vp, VOL_STATE_ERROR);
5685 if ((flags & VOL_SALVAGE_NO_OFFLINE)) {
5686 /* Here, we free the header for the volume, but make sure to only
5687 * do this if VOL_SALVAGE_NO_OFFLINE is specified. The reason for
5688 * this requires a bit of explanation.
5690 * Normally, the volume header will be freed when the volume goes
5691 * goes offline. However, if VOL_SALVAGE_NO_OFFLINE has been
5692 * specified, the volume was in the process of being attached when
5693 * we discovered that it needed salvaging. Thus, the volume will
5694 * never go offline, since it never went fully online in the first
5695 * place. Specifically, we do not call VOfflineForSalvage_r above,
5696 * and we never get rid of the volume via VPutVolume_r; the volume
5697 * has not been initialized enough for those to work.
5699 * So instead, explicitly free the volume header here. If we do not
5700 * do this, we are wasting a header that some other volume could be
5701 * using, since the header remains attached to the volume. Also if
5702 * we do not free the header here, we end up with a volume where
5703 * nUsers == 0, but the volume has a header that is not on the
5704 * header LRU. Some code expects that all nUsers == 0 volumes have
5705 * their header on the header LRU (or have no header).
5707 * Also note that we must not free the volume header here if
5708 * VOL_SALVAGE_NO_OFFLINE is not set. Since, if
5709 * VOL_SALVAGE_NO_OFFLINE is not set, someone else may have a
5710 * reference to this volume, and they assume they can use the
5711 * volume's header. If we free the volume out from under them, they
5712 * can easily segfault.
5714 FreeVolumeHeader(vp);
5721 * update salvageserver scheduling priority for a volume.
5723 * @param[in] vp pointer to volume object
5725 * @return operation status
5727 * @retval 1 request denied, or SALVSYNC communications failure
5729 * @pre VOL_LOCK is held.
5731 * @post in-core salvage priority counter is incremented. if at least
5732 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5733 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5734 * to update its priority queue. if no salvage is scheduled,
5735 * this function is a no-op.
5737 * @note DAFS fileserver only
5739 * @note this should be called whenever a VGetVolume fails due to a
5740 * pending salvage request
5742 * @todo should set exclusive state and drop glock around salvsync call
5744 * @internal volume package internal use only.
5747 VUpdateSalvagePriority_r(Volume * vp)
5751 #ifdef SALVSYNC_BUILD_CLIENT
5756 now = FT_ApproxTime();
5758 /* update the salvageserver priority queue occasionally so that
5759 * frequently requested volumes get moved to the head of the queue
5761 if ((vp->salvage.scheduled) &&
5762 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5763 code = SALVSYNC_SalvageVolume(vp->hashid,
5764 VPartitionPath(vp->partition),
5769 vp->stats.last_salvage_req = now;
5770 if (code != SYNC_OK) {
5774 #endif /* SALVSYNC_BUILD_CLIENT */
5779 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5781 /* A couple of little helper functions. These return true if we tried to
5782 * use this mechanism to schedule a salvage, false if we haven't tried.
5783 * If we did try a salvage then the results are contained in code.
5787 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5788 #ifdef SALVSYNC_BUILD_CLIENT
5789 if (VCanUseSALVSYNC()) {
5790 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over SALVSYNC\n",
5791 afs_printable_VolumeId_lu(vp->hashid), partName);
5793 /* can't use V_id() since there's no guarantee
5794 * we have the disk data header at this point */
5795 *code = SALVSYNC_SalvageVolume(vp->hashid,
5808 try_FSSYNC(Volume *vp, char *partName, int *code) {
5809 #ifdef FSSYNC_BUILD_CLIENT
5810 if (VCanUseFSSYNC()) {
5811 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over FSSYNC\n",
5812 afs_printable_VolumeId_lu(vp->hashid), partName);
5815 * If we aren't the fileserver, tell the fileserver the volume
5816 * needs to be salvaged. We could directly tell the
5817 * salvageserver, but the fileserver keeps track of some stats
5818 * related to salvages, and handles some other salvage-related
5819 * complications for us.
5821 *code = FSYNC_VolOp(vp->hashid, partName,
5822 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5825 #endif /* FSSYNC_BUILD_CLIENT */
5830 * schedule a salvage with the salvage server or fileserver.
5832 * @param[in] vp pointer to volume object
5834 * @return operation status
5835 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5836 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5837 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5838 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5839 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5842 * @arg VOL_LOCK is held.
5843 * @arg nUsers and nWaiters should be zero.
5845 * @post salvageserver or fileserver is sent a salvage request
5847 * @note If we are the fileserver, the request will be sent to the salvage
5848 * server over SALVSYNC. If we are not the fileserver, the request will be
5849 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5851 * @note the caller must check if the volume needs to be freed after calling
5852 * this; the volume may not have any references or be on any lists after
5853 * we return, and we do not free it
5857 * @internal volume package internal use only.
5860 VScheduleSalvage_r(Volume * vp)
5862 int ret = VCHECK_SALVAGE_SCHEDULED;
5864 VolState state_save;
5865 VThreadOptions_t * thread_opts;
5868 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5870 if (vp->nWaiters || vp->nUsers) {
5871 return VCHECK_SALVAGE_ASYNC;
5874 /* prevent endless salvage,attach,salvage,attach,... loops */
5875 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5876 return VCHECK_SALVAGE_FAIL;
5880 * don't perform salvsync ops on certain threads
5882 thread_opts = pthread_getspecific(VThread_key);
5883 if (thread_opts == NULL) {
5884 thread_opts = &VThread_defaults;
5886 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5887 return VCHECK_SALVAGE_ASYNC;
5890 if (vp->salvage.scheduled) {
5891 return VCHECK_SALVAGE_SCHEDULED;
5894 VCreateReservation_r(vp);
5895 VWaitExclusiveState_r(vp);
5898 * XXX the scheduling process should really be done asynchronously
5899 * to avoid fssync deadlocks
5901 if (vp->salvage.scheduled) {
5902 ret = VCHECK_SALVAGE_SCHEDULED;
5904 /* if we haven't previously scheduled a salvage, do so now
5906 * set the volume to an exclusive state and drop the lock
5907 * around the SALVSYNC call
5909 strlcpy(partName, vp->partition->name, sizeof(partName));
5910 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5913 opr_Verify(try_SALVSYNC(vp, partName, &code)
5914 || try_FSSYNC(vp, partName, &code));
5917 VChangeState_r(vp, state_save);
5919 if (code == SYNC_OK) {
5920 ret = VCHECK_SALVAGE_SCHEDULED;
5921 vp->salvage.scheduled = 1;
5922 vp->stats.last_salvage_req = FT_ApproxTime();
5923 if (VCanUseSALVSYNC()) {
5924 /* don't record these stats for non-fileservers; let the
5925 * fileserver take care of these */
5926 vp->stats.salvages++;
5927 IncUInt64(&VStats.salvages);
5931 case SYNC_BAD_COMMAND:
5932 case SYNC_COM_ERROR:
5933 ret = VCHECK_SALVAGE_FAIL;
5936 ret = VCHECK_SALVAGE_DENIED;
5937 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5938 "denied\n", afs_printable_VolumeId_lu(vp->hashid));
5941 ret = VCHECK_SALVAGE_FAIL;
5942 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5943 "failed\n", afs_printable_VolumeId_lu(vp->hashid));
5946 ret = VCHECK_SALVAGE_FAIL;
5947 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5948 "received unknown protocol error %d\n",
5949 afs_printable_VolumeId_lu(vp->hashid), code);
5953 if (VCanUseFSSYNC()) {
5954 VChangeState_r(vp, VOL_STATE_ERROR);
5959 /* NB: this is cancelling the reservation we obtained above, but we do
5960 * not call VCancelReservation_r, since that may trigger the vp dtor,
5961 * possibly free'ing the vp. We need to keep the vp around after
5962 * this, as the caller may reference vp without any refs. Instead, it
5963 * is the duty of the caller to inspect 'vp' after we return to see if
5964 * needs to be freed. */
5965 opr_Verify(--vp->nWaiters >= 0);
5968 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5970 #ifdef SALVSYNC_BUILD_CLIENT
5973 * connect to the salvageserver SYNC service.
5975 * @return operation status
5979 * @post connection to salvageserver SYNC service established
5981 * @see VConnectSALV_r
5982 * @see VDisconnectSALV
5983 * @see VReconnectSALV
5990 retVal = VConnectSALV_r();
5996 * connect to the salvageserver SYNC service.
5998 * @return operation status
6002 * @pre VOL_LOCK is held.
6004 * @post connection to salvageserver SYNC service established
6007 * @see VDisconnectSALV_r
6008 * @see VReconnectSALV_r
6009 * @see SALVSYNC_clientInit
6011 * @internal volume package internal use only.
6014 VConnectSALV_r(void)
6016 return SALVSYNC_clientInit();
6020 * disconnect from the salvageserver SYNC service.
6022 * @return operation status
6025 * @pre client should have a live connection to the salvageserver
6027 * @post connection to salvageserver SYNC service destroyed
6029 * @see VDisconnectSALV_r
6031 * @see VReconnectSALV
6034 VDisconnectSALV(void)
6037 VDisconnectSALV_r();
6043 * disconnect from the salvageserver SYNC service.
6045 * @return operation status
6049 * @arg VOL_LOCK is held.
6050 * @arg client should have a live connection to the salvageserver.
6052 * @post connection to salvageserver SYNC service destroyed
6054 * @see VDisconnectSALV
6055 * @see VConnectSALV_r
6056 * @see VReconnectSALV_r
6057 * @see SALVSYNC_clientFinis
6059 * @internal volume package internal use only.
6062 VDisconnectSALV_r(void)
6064 return SALVSYNC_clientFinis();
6068 * disconnect and then re-connect to the salvageserver SYNC service.
6070 * @return operation status
6074 * @pre client should have a live connection to the salvageserver
6076 * @post old connection is dropped, and a new one is established
6079 * @see VDisconnectSALV
6080 * @see VReconnectSALV_r
6083 VReconnectSALV(void)
6087 retVal = VReconnectSALV_r();
6093 * disconnect and then re-connect to the salvageserver SYNC service.
6095 * @return operation status
6100 * @arg VOL_LOCK is held.
6101 * @arg client should have a live connection to the salvageserver.
6103 * @post old connection is dropped, and a new one is established
6105 * @see VConnectSALV_r
6106 * @see VDisconnectSALV
6107 * @see VReconnectSALV
6108 * @see SALVSYNC_clientReconnect
6110 * @internal volume package internal use only.
6113 VReconnectSALV_r(void)
6115 return SALVSYNC_clientReconnect();
6117 #endif /* SALVSYNC_BUILD_CLIENT */
6118 #endif /* AFS_DEMAND_ATTACH_FS */
6121 /***************************************************/
6122 /* FSSYNC routines */
6123 /***************************************************/
6125 /* This must be called by any volume utility which needs to run while the
6126 file server is also running. This is separated from VInitVolumePackage2 so
6127 that a utility can fork--and each of the children can independently
6128 initialize communication with the file server */
6129 #ifdef FSSYNC_BUILD_CLIENT
6131 * connect to the fileserver SYNC service.
6133 * @return operation status
6138 * @arg VInit must equal 2.
6139 * @arg Program Type must not be fileserver or salvager.
6141 * @post connection to fileserver SYNC service established
6144 * @see VDisconnectFS
6145 * @see VChildProcReconnectFS
6152 retVal = VConnectFS_r();
6158 * connect to the fileserver SYNC service.
6160 * @return operation status
6165 * @arg VInit must equal 2.
6166 * @arg Program Type must not be fileserver or salvager.
6167 * @arg VOL_LOCK is held.
6169 * @post connection to fileserver SYNC service established
6172 * @see VDisconnectFS_r
6173 * @see VChildProcReconnectFS_r
6175 * @internal volume package internal use only.
6181 opr_Assert((VInit == 2) &&
6182 (programType != fileServer) &&
6183 (programType != salvager));
6184 rc = FSYNC_clientInit();
6192 * disconnect from the fileserver SYNC service.
6195 * @arg client should have a live connection to the fileserver.
6196 * @arg VOL_LOCK is held.
6197 * @arg Program Type must not be fileserver or salvager.
6199 * @post connection to fileserver SYNC service destroyed
6201 * @see VDisconnectFS
6203 * @see VChildProcReconnectFS_r
6205 * @internal volume package internal use only.
6208 VDisconnectFS_r(void)
6210 opr_Assert((programType != fileServer) &&
6211 (programType != salvager));
6212 FSYNC_clientFinis();
6217 * disconnect from the fileserver SYNC service.
6220 * @arg client should have a live connection to the fileserver.
6221 * @arg Program Type must not be fileserver or salvager.
6223 * @post connection to fileserver SYNC service destroyed
6225 * @see VDisconnectFS_r
6227 * @see VChildProcReconnectFS
6238 * connect to the fileserver SYNC service from a child process following a fork.
6240 * @return operation status
6245 * @arg VOL_LOCK is held.
6246 * @arg current FSYNC handle is shared with a parent process
6248 * @post current FSYNC handle is discarded and a new connection to the
6249 * fileserver SYNC service is established
6251 * @see VChildProcReconnectFS
6253 * @see VDisconnectFS_r
6255 * @internal volume package internal use only.
6258 VChildProcReconnectFS_r(void)
6260 return FSYNC_clientChildProcReconnect();
6264 * connect to the fileserver SYNC service from a child process following a fork.
6266 * @return operation status
6270 * @pre current FSYNC handle is shared with a parent process
6272 * @post current FSYNC handle is discarded and a new connection to the
6273 * fileserver SYNC service is established
6275 * @see VChildProcReconnectFS_r
6277 * @see VDisconnectFS
6280 VChildProcReconnectFS(void)
6284 ret = VChildProcReconnectFS_r();
6288 #endif /* FSSYNC_BUILD_CLIENT */
6291 /***************************************************/
6292 /* volume bitmap routines */
6293 /***************************************************/
6296 * Grow the bitmap by the defined increment
6299 VGrowBitmap(struct vnodeIndex *index)
6303 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6304 osi_Assert(bp != NULL);
6306 bp += index->bitmapSize;
6307 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6308 index->bitmapOffset = index->bitmapSize;
6309 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6315 * allocate a vnode bitmap number for the vnode
6317 * @param[out] ec error code
6318 * @param[in] vp volume object pointer
6319 * @param[in] index vnode index number for the vnode
6320 * @param[in] flags flag values described in note
6322 * @note for DAFS, flags parameter controls locking behavior.
6323 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6324 * will create a reservation and block on any other exclusive
6325 * operations. Otherwise, this function assumes the caller
6326 * already has exclusive access to vp, and we just change the
6329 * @pre VOL_LOCK held
6331 * @return bit number allocated
6337 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6338 struct vnodeIndex *index, int flags)
6342 #ifdef AFS_DEMAND_ATTACH_FS
6343 VolState state_save;
6344 #endif /* AFS_DEMAND_ATTACH_FS */
6348 /* This test is probably redundant */
6349 if (!VolumeWriteable(vp)) {
6350 *ec = (bit32) VREADONLY;
6354 #ifdef AFS_DEMAND_ATTACH_FS
6355 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6356 VCreateReservation_r(vp);
6357 VWaitExclusiveState_r(vp);
6359 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6360 #endif /* AFS_DEMAND_ATTACH_FS */
6363 if ((programType == fileServer) && !index->bitmap) {
6365 #ifndef AFS_DEMAND_ATTACH_FS
6366 /* demand attach fs uses the volume state to avoid races.
6367 * specialStatus field is not used at all */
6369 if (vp->specialStatus == VBUSY) {
6370 if (vp->goingOffline) { /* vos dump waiting for the volume to
6371 * go offline. We probably come here
6372 * from AddNewReadableResidency */
6375 while (vp->specialStatus == VBUSY) {
6376 #ifdef AFS_PTHREAD_ENV
6380 #else /* !AFS_PTHREAD_ENV */
6382 #endif /* !AFS_PTHREAD_ENV */
6386 #endif /* !AFS_DEMAND_ATTACH_FS */
6388 if (!index->bitmap) {
6389 #ifndef AFS_DEMAND_ATTACH_FS
6390 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6391 #endif /* AFS_DEMAND_ATTACH_FS */
6392 for (i = 0; i < nVNODECLASSES; i++) {
6393 VGetBitmap_r(ec, vp, i);
6395 #ifdef AFS_DEMAND_ATTACH_FS
6396 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6397 #else /* AFS_DEMAND_ATTACH_FS */
6398 DeleteVolumeFromHashTable(vp);
6399 vp->shuttingDown = 1; /* Let who has it free it. */
6400 vp->specialStatus = 0;
6401 #endif /* AFS_DEMAND_ATTACH_FS */
6405 #ifndef AFS_DEMAND_ATTACH_FS
6407 vp->specialStatus = 0; /* Allow others to have access. */
6408 #endif /* AFS_DEMAND_ATTACH_FS */
6411 #endif /* BITMAP_LATER */
6413 #ifdef AFS_DEMAND_ATTACH_FS
6415 #endif /* AFS_DEMAND_ATTACH_FS */
6416 bp = index->bitmap + index->bitmapOffset;
6417 ep = index->bitmap + index->bitmapSize;
6419 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6421 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6424 o = opr_ffs(~*bp) - 1;
6426 ret = ((bp - index->bitmap) * 8 + o);
6427 #ifdef AFS_DEMAND_ATTACH_FS
6429 #endif /* AFS_DEMAND_ATTACH_FS */
6432 bp += sizeof(bit32) /* i.e. 4 */ ;
6434 /* No bit map entry--must grow bitmap */
6436 bp = index->bitmap + index->bitmapOffset;
6438 ret = index->bitmapOffset * 8;
6439 #ifdef AFS_DEMAND_ATTACH_FS
6441 #endif /* AFS_DEMAND_ATTACH_FS */
6444 #ifdef AFS_DEMAND_ATTACH_FS
6445 VChangeState_r(vp, state_save);
6446 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6447 VCancelReservation_r(vp);
6449 #endif /* AFS_DEMAND_ATTACH_FS */
6454 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6458 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6464 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6465 unsigned bitNumber, int flags)
6467 unsigned int offset;
6471 #ifdef AFS_DEMAND_ATTACH_FS
6472 if (flags & VOL_FREE_BITMAP_WAIT) {
6473 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6474 * state, so ensure we're not in an exclusive volume state when we update
6476 VCreateReservation_r(vp);
6477 VWaitExclusiveState_r(vp);
6484 #endif /* BITMAP_LATER */
6486 offset = bitNumber >> 3;
6487 if (offset >= index->bitmapSize) {
6491 if (offset < index->bitmapOffset)
6492 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6493 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6496 #ifdef AFS_DEMAND_ATTACH_FS
6497 if (flags & VOL_FREE_BITMAP_WAIT) {
6498 VCancelReservation_r(vp);
6501 return; /* make the compiler happy for non-DAFS */
6505 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6509 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6513 /* this function will drop the glock internally.
6514 * for old pthread fileservers, this is safe thanks to vbusy.
6516 * for demand attach fs, caller must have already called
6517 * VCreateReservation_r and VWaitExclusiveState_r */
6519 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6521 StreamHandle_t *file;
6522 afs_sfsize_t nVnodes, size;
6523 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6524 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6525 struct VnodeDiskObject *vnode;
6526 unsigned int unique = 0;
6530 #endif /* BITMAP_LATER */
6531 #ifdef AFS_DEMAND_ATTACH_FS
6532 VolState state_save;
6533 #endif /* AFS_DEMAND_ATTACH_FS */
6537 #ifdef AFS_DEMAND_ATTACH_FS
6538 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6539 #endif /* AFS_DEMAND_ATTACH_FS */
6542 fdP = IH_OPEN(vip->handle);
6543 opr_Assert(fdP != NULL);
6544 file = FDH_FDOPEN(fdP, "r");
6545 opr_Assert(file != NULL);
6546 vnode = malloc(vcp->diskSize);
6547 opr_Assert(vnode != NULL);
6548 size = OS_SIZE(fdP->fd_fd);
6549 opr_Assert(size != -1);
6550 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6552 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6553 * a few files can be created in this volume,
6554 * the whole thing is rounded up to nearest 4
6555 * bytes, because the bit map allocator likes
6558 BitMap = (byte *) calloc(1, vip->bitmapSize);
6559 opr_Assert(BitMap != NULL);
6560 #else /* BITMAP_LATER */
6561 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6562 opr_Assert(vip->bitmap != NULL);
6563 vip->bitmapOffset = 0;
6564 #endif /* BITMAP_LATER */
6565 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6567 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6568 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6570 if (vnode->type != vNull) {
6571 if (vnode->vnodeMagic != vcp->magic) {
6572 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6577 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6578 #else /* BITMAP_LATER */
6579 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6580 #endif /* BITMAP_LATER */
6581 if (unique <= vnode->uniquifier)
6582 unique = vnode->uniquifier + 1;
6584 #ifndef AFS_PTHREAD_ENV
6585 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6588 #endif /* !AFS_PTHREAD_ENV */
6591 if (vp->nextVnodeUnique < unique) {
6592 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6595 /* Paranoia, partly justified--I think fclose after fdopen
6596 * doesn't seem to close fd. In any event, the documentation
6597 * doesn't specify, so it's safer to close it twice.
6605 /* There may have been a racing condition with some other thread, both
6606 * creating the bitmaps for this volume. If the other thread was faster
6607 * the pointer to bitmap should already be filled and we can free ours.
6609 if (vip->bitmap == NULL) {
6610 vip->bitmap = BitMap;
6611 vip->bitmapOffset = 0;
6614 #endif /* BITMAP_LATER */
6615 #ifdef AFS_DEMAND_ATTACH_FS
6616 VChangeState_r(vp, state_save);
6617 #endif /* AFS_DEMAND_ATTACH_FS */
6621 /***************************************************/
6622 /* Volume Path and Volume Number utility routines */
6623 /***************************************************/
6626 * find the first occurrence of a volume header file and return the path.
6628 * @param[out] ec outbound error code
6629 * @param[in] volumeId volume id to find
6630 * @param[out] partitionp pointer to disk partition path string
6631 * @param[out] namep pointer to volume header file name string
6633 * @post path to first occurrence of volume header is returned in partitionp
6634 * and namep, or ec is set accordingly.
6636 * @warning this function is NOT re-entrant -- partitionp and namep point to
6637 * static data segments
6639 * @note if a volume utility inadvertently leaves behind a stale volume header
6640 * on a vice partition, it is possible for callers to get the wrong one,
6641 * depending on the order of the disk partition linked list.
6645 VGetVolumePath(Error * ec, VolumeId volumeId, char **partitionp, char **namep)
6647 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6648 char path[VMAXPATHLEN];
6650 struct DiskPartition64 *dp;
6653 name[0] = OS_DIRSEPC;
6654 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6655 afs_printable_VolumeId_lu(volumeId));
6656 for (dp = DiskPartitionList; dp; dp = dp->next) {
6657 struct afs_stat_st status;
6658 strcpy(path, VPartitionPath(dp));
6660 if (afs_stat(path, &status) == 0) {
6661 strcpy(partition, dp->name);
6668 *partitionp = *namep = NULL;
6670 *partitionp = partition;
6676 * extract a volume number from a volume header filename string.
6678 * @param[in] name volume header filename string
6680 * @return volume number
6682 * @note the string must be of the form VFORMAT. the only permissible
6683 * deviation is a leading OS_DIRSEPC character.
6688 VolumeNumber(char *name)
6690 if (*name == OS_DIRSEPC)
6692 return strtoul(name + 1, NULL, 10);
6696 * compute the volume header filename.
6698 * @param[in] volumeId
6700 * @return volume header filename
6702 * @post volume header filename string is constructed
6704 * @warning this function is NOT re-entrant -- the returned string is
6705 * stored in a static char array. see VolumeExternalName_r
6706 * for a re-entrant equivalent.
6708 * @see VolumeExternalName_r
6710 * @deprecated due to the above re-entrancy warning, this interface should
6711 * be considered deprecated. Please use VolumeExternalName_r
6715 VolumeExternalName(VolumeId volumeId)
6717 static char name[VMAXPATHLEN];
6718 snprintf(name, sizeof name, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6723 * compute the volume header filename.
6725 * @param[in] volumeId
6726 * @param[inout] name array in which to store filename
6727 * @param[in] len length of name array
6729 * @return result code from afs_snprintf
6731 * @see VolumeExternalName
6734 * @note re-entrant equivalent of VolumeExternalName
6737 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6739 return snprintf(name, len, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6743 /***************************************************/
6744 /* Volume Usage Statistics routines */
6745 /***************************************************/
6747 #define OneDay (86400) /* 24 hours' worth of seconds */
6750 Midnight(time_t t) {
6751 struct tm local, *l;
6754 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6755 l = localtime_r(&t, &local);
6761 /* the following is strictly speaking problematic on the
6762 switching day to daylight saving time, after the switch,
6763 as tm_isdst does not match. Similarly, on the looong day when
6764 switching back the OneDay check will not do what naively expected!
6765 The effects are minor, though, and more a matter of interpreting
6767 #ifndef AFS_PTHREAD_ENV
6770 local.tm_hour = local.tm_min=local.tm_sec = 0;
6771 midnight = mktime(&local);
6772 if (midnight != (time_t) -1) return(midnight);
6774 return( (t/OneDay)*OneDay );
6778 /*------------------------------------------------------------------------
6779 * [export] VAdjustVolumeStatistics
6782 * If we've passed midnight, we need to update all the day use
6783 * statistics as well as zeroing the detailed volume statistics
6784 * (if we are implementing them).
6787 * vp : Pointer to the volume structure describing the lucky
6788 * volume being considered for update.
6794 * Nothing interesting.
6798 *------------------------------------------------------------------------*/
6801 VAdjustVolumeStatistics_r(Volume * vp)
6803 unsigned int now = FT_ApproxTime();
6805 if (now - V_dayUseDate(vp) > OneDay) {
6808 ndays = (now - V_dayUseDate(vp)) / OneDay;
6809 for (i = 6; i > ndays - 1; i--)
6810 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6811 for (i = 0; i < ndays - 1 && i < 7; i++)
6812 V_weekUse(vp)[i] = 0;
6814 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6816 V_dayUseDate(vp) = Midnight(now);
6819 * All we need to do is bzero the entire VOL_STATS_BYTES of
6820 * the detailed volume statistics area.
6822 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6825 /*It's been more than a day of collection */
6827 * Always return happily.
6830 } /*VAdjustVolumeStatistics */
6833 VAdjustVolumeStatistics(Volume * vp)
6837 retVal = VAdjustVolumeStatistics_r(vp);
6843 VBumpVolumeUsage_r(Volume * vp)
6845 unsigned int now = FT_ApproxTime();
6846 V_accessDate(vp) = now;
6847 if (now - V_dayUseDate(vp) > OneDay)
6848 VAdjustVolumeStatistics_r(vp);
6850 * Save the volume header image to disk after a threshold of bumps to dayUse,
6851 * at most every usage_rate_limit seconds.
6854 vp->usage_bumps_outstanding++;
6855 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6856 && vp->usage_bumps_next_write <= now) {
6858 vp->usage_bumps_outstanding = 0;
6859 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6860 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6865 VBumpVolumeUsage(Volume * vp)
6868 VBumpVolumeUsage_r(vp);
6873 VSetDiskUsage_r(void)
6875 #ifndef AFS_DEMAND_ATTACH_FS
6876 static int FifteenMinuteCounter = 0;
6880 /* NOTE: Don't attempt to access the partitions list until the
6881 * initialization level indicates that all volumes are attached,
6882 * which implies that all partitions are initialized. */
6883 #ifdef AFS_PTHREAD_ENV
6884 VOL_CV_WAIT(&vol_vinit_cond);
6885 #else /* AFS_PTHREAD_ENV */
6887 #endif /* AFS_PTHREAD_ENV */
6890 VResetDiskUsage_r();
6892 #ifndef AFS_DEMAND_ATTACH_FS
6893 if (++FifteenMinuteCounter == 3) {
6894 FifteenMinuteCounter = 0;
6897 #endif /* !AFS_DEMAND_ATTACH_FS */
6909 /***************************************************/
6910 /* Volume Update List routines */
6911 /***************************************************/
6913 /* The number of minutes that a volume hasn't been updated before the
6914 * "Dont salvage" flag in the volume header will be turned on */
6915 #define SALVAGE_INTERVAL (10*60)
6920 * volume update list functionality has been moved into the VLRU
6921 * the DONT_SALVAGE flag is now set during VLRU demotion
6924 #ifndef AFS_DEMAND_ATTACH_FS
6925 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6926 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6927 static int updateSize = 0; /* number of entries possible */
6928 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6929 #endif /* !AFS_DEMAND_ATTACH_FS */
6932 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6935 vp->updateTime = FT_ApproxTime();
6936 if (V_dontSalvage(vp) == 0)
6938 V_dontSalvage(vp) = 0;
6939 VSyncVolume_r(ec, vp, 0);
6940 #ifdef AFS_DEMAND_ATTACH_FS
6941 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6942 #else /* !AFS_DEMAND_ATTACH_FS */
6945 if (UpdateList == NULL) {
6946 updateSize = UPDATE_LIST_SIZE;
6947 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6949 if (nUpdatedVolumes == updateSize) {
6951 if (updateSize > 524288) {
6952 Log("warning: there is likely a bug in the volume update scanner\n");
6955 UpdateList = realloc(UpdateList,
6956 sizeof(VolumeId) * updateSize);
6959 opr_Assert(UpdateList != NULL);
6960 UpdateList[nUpdatedVolumes++] = V_id(vp);
6961 #endif /* !AFS_DEMAND_ATTACH_FS */
6964 #ifndef AFS_DEMAND_ATTACH_FS
6966 VScanUpdateList(void)
6971 afs_uint32 now = FT_ApproxTime();
6972 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6973 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6975 UpdateList[i - gap] = UpdateList[i];
6977 /* XXX this routine needlessly messes up the Volume LRU by
6978 * breaking the LRU temporal-locality assumptions.....
6979 * we should use a special volume header allocator here */
6980 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6983 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6984 V_dontSalvage(vp) = DONT_SALVAGE;
6985 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6993 #ifndef AFS_PTHREAD_ENV
6995 #endif /* !AFS_PTHREAD_ENV */
6997 nUpdatedVolumes -= gap;
6999 #endif /* !AFS_DEMAND_ATTACH_FS */
7002 /***************************************************/
7003 /* Volume LRU routines */
7004 /***************************************************/
7009 * with demand attach fs, we attempt to soft detach(1)
7010 * volumes which have not been accessed in a long time
7011 * in order to speed up fileserver shutdown
7013 * (1) by soft detach we mean a process very similar
7014 * to VOffline, except the final state of the
7015 * Volume will be VOL_STATE_PREATTACHED, instead
7016 * of the usual VOL_STATE_UNATTACHED
7018 #ifdef AFS_DEMAND_ATTACH_FS
7020 /* implementation is reminiscent of a generational GC
7022 * queue 0 is newly attached volumes. this queue is
7023 * sorted by attach timestamp
7025 * queue 1 is volumes that have been around a bit
7026 * longer than queue 0. this queue is sorted by
7029 * queue 2 is volumes tha have been around the longest.
7030 * this queue is unsorted
7032 * queue 3 is volumes that have been marked as
7033 * candidates for soft detachment. this queue is
7036 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
7037 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
7040 * definition of a VLRU queue.
7043 volatile struct rx_queue q;
7050 * main VLRU data structure.
7053 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
7056 /** time interval (in seconds) between promotion passes for
7057 * each young generation queue. */
7058 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
7060 /** time interval (in seconds) between soft detach candidate
7061 * scans for each generation queue.
7063 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
7064 * we perform a soft detach pass. */
7065 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
7067 /* scheduler state */
7068 int next_idx; /**< next queue to receive attention */
7069 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
7070 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
7072 int scanner_state; /**< state of scanner thread */
7073 pthread_cond_t cv; /**< state transition CV */
7076 /** global VLRU state */
7077 static struct VLRU volume_LRU;
7080 * defined states for VLRU scanner thread.
7083 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7084 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7085 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7086 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7087 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7088 } vlru_thread_state_t;
7090 /* vlru disk data header stuff */
7091 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7092 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7094 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7095 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7098 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7099 * soft detachment. */
7100 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7102 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7103 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7105 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7106 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7108 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7109 static afs_uint32 VLRU_enabled = 1;
7111 /* queue synchronization routines */
7112 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7113 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7114 static void VLRU_Wait_r(struct VLRU_q * q);
7117 * set VLRU subsystem tunable parameters.
7119 * @param[in] option tunable option to modify
7120 * @param[in] val new value for tunable parameter
7122 * @pre @c VInitVolumePackage2 has not yet been called.
7124 * @post tunable parameter is modified
7128 * @note valid option parameters are:
7129 * @arg @c VLRU_SET_THRESH
7130 * set the period of inactivity after which
7131 * volumes are eligible for soft detachment
7132 * @arg @c VLRU_SET_INTERVAL
7133 * set the time interval between calls
7134 * to the volume LRU "garbage collector"
7135 * @arg @c VLRU_SET_MAX
7136 * set the max number of volumes to deallocate
7140 VLRU_SetOptions(int option, afs_uint32 val)
7142 if (option == VLRU_SET_THRESH) {
7143 VLRU_offline_thresh = val;
7144 } else if (option == VLRU_SET_INTERVAL) {
7145 VLRU_offline_interval = val;
7146 } else if (option == VLRU_SET_MAX) {
7147 VLRU_offline_max = val;
7148 } else if (option == VLRU_SET_ENABLED) {
7151 VLRU_ComputeConstants();
7155 * compute VLRU internal timing parameters.
7157 * @post VLRU scanner thread internal timing parameters are computed
7159 * @note computes internal timing parameters based upon user-modifiable
7160 * tunable parameters.
7164 * @internal volume package internal use only.
7167 VLRU_ComputeConstants(void)
7169 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7171 /* compute the candidate scan interval */
7172 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7174 /* compute the promotion intervals */
7175 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7176 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7179 /* compute the gen 0 scan interval */
7180 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7182 /* compute the gen 0 scan interval */
7183 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7188 * initialize VLRU subsystem.
7190 * @pre this function has not yet been called
7192 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7196 * @internal volume package internal use only.
7202 pthread_attr_t attrs;
7205 if (!VLRU_enabled) {
7206 Log("VLRU: disabled\n");
7210 /* initialize each of the VLRU queues */
7211 for (i = 0; i < VLRU_QUEUES; i++) {
7212 queue_Init(&volume_LRU.q[i]);
7213 volume_LRU.q[i].len = 0;
7214 volume_LRU.q[i].busy = 0;
7215 opr_cv_init(&volume_LRU.q[i].cv);
7218 /* setup the timing constants */
7219 VLRU_ComputeConstants();
7221 /* XXX put inside LogLevel check? */
7222 Log("VLRU: starting scanner with the following configuration parameters:\n");
7223 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7224 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7225 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7226 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7227 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7228 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7230 /* start up the VLRU scanner */
7231 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7232 if (programType == fileServer) {
7233 opr_cv_init(&volume_LRU.cv);
7234 opr_Verify(pthread_attr_init(&attrs) == 0);
7235 opr_Verify(pthread_attr_setdetachstate(&attrs,
7236 PTHREAD_CREATE_DETACHED) == 0);
7237 opr_Verify(pthread_create(&tid, &attrs,
7238 &VLRU_ScannerThread, NULL) == 0);
7243 * initialize the VLRU-related fields of a newly allocated volume object.
7245 * @param[in] vp pointer to volume object
7248 * @arg @c VOL_LOCK is held.
7249 * @arg volume object is not on a VLRU queue.
7251 * @post VLRU fields are initialized to indicate that volume object is not
7252 * currently registered with the VLRU subsystem
7256 * @internal volume package interal use only.
7259 VLRU_Init_Node_r(Volume * vp)
7264 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7265 vp->vlru.idx = VLRU_QUEUE_INVALID;
7269 * add a volume object to a VLRU queue.
7271 * @param[in] vp pointer to volume object
7274 * @arg @c VOL_LOCK is held.
7275 * @arg caller MUST hold a lightweight ref on @p vp.
7276 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7278 * @post the volume object is added to the appropriate VLRU queue
7280 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7281 * then the volume is added to that queue. Otherwise, the value
7282 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7283 * volume is added to the NEW generation queue.
7285 * @note @c VOL_LOCK may be dropped internally
7287 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7288 * during the add operation, and is restored to the previous
7289 * state prior to return.
7293 * @internal volume package internal use only.
7296 VLRU_Add_r(Volume * vp)
7299 VolState state_save;
7304 if (queue_IsOnQueue(&vp->vlru))
7307 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7310 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7311 idx = VLRU_QUEUE_NEW;
7314 VLRU_Wait_r(&volume_LRU.q[idx]);
7316 /* repeat check since VLRU_Wait_r may have dropped
7318 if (queue_IsNotOnQueue(&vp->vlru)) {
7320 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7321 volume_LRU.q[idx].len++;
7322 V_attachFlags(vp) |= VOL_ON_VLRU;
7323 vp->stats.last_promote = FT_ApproxTime();
7326 VChangeState_r(vp, state_save);
7330 * delete a volume object from a VLRU queue.
7332 * @param[in] vp pointer to volume object
7335 * @arg @c VOL_LOCK is held.
7336 * @arg caller MUST hold a lightweight ref on @p vp.
7337 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7339 * @post volume object is removed from the VLRU queue
7341 * @note @c VOL_LOCK may be dropped internally
7345 * @todo We should probably set volume state to something exlcusive
7346 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7348 * @internal volume package internal use only.
7351 VLRU_Delete_r(Volume * vp)
7358 if (queue_IsNotOnQueue(&vp->vlru))
7364 if (idx == VLRU_QUEUE_INVALID)
7366 VLRU_Wait_r(&volume_LRU.q[idx]);
7367 } while (idx != vp->vlru.idx);
7369 /* now remove from the VLRU and update
7370 * the appropriate counter */
7371 queue_Remove(&vp->vlru);
7372 volume_LRU.q[idx].len--;
7373 vp->vlru.idx = VLRU_QUEUE_INVALID;
7374 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7378 * tell the VLRU subsystem that a volume was just accessed.
7380 * @param[in] vp pointer to volume object
7383 * @arg @c VOL_LOCK is held
7384 * @arg caller MUST hold a lightweight ref on @p vp
7385 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7387 * @post volume VLRU access statistics are updated. If the volume was on
7388 * the VLRU soft detach candidate queue, it is moved to the NEW
7391 * @note @c VOL_LOCK may be dropped internally
7395 * @internal volume package internal use only.
7398 VLRU_UpdateAccess_r(Volume * vp)
7400 Volume * rvp = NULL;
7405 if (queue_IsNotOnQueue(&vp->vlru))
7408 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7410 /* update the access timestamp */
7411 vp->stats.last_get = FT_ApproxTime();
7414 * if the volume is on the soft detach candidate
7415 * list, we need to safely move it back to a
7416 * regular generation. this has to be done
7417 * carefully so we don't race against the scanner
7421 /* if this volume is on the soft detach candidate queue,
7422 * then grab exclusive access to the necessary queues */
7423 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7425 VCreateReservation_r(rvp);
7427 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7428 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7429 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7430 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7433 /* make sure multiple threads don't race to update */
7434 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7435 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7439 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7440 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7441 VCancelReservation_r(rvp);
7446 * switch a volume between two VLRU queues.
7448 * @param[in] vp pointer to volume object
7449 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7450 * @param[in] append controls whether the volume will be appended or
7451 * prepended to the queue. A nonzero value means it will
7452 * be appended; zero means it will be prepended.
7454 * @pre The new (and old, if applicable) queue(s) must either be owned
7455 * exclusively by the calling thread for asynchronous manipulation,
7456 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7457 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7458 * for further details of the queue asynchronous processing mechanism.
7460 * @post If the volume object was already on a VLRU queue, it is
7461 * removed from the queue. Depending on the value of the append
7462 * parameter, the volume object is either appended or prepended
7463 * to the VLRU queue referenced by the new_idx parameter.
7467 * @see VLRU_BeginExclusive_r
7468 * @see VLRU_EndExclusive_r
7471 * @internal volume package internal use only.
7474 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7476 if (queue_IsNotOnQueue(&vp->vlru))
7479 queue_Remove(&vp->vlru);
7480 volume_LRU.q[vp->vlru.idx].len--;
7482 /* put the volume back on the correct generational queue */
7484 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7486 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7489 volume_LRU.q[new_idx].len++;
7490 vp->vlru.idx = new_idx;
7494 * VLRU background thread.
7496 * The VLRU Scanner Thread is responsible for periodically scanning through
7497 * each VLRU queue looking for volumes which should be moved to another
7498 * queue, or soft detached.
7500 * @param[in] args unused thread arguments parameter
7502 * @return unused thread return value
7503 * @retval NULL always
7505 * @internal volume package internal use only.
7508 VLRU_ScannerThread(void * args)
7510 afs_uint32 now, min_delay, delay;
7511 int i, min_idx, min_op, overdue, state;
7513 /* set t=0 for promotion cycle to be
7514 * fileserver startup */
7515 now = FT_ApproxTime();
7516 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7517 volume_LRU.last_promotion[i] = now;
7520 /* don't start the scanner until VLRU_offline_thresh
7521 * plus a small delay for VInitVolumePackage2 to finish
7524 sleep(VLRU_offline_thresh + 60);
7526 /* set t=0 for scan cycle to be now */
7527 now = FT_ApproxTime();
7528 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7529 volume_LRU.last_scan[i] = now;
7533 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7534 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7537 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7538 /* check to see if we've been asked to pause */
7539 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7540 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7541 opr_cv_broadcast(&volume_LRU.cv);
7543 VOL_CV_WAIT(&volume_LRU.cv);
7544 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7547 /* scheduling can happen outside the glock */
7550 /* figure out what is next on the schedule */
7552 /* figure out a potential schedule for the new generation first */
7554 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7557 if (min_delay > volume_LRU.scan_interval[0]) {
7558 /* unsigned overflow -- we're overdue to run this scan */
7563 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7565 i = VLRU_QUEUE_CANDIDATE;
7566 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7567 if (delay < min_delay) {
7571 if (delay > volume_LRU.scan_interval[i]) {
7572 /* unsigned overflow -- we're overdue to run this scan */
7579 /* if we're still not overdue for something, figure out schedules for promotions */
7580 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7581 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7582 if (delay < min_delay) {
7587 if (delay > volume_LRU.promotion_interval[i]) {
7588 /* unsigned overflow -- we're overdue to run this promotion */
7597 /* sleep as needed */
7602 /* do whatever is next */
7605 VLRU_Promote_r(min_idx);
7606 VLRU_Demote_r(min_idx+1);
7608 VLRU_Scan_r(min_idx);
7610 now = FT_ApproxTime();
7613 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7615 /* signal that scanner is down */
7616 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7617 opr_cv_broadcast(&volume_LRU.cv);
7623 * promote volumes from one VLRU generation to the next.
7625 * This routine scans a VLRU generation looking for volumes which are
7626 * eligible to be promoted to the next generation. All volumes which
7627 * meet the eligibility requirement are promoted.
7629 * Promotion eligibility is based upon meeting both of the following
7632 * @arg The volume has been accessed since the last promotion:
7633 * @c (vp->stats.last_get >= vp->stats.last_promote)
7634 * @arg The last promotion occurred at least
7635 * @c volume_LRU.promotion_interval[idx] seconds ago
7637 * As a performance optimization, promotions are "globbed". In other
7638 * words, we promote arbitrarily large contiguous sublists of elements
7641 * @param[in] idx VLRU queue index to scan
7645 * @internal VLRU internal use only.
7648 VLRU_Promote_r(int idx)
7650 int len, chaining, promote;
7651 afs_uint32 now, thresh;
7652 struct rx_queue *qp, *nqp;
7653 Volume * vp, *start = NULL, *end = NULL;
7655 /* get exclusive access to two chains, and drop the glock */
7656 VLRU_Wait_r(&volume_LRU.q[idx]);
7657 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7658 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7659 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7662 thresh = volume_LRU.promotion_interval[idx];
7663 now = FT_ApproxTime();
7666 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7667 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7668 promote = (((vp->stats.last_promote + thresh) <= now) &&
7669 (vp->stats.last_get >= vp->stats.last_promote));
7677 /* promote and prepend chain */
7678 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7692 /* promote and prepend */
7693 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7697 volume_LRU.q[idx].len -= len;
7698 volume_LRU.q[idx+1].len += len;
7701 /* release exclusive access to the two chains */
7703 volume_LRU.last_promotion[idx] = now;
7704 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7705 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7708 /* run the demotions */
7710 VLRU_Demote_r(int idx)
7713 int len, chaining, demote;
7714 afs_uint32 now, thresh;
7715 struct rx_queue *qp, *nqp;
7716 Volume * vp, *start = NULL, *end = NULL;
7717 Volume ** salv_flag_vec = NULL;
7718 int salv_vec_offset = 0;
7720 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7722 /* get exclusive access to two chains, and drop the glock */
7723 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7724 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7725 VLRU_Wait_r(&volume_LRU.q[idx]);
7726 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7729 /* no big deal if this allocation fails */
7730 if (volume_LRU.q[idx].len) {
7731 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7734 now = FT_ApproxTime();
7735 thresh = volume_LRU.promotion_interval[idx-1];
7738 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7739 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7740 demote = (((vp->stats.last_promote + thresh) <= now) &&
7741 (vp->stats.last_get < (now - thresh)));
7743 /* we now do volume update list DONT_SALVAGE flag setting during
7744 * demotion passes */
7745 if (salv_flag_vec &&
7746 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7748 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7749 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7750 salv_flag_vec[salv_vec_offset++] = vp;
7751 VCreateReservation_r(vp);
7760 /* demote and append chain */
7761 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7775 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7779 volume_LRU.q[idx].len -= len;
7780 volume_LRU.q[idx-1].len += len;
7783 /* release exclusive access to the two chains */
7785 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7786 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7788 /* now go back and set the DONT_SALVAGE flags as appropriate */
7789 if (salv_flag_vec) {
7791 for (i = 0; i < salv_vec_offset; i++) {
7792 vp = salv_flag_vec[i];
7793 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7794 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7795 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7798 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7799 V_dontSalvage(vp) = DONT_SALVAGE;
7800 VUpdateVolume_r(&ec, vp, 0);
7804 VCancelReservation_r(vp);
7806 free(salv_flag_vec);
7810 /* run a pass of the VLRU GC scanner */
7812 VLRU_Scan_r(int idx)
7814 afs_uint32 now, thresh;
7815 struct rx_queue *qp, *nqp;
7819 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7821 /* gain exclusive access to the idx VLRU */
7822 VLRU_Wait_r(&volume_LRU.q[idx]);
7823 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7825 if (idx != VLRU_QUEUE_CANDIDATE) {
7826 /* gain exclusive access to the candidate VLRU */
7827 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7828 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7831 now = FT_ApproxTime();
7832 thresh = now - VLRU_offline_thresh;
7834 /* perform candidate selection and soft detaching */
7835 if (idx == VLRU_QUEUE_CANDIDATE) {
7836 /* soft detach some volumes from the candidate pool */
7840 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7841 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7842 if (i >= VLRU_offline_max) {
7845 /* check timestamp to see if it's a candidate for soft detaching */
7846 if (vp->stats.last_get <= thresh) {
7848 if (VCheckSoftDetach(vp, thresh))
7854 /* scan for volumes to become soft detach candidates */
7855 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7856 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7858 /* check timestamp to see if it's a candidate for soft detaching */
7859 if (vp->stats.last_get <= thresh) {
7860 VCheckSoftDetachCandidate(vp, thresh);
7863 if (!(i&0x7f)) { /* lock coarsening optimization */
7871 /* relinquish exclusive access to the VLRU chains */
7875 volume_LRU.last_scan[idx] = now;
7876 if (idx != VLRU_QUEUE_CANDIDATE) {
7877 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7879 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7882 /* check whether volume is safe to soft detach
7883 * caller MUST NOT hold a ref count on vp */
7885 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7889 if (vp->nUsers || vp->nWaiters)
7892 if (vp->stats.last_get <= thresh) {
7893 ret = VSoftDetachVolume_r(vp, thresh);
7899 /* check whether volume should be made a
7900 * soft detach candidate */
7902 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7905 if (vp->nUsers || vp->nWaiters)
7910 opr_Assert(idx == VLRU_QUEUE_NEW);
7912 if (vp->stats.last_get <= thresh) {
7913 /* move to candidate pool */
7914 queue_Remove(&vp->vlru);
7915 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7916 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7917 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7918 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7926 /* begin exclusive access on VLRU */
7928 VLRU_BeginExclusive_r(struct VLRU_q * q)
7930 opr_Assert(q->busy == 0);
7934 /* end exclusive access on VLRU */
7936 VLRU_EndExclusive_r(struct VLRU_q * q)
7938 opr_Assert(q->busy);
7940 opr_cv_broadcast(&q->cv);
7943 /* wait for another thread to end exclusive access on VLRU */
7945 VLRU_Wait_r(struct VLRU_q * q)
7948 VOL_CV_WAIT(&q->cv);
7953 * volume soft detach
7955 * caller MUST NOT hold a ref count on vp */
7957 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7962 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7964 ts_save = vp->stats.last_get;
7965 if (ts_save > thresh)
7968 if (vp->nUsers || vp->nWaiters)
7971 if (VIsExclusiveState(V_attachState(vp))) {
7975 switch (V_attachState(vp)) {
7976 case VOL_STATE_UNATTACHED:
7977 case VOL_STATE_PREATTACHED:
7978 case VOL_STATE_ERROR:
7979 case VOL_STATE_GOING_OFFLINE:
7980 case VOL_STATE_SHUTTING_DOWN:
7981 case VOL_STATE_SALVAGING:
7982 case VOL_STATE_DELETED:
7983 volume_LRU.q[vp->vlru.idx].len--;
7985 /* create and cancel a reservation to
7986 * give the volume an opportunity to
7988 VCreateReservation_r(vp);
7989 queue_Remove(&vp->vlru);
7990 vp->vlru.idx = VLRU_QUEUE_INVALID;
7991 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7992 VCancelReservation_r(vp);
7998 /* hold the volume and take it offline.
7999 * no need for reservations, as VHold_r
8000 * takes care of that internally. */
8001 if (VHold_r(vp) == 0) {
8002 /* vhold drops the glock, so now we should
8003 * check to make sure we aren't racing against
8004 * other threads. if we are racing, offlining vp
8005 * would be wasteful, and block the scanner for a while
8009 (vp->shuttingDown) ||
8010 (vp->goingOffline) ||
8011 (vp->stats.last_get != ts_save)) {
8012 /* looks like we're racing someone else. bail */
8016 /* pull it off the VLRU */
8017 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
8018 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
8019 queue_Remove(&vp->vlru);
8020 vp->vlru.idx = VLRU_QUEUE_INVALID;
8021 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
8023 /* take if offline */
8024 VOffline_r(vp, "volume has been soft detached");
8026 /* invalidate the volume header cache */
8027 FreeVolumeHeader(vp);
8030 IncUInt64(&VStats.soft_detaches);
8031 vp->stats.soft_detaches++;
8033 /* put in pre-attached state so demand
8034 * attacher can work on it */
8035 VChangeState_r(vp, VOL_STATE_PREATTACHED);
8041 #endif /* AFS_DEMAND_ATTACH_FS */
8044 /***************************************************/
8045 /* Volume Header Cache routines */
8046 /***************************************************/
8049 * volume header cache.
8051 struct volume_hdr_LRU_t volume_hdr_LRU;
8054 * initialize the volume header cache.
8056 * @param[in] howMany number of header cache entries to preallocate
8058 * @pre VOL_LOCK held. Function has never been called before.
8060 * @post howMany cache entries are allocated, initialized, and added
8061 * to the LRU list. Header cache statistics are initialized.
8063 * @note only applicable to fileServer program type. Should only be
8064 * called once during volume package initialization.
8066 * @internal volume package internal use only.
8069 VInitVolumeHeaderCache(afs_uint32 howMany)
8071 struct volHeader *hp;
8072 if (programType != fileServer)
8074 queue_Init(&volume_hdr_LRU);
8075 volume_hdr_LRU.stats.free = 0;
8076 volume_hdr_LRU.stats.used = howMany;
8077 volume_hdr_LRU.stats.attached = 0;
8078 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8079 opr_Assert(hp != NULL);
8082 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8083 * to ensure they have the right values
8085 ReleaseVolumeHeader(hp++);
8088 /* get a volume header off of the volume header LRU.
8090 * @return volume header
8091 * @retval NULL no usable volume header is available on the LRU
8093 * @pre VOL_LOCK held
8095 * @post for DAFS, if the returned header is associated with a volume, that
8096 * volume is NOT in an exclusive state
8098 * @internal volume package internal use only.
8100 #ifdef AFS_DEMAND_ATTACH_FS
8101 static struct volHeader*
8102 GetVolHeaderFromLRU(void)
8104 struct volHeader *hd = NULL, *qh, *nqh;
8105 /* Usually, a volume in an exclusive state will not have its header on
8106 * the LRU. However, it is possible for this to occur when a salvage
8107 * request is received over FSSYNC, and possibly in other corner cases.
8108 * So just skip over headers whose volumes are in an exclusive state. We
8109 * could VWaitExclusiveState_r instead, but not waiting is faster and
8111 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8112 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8120 #else /* AFS_DEMAND_ATTACH_FS */
8121 static struct volHeader*
8122 GetVolHeaderFromLRU(void)
8124 struct volHeader *hd = NULL;
8125 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8126 hd = queue_First(&volume_hdr_LRU, volHeader);
8131 #endif /* !AFS_DEMAND_ATTACH_FS */
8134 * get a volume header and attach it to the volume object.
8136 * @param[in] vp pointer to volume object
8138 * @return cache entry status
8139 * @retval 0 volume header was newly attached; cache data is invalid
8140 * @retval 1 volume header was previously attached; cache data is valid
8142 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8144 * @post volume header attached to volume object. if necessary, header cache
8145 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8147 * @note VOL_LOCK may be dropped
8149 * @warning this interface does not load header data from disk. it merely
8150 * attaches a header object to the volume object, and may sync the old
8151 * header cache data out to disk in the process.
8153 * @internal volume package internal use only.
8156 GetVolumeHeader(Volume * vp)
8159 struct volHeader *hd;
8161 static int everLogged = 0;
8163 #ifdef AFS_DEMAND_ATTACH_FS
8164 VolState vp_save = 0, back_save = 0;
8166 /* XXX debug 9/19/05 we've apparently got
8167 * a ref counting bug somewhere that's
8168 * breaking the nUsers == 0 => header on LRU
8170 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8171 Log("nUsers == 0, but header not on LRU\n");
8176 old = (vp->header != NULL); /* old == volume already has a header */
8178 if (programType != fileServer) {
8179 /* for volume utilities, we allocate volHeaders as needed */
8181 hd = calloc(1, sizeof(*vp->header));
8182 opr_Assert(hd != NULL);
8185 #ifdef AFS_DEMAND_ATTACH_FS
8186 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8190 /* for the fileserver, we keep a volume header cache */
8192 /* the header we previously dropped in the lru is
8193 * still available. pull it off the lru and return */
8196 opr_Assert(hd->back == vp);
8197 #ifdef AFS_DEMAND_ATTACH_FS
8198 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8201 hd = GetVolHeaderFromLRU();
8203 /* LRU is empty, so allocate a new volHeader
8204 * this is probably indicative of a leak, so let the user know */
8205 hd = calloc(1, sizeof(struct volHeader));
8206 opr_Assert(hd != NULL);
8208 Log("****Allocated more volume headers, probably leak****\n");
8211 volume_hdr_LRU.stats.free++;
8214 /* this header used to belong to someone else.
8215 * we'll need to check if the header needs to
8216 * be sync'd out to disk */
8218 #ifdef AFS_DEMAND_ATTACH_FS
8219 /* GetVolHeaderFromLRU had better not give us back a header
8220 * with a volume in exclusive state... */
8221 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8224 if (hd->diskstuff.inUse) {
8225 /* volume was in use, so we'll need to sync
8226 * its header to disk */
8228 #ifdef AFS_DEMAND_ATTACH_FS
8229 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8230 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8231 VCreateReservation_r(hd->back);
8235 WriteVolumeHeader_r(&error, hd->back);
8236 /* Ignore errors; catch them later */
8238 #ifdef AFS_DEMAND_ATTACH_FS
8243 hd->back->header = NULL;
8244 #ifdef AFS_DEMAND_ATTACH_FS
8245 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8247 if (hd->diskstuff.inUse) {
8248 VChangeState_r(hd->back, back_save);
8249 VCancelReservation_r(hd->back);
8250 VChangeState_r(vp, vp_save);
8254 volume_hdr_LRU.stats.attached++;
8258 #ifdef AFS_DEMAND_ATTACH_FS
8259 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8262 volume_hdr_LRU.stats.free--;
8263 volume_hdr_LRU.stats.used++;
8265 IncUInt64(&VStats.hdr_gets);
8266 #ifdef AFS_DEMAND_ATTACH_FS
8267 IncUInt64(&vp->stats.hdr_gets);
8268 vp->stats.last_hdr_get = FT_ApproxTime();
8275 * make sure volume header is attached and contains valid cache data.
8277 * @param[out] ec outbound error code
8278 * @param[in] vp pointer to volume object
8280 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8282 * @post header cache entry attached, and loaded with valid data, or
8283 * *ec is nonzero, and the header is released back into the LRU.
8285 * @internal volume package internal use only.
8288 LoadVolumeHeader(Error * ec, Volume * vp)
8290 #ifdef AFS_DEMAND_ATTACH_FS
8291 VolState state_save;
8295 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8296 IncUInt64(&VStats.hdr_loads);
8297 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8300 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8301 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8303 IncUInt64(&vp->stats.hdr_loads);
8304 now = FT_ApproxTime();
8308 V_attachFlags(vp) |= VOL_HDR_LOADED;
8309 vp->stats.last_hdr_load = now;
8311 VChangeState_r(vp, state_save);
8313 #else /* AFS_DEMAND_ATTACH_FS */
8315 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8316 IncUInt64(&VStats.hdr_loads);
8318 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8319 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8322 #endif /* AFS_DEMAND_ATTACH_FS */
8324 /* maintain (nUsers==0) => header in LRU invariant */
8325 FreeVolumeHeader(vp);
8330 * release a header cache entry back into the LRU list.
8332 * @param[in] hd pointer to volume header cache object
8334 * @pre VOL_LOCK held.
8336 * @post header cache object appended onto end of LRU list.
8338 * @note only applicable to fileServer program type.
8340 * @note used to place a header cache entry back into the
8341 * LRU pool without invalidating it as a cache entry.
8343 * @internal volume package internal use only.
8346 ReleaseVolumeHeader(struct volHeader *hd)
8348 if (programType != fileServer)
8350 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8352 queue_Append(&volume_hdr_LRU, hd);
8353 #ifdef AFS_DEMAND_ATTACH_FS
8355 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8358 volume_hdr_LRU.stats.free++;
8359 volume_hdr_LRU.stats.used--;
8363 * free/invalidate a volume header cache entry.
8365 * @param[in] vp pointer to volume object
8367 * @pre VOL_LOCK is held.
8369 * @post For fileserver, header cache entry is returned to LRU, and it is
8370 * invalidated as a cache entry. For volume utilities, the header
8371 * cache entry is freed.
8373 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8374 * whenever it is necessary to invalidate the header cache entry.
8376 * @see ReleaseVolumeHeader
8378 * @internal volume package internal use only.
8381 FreeVolumeHeader(Volume * vp)
8383 struct volHeader *hd = vp->header;
8386 if (programType == fileServer) {
8387 ReleaseVolumeHeader(hd);
8392 #ifdef AFS_DEMAND_ATTACH_FS
8393 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8395 volume_hdr_LRU.stats.attached--;
8400 /***************************************************/
8401 /* Volume Hash Table routines */
8402 /***************************************************/
8405 * set size of volume object hash table.
8407 * @param[in] logsize log(2) of desired hash table size
8409 * @return operation status
8411 * @retval -1 failure
8413 * @pre MUST be called prior to VInitVolumePackage2
8415 * @post Volume Hash Table will have 2^logsize buckets
8418 VSetVolHashSize(int logsize)
8420 /* 64 to 268435456 hash buckets seems like a reasonable range */
8421 if ((logsize < 6 ) || (logsize > 28)) {
8426 VolumeHashTable.Size = opr_jhash_size(logsize);
8427 VolumeHashTable.Mask = opr_jhash_mask(logsize);
8429 /* we can't yet support runtime modification of this
8430 * parameter. we'll need a configuration rwlock to
8431 * make runtime modification feasible.... */
8438 * initialize dynamic data structures for volume hash table.
8440 * @post hash table is allocated, and fields are initialized.
8442 * @internal volume package internal use only.
8445 VInitVolumeHash(void)
8449 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8450 sizeof(VolumeHashChainHead));
8451 opr_Assert(VolumeHashTable.Table != NULL);
8453 for (i=0; i < VolumeHashTable.Size; i++) {
8454 queue_Init(&VolumeHashTable.Table[i]);
8455 #ifdef AFS_DEMAND_ATTACH_FS
8456 opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8457 #endif /* AFS_DEMAND_ATTACH_FS */
8462 * add a volume object to the hash table.
8464 * @param[in] vp pointer to volume object
8465 * @param[in] hashid hash of volume id
8467 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8470 * @post volume is added to hash chain.
8472 * @internal volume package internal use only.
8474 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8475 * asynchronous hash chain reordering to finish.
8478 AddVolumeToHashTable(Volume * vp, VolumeId hashid)
8480 VolumeHashChainHead * head;
8482 if (queue_IsOnQueue(vp))
8485 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8487 #ifdef AFS_DEMAND_ATTACH_FS
8488 /* wait for the hash chain to become available */
8491 V_attachFlags(vp) |= VOL_IN_HASH;
8492 vp->chainCacheCheck = ++head->cacheCheck;
8493 #endif /* AFS_DEMAND_ATTACH_FS */
8496 vp->hashid = hashid;
8497 queue_Append(head, vp);
8501 * delete a volume object from the hash table.
8503 * @param[in] vp pointer to volume object
8505 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8508 * @post volume is removed from hash chain.
8510 * @internal volume package internal use only.
8512 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8513 * asynchronous hash chain reordering to finish.
8516 DeleteVolumeFromHashTable(Volume * vp)
8518 VolumeHashChainHead * head;
8520 if (!queue_IsOnQueue(vp))
8523 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8525 #ifdef AFS_DEMAND_ATTACH_FS
8526 /* wait for the hash chain to become available */
8529 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8531 #endif /* AFS_DEMAND_ATTACH_FS */
8535 /* do NOT reset hashid to zero, as the online
8536 * salvager package may need to know the volume id
8537 * after the volume is removed from the hash */
8541 * lookup a volume object in the hash table given a volume id.
8543 * @param[out] ec error code return
8544 * @param[in] volumeId volume id
8545 * @param[in] hint volume object which we believe could be the correct
8548 * @return volume object pointer
8549 * @retval NULL no such volume id is registered with the hash table.
8551 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8554 * @post volume object with the given id is returned. volume object and
8555 * hash chain access statistics are updated. hash chain may have
8558 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8559 * asynchronous hash chain reordering operation to finish, or
8560 * in order for us to perform an asynchronous chain reordering.
8562 * @note Hash chain reorderings occur when the access count for the
8563 * volume object being looked up exceeds the sum of the previous
8564 * node's (the node ahead of it in the hash chain linked list)
8565 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8567 * @note For DAFS, the hint parameter allows us to short-circuit if the
8568 * cacheCheck fields match between the hash chain head and the
8569 * hint volume object.
8572 VLookupVolume_r(Error * ec, VolumeId volumeId, Volume * hint)
8576 #ifdef AFS_DEMAND_ATTACH_FS
8579 VolumeHashChainHead * head;
8582 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8584 #ifdef AFS_DEMAND_ATTACH_FS
8585 /* wait for the hash chain to become available */
8588 /* check to see if we can short circuit without walking the hash chain */
8589 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8590 IncUInt64(&hint->stats.hash_short_circuits);
8593 #endif /* AFS_DEMAND_ATTACH_FS */
8595 /* someday we need to either do per-chain locks, RWlocks,
8596 * or both for volhash access.
8597 * (and move to a data structure with better cache locality) */
8599 /* search the chain for this volume id */
8600 for(queue_Scan(head, vp, np, Volume)) {
8602 if (vp->hashid == volumeId) {
8607 if (queue_IsEnd(head, vp)) {
8611 #ifdef AFS_DEMAND_ATTACH_FS
8612 /* update hash chain statistics */
8615 FillInt64(lks, 0, looks);
8616 AddUInt64(head->looks, lks, &head->looks);
8617 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8618 IncUInt64(&head->gets);
8623 IncUInt64(&vp->stats.hash_lookups);
8625 /* for demand attach fileserver, we permit occasional hash chain reordering
8626 * so that frequently looked up volumes move towards the head of the chain */
8627 pp = queue_Prev(vp, Volume);
8628 if (!queue_IsEnd(head, pp)) {
8629 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8630 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8631 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8632 VReorderHash_r(head, pp, vp);
8636 /* update the short-circuit cache check */
8637 vp->chainCacheCheck = head->cacheCheck;
8639 #endif /* AFS_DEMAND_ATTACH_FS */
8644 #ifdef AFS_DEMAND_ATTACH_FS
8645 /* perform volume hash chain reordering.
8647 * advance a subchain beginning at vp ahead of
8648 * the adjacent subchain ending at pp */
8650 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8652 Volume *tp, *np, *lp;
8653 afs_uint64 move_thresh;
8655 /* this should never be called if the chain is already busy, so
8656 * no need to wait for other exclusive chain ops to finish */
8658 /* this is a rather heavy set of operations,
8659 * so let's set the chain busy flag and drop
8661 VHashBeginExclusive_r(head);
8664 /* scan forward in the chain from vp looking for the last element
8665 * in the chain we want to advance */
8666 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8667 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8668 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8669 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8673 lp = queue_Prev(tp, Volume);
8675 /* scan backwards from pp to determine where to splice and
8676 * insert the subchain we're advancing */
8677 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8678 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8682 tp = queue_Next(tp, Volume);
8684 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8685 queue_MoveChainBefore(tp,vp,lp);
8688 IncUInt64(&VStats.hash_reorders);
8690 IncUInt64(&head->reorders);
8692 /* wake up any threads waiting for the hash chain */
8693 VHashEndExclusive_r(head);
8697 /* demand-attach fs volume hash
8698 * asynchronous exclusive operations */
8701 * begin an asynchronous exclusive operation on a volume hash chain.
8703 * @param[in] head pointer to volume hash chain head object
8705 * @pre VOL_LOCK held. hash chain is quiescent.
8707 * @post hash chain marked busy.
8709 * @note this interface is used in conjunction with VHashEndExclusive_r and
8710 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8711 * volume hash chain. Its main use case is hash chain reordering, which
8712 * has the potential to be a highly latent operation.
8714 * @see VHashEndExclusive_r
8719 * @internal volume package internal use only.
8722 VHashBeginExclusive_r(VolumeHashChainHead * head)
8724 opr_Assert(head->busy == 0);
8729 * relinquish exclusive ownership of a volume hash chain.
8731 * @param[in] head pointer to volume hash chain head object
8733 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8735 * @post hash chain is marked quiescent. threads awaiting use of
8736 * chain are awakened.
8738 * @see VHashBeginExclusive_r
8743 * @internal volume package internal use only.
8746 VHashEndExclusive_r(VolumeHashChainHead * head)
8748 opr_Assert(head->busy);
8750 opr_cv_broadcast(&head->chain_busy_cv);
8754 * wait for all asynchronous operations on a hash chain to complete.
8756 * @param[in] head pointer to volume hash chain head object
8758 * @pre VOL_LOCK held.
8760 * @post hash chain object is quiescent.
8762 * @see VHashBeginExclusive_r
8763 * @see VHashEndExclusive_r
8767 * @note This interface should be called before any attempt to
8768 * traverse the hash chain. It is permissible for a thread
8769 * to gain exclusive access to the chain, and then perform
8770 * latent operations on the chain asynchronously wrt the
8773 * @warning if waiting is necessary, VOL_LOCK is dropped
8775 * @internal volume package internal use only.
8778 VHashWait_r(VolumeHashChainHead * head)
8780 while (head->busy) {
8781 VOL_CV_WAIT(&head->chain_busy_cv);
8784 #endif /* AFS_DEMAND_ATTACH_FS */
8787 /***************************************************/
8788 /* Volume by Partition List routines */
8789 /***************************************************/
8792 * demand attach fileserver adds a
8793 * linked list of volumes to each
8794 * partition object, thus allowing
8795 * for quick enumeration of all
8796 * volumes on a partition
8799 #ifdef AFS_DEMAND_ATTACH_FS
8801 * add a volume to its disk partition VByPList.
8803 * @param[in] vp pointer to volume object
8805 * @pre either the disk partition VByPList is owned exclusively
8806 * by the calling thread, or the list is quiescent and
8809 * @post volume is added to disk partition VByPList
8813 * @warning it is the caller's responsibility to ensure list
8816 * @see VVByPListWait_r
8817 * @see VVByPListBeginExclusive_r
8818 * @see VVByPListEndExclusive_r
8820 * @internal volume package internal use only.
8823 AddVolumeToVByPList_r(Volume * vp)
8825 if (queue_IsNotOnQueue(&vp->vol_list)) {
8826 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8827 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8828 vp->partition->vol_list.len++;
8833 * delete a volume from its disk partition VByPList.
8835 * @param[in] vp pointer to volume object
8837 * @pre either the disk partition VByPList is owned exclusively
8838 * by the calling thread, or the list is quiescent and
8841 * @post volume is removed from the disk partition VByPList
8845 * @warning it is the caller's responsibility to ensure list
8848 * @see VVByPListWait_r
8849 * @see VVByPListBeginExclusive_r
8850 * @see VVByPListEndExclusive_r
8852 * @internal volume package internal use only.
8855 DeleteVolumeFromVByPList_r(Volume * vp)
8857 if (queue_IsOnQueue(&vp->vol_list)) {
8858 queue_Remove(&vp->vol_list);
8859 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8860 vp->partition->vol_list.len--;
8865 * begin an asynchronous exclusive operation on a VByPList.
8867 * @param[in] dp pointer to disk partition object
8869 * @pre VOL_LOCK held. VByPList is quiescent.
8871 * @post VByPList marked busy.
8873 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8874 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8877 * @see VVByPListEndExclusive_r
8878 * @see VVByPListWait_r
8882 * @internal volume package internal use only.
8884 /* take exclusive control over the list */
8886 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8888 opr_Assert(dp->vol_list.busy == 0);
8889 dp->vol_list.busy = 1;
8893 * relinquish exclusive ownership of a VByPList.
8895 * @param[in] dp pointer to disk partition object
8897 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8899 * @post VByPList is marked quiescent. threads awaiting use of
8900 * the list are awakened.
8902 * @see VVByPListBeginExclusive_r
8903 * @see VVByPListWait_r
8907 * @internal volume package internal use only.
8910 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8912 opr_Assert(dp->vol_list.busy);
8913 dp->vol_list.busy = 0;
8914 opr_cv_broadcast(&dp->vol_list.cv);
8918 * wait for all asynchronous operations on a VByPList to complete.
8920 * @param[in] dp pointer to disk partition object
8922 * @pre VOL_LOCK is held.
8924 * @post disk partition's VByP list is quiescent
8928 * @note This interface should be called before any attempt to
8929 * traverse the VByPList. It is permissible for a thread
8930 * to gain exclusive access to the list, and then perform
8931 * latent operations on the list asynchronously wrt the
8934 * @warning if waiting is necessary, VOL_LOCK is dropped
8936 * @see VVByPListEndExclusive_r
8937 * @see VVByPListBeginExclusive_r
8939 * @internal volume package internal use only.
8942 VVByPListWait_r(struct DiskPartition64 * dp)
8944 while (dp->vol_list.busy) {
8945 VOL_CV_WAIT(&dp->vol_list.cv);
8948 #endif /* AFS_DEMAND_ATTACH_FS */
8950 /***************************************************/
8951 /* Volume Cache Statistics routines */
8952 /***************************************************/
8955 VPrintCacheStats_r(void)
8957 struct VnodeClassInfo *vcp;
8958 vcp = &VnodeClassInfo[vLarge];
8959 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);
8960 vcp = &VnodeClassInfo[vSmall];
8961 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);
8962 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8963 "%"AFS_INT64_FMT" replacements\n",
8964 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8968 VPrintCacheStats(void)
8971 VPrintCacheStats_r();
8975 #ifdef AFS_DEMAND_ATTACH_FS
8977 UInt64ToDouble(afs_uint64 * x)
8979 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8981 SplitInt64(*x, h, l);
8982 return (((double)h) * c32) + ((double) l);
8986 DoubleToPrintable(double x, char * buf, int len)
8988 static double billion = 1000000000.0;
8991 y[0] = (afs_uint32) (x / (billion * billion));
8992 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8993 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8996 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8998 snprintf(buf, len, "%d%09d", y[1], y[2]);
9000 snprintf(buf, len, "%d", y[2]);
9006 struct VLRUExtStatsEntry {
9010 struct VLRUExtStats {
9016 } queue_info[VLRU_QUEUE_INVALID];
9017 struct VLRUExtStatsEntry * vec;
9021 * add a 256-entry fudge factor onto the vector in case state changes
9022 * out from under us.
9024 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
9027 * collect extended statistics for the VLRU subsystem.
9029 * @param[out] stats pointer to stats structure to be populated
9030 * @param[in] nvols number of volumes currently known to exist
9032 * @pre VOL_LOCK held
9034 * @post stats->vec allocated and populated
9036 * @return operation status
9041 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
9043 afs_uint32 cur, idx, len;
9044 struct rx_queue * qp, * nqp;
9046 struct VLRUExtStatsEntry * vec;
9048 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
9049 vec = stats->vec = calloc(len,
9050 sizeof(struct VLRUExtStatsEntry));
9056 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9057 VLRU_Wait_r(&volume_LRU.q[idx]);
9058 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
9061 stats->queue_info[idx].start = cur;
9063 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
9065 /* out of space in vec */
9068 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
9069 vec[cur].volid = vp->hashid;
9073 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9076 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9084 #define ENUMTOSTRING(en) #en
9085 #define ENUMCASE(en) \
9086 case en: return ENUMTOSTRING(en)
9089 vlru_idx_to_string(int idx)
9092 ENUMCASE(VLRU_QUEUE_NEW);
9093 ENUMCASE(VLRU_QUEUE_MID);
9094 ENUMCASE(VLRU_QUEUE_OLD);
9095 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9096 ENUMCASE(VLRU_QUEUE_HELD);
9097 ENUMCASE(VLRU_QUEUE_INVALID);
9099 return "**UNKNOWN**";
9104 VPrintExtendedCacheStats_r(int flags)
9107 afs_uint32 vol_sum = 0;
9114 struct stats looks, gets, reorders, len;
9115 struct stats ch_looks, ch_gets, ch_reorders;
9117 VolumeHashChainHead *head;
9119 struct VLRUExtStats vlru_stats;
9121 /* zero out stats */
9122 memset(&looks, 0, sizeof(struct stats));
9123 memset(&gets, 0, sizeof(struct stats));
9124 memset(&reorders, 0, sizeof(struct stats));
9125 memset(&len, 0, sizeof(struct stats));
9126 memset(&ch_looks, 0, sizeof(struct stats));
9127 memset(&ch_gets, 0, sizeof(struct stats));
9128 memset(&ch_reorders, 0, sizeof(struct stats));
9130 for (i = 0; i < VolumeHashTable.Size; i++) {
9131 head = &VolumeHashTable.Table[i];
9134 VHashBeginExclusive_r(head);
9137 ch_looks.sum = UInt64ToDouble(&head->looks);
9138 ch_gets.sum = UInt64ToDouble(&head->gets);
9139 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9141 /* update global statistics */
9143 looks.sum += ch_looks.sum;
9144 gets.sum += ch_gets.sum;
9145 reorders.sum += ch_reorders.sum;
9146 len.sum += (double)head->len;
9147 vol_sum += head->len;
9150 len.min = (double) head->len;
9151 len.max = (double) head->len;
9152 looks.min = ch_looks.sum;
9153 looks.max = ch_looks.sum;
9154 gets.min = ch_gets.sum;
9155 gets.max = ch_gets.sum;
9156 reorders.min = ch_reorders.sum;
9157 reorders.max = ch_reorders.sum;
9159 if (((double)head->len) < len.min)
9160 len.min = (double) head->len;
9161 if (((double)head->len) > len.max)
9162 len.max = (double) head->len;
9163 if (ch_looks.sum < looks.min)
9164 looks.min = ch_looks.sum;
9165 else if (ch_looks.sum > looks.max)
9166 looks.max = ch_looks.sum;
9167 if (ch_gets.sum < gets.min)
9168 gets.min = ch_gets.sum;
9169 else if (ch_gets.sum > gets.max)
9170 gets.max = ch_gets.sum;
9171 if (ch_reorders.sum < reorders.min)
9172 reorders.min = ch_reorders.sum;
9173 else if (ch_reorders.sum > reorders.max)
9174 reorders.max = ch_reorders.sum;
9178 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9179 /* compute detailed per-chain stats */
9180 struct stats hdr_loads, hdr_gets;
9181 double v_looks, v_loads, v_gets;
9183 /* initialize stats with data from first element in chain */
9184 vp = queue_First(head, Volume);
9185 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9186 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9187 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9188 ch_gets.min = ch_gets.max = v_looks;
9189 hdr_loads.min = hdr_loads.max = v_loads;
9190 hdr_gets.min = hdr_gets.max = v_gets;
9191 hdr_loads.sum = hdr_gets.sum = 0;
9193 vp = queue_Next(vp, Volume);
9195 /* pull in stats from remaining elements in chain */
9196 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9197 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9198 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9199 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9201 hdr_loads.sum += v_loads;
9202 hdr_gets.sum += v_gets;
9204 if (v_looks < ch_gets.min)
9205 ch_gets.min = v_looks;
9206 else if (v_looks > ch_gets.max)
9207 ch_gets.max = v_looks;
9209 if (v_loads < hdr_loads.min)
9210 hdr_loads.min = v_loads;
9211 else if (v_loads > hdr_loads.max)
9212 hdr_loads.max = v_loads;
9214 if (v_gets < hdr_gets.min)
9215 hdr_gets.min = v_gets;
9216 else if (v_gets > hdr_gets.max)
9217 hdr_gets.max = v_gets;
9220 /* compute per-chain averages */
9221 ch_gets.avg = ch_gets.sum / ((double)head->len);
9222 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9223 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9225 /* dump per-chain stats */
9226 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9228 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9229 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9230 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9231 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9232 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9233 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9234 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9235 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9236 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9237 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9238 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9239 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9240 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9241 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9242 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9243 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9244 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9245 } else if (flags & VOL_STATS_PER_CHAIN) {
9246 /* dump simple per-chain stats */
9247 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9249 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9250 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9251 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9255 VHashEndExclusive_r(head);
9260 /* compute global averages */
9261 len.avg = len.sum / ((double)VolumeHashTable.Size);
9262 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9263 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9264 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9266 /* dump global stats */
9267 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9268 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9269 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9270 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9271 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9272 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9273 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9274 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9275 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9276 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9277 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9278 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9279 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9280 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9281 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9282 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9283 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9284 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9285 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9286 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9287 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9289 /* print extended disk related statistics */
9291 struct DiskPartition64 * diskP;
9292 afs_uint32 vol_count[VOLMAXPARTS+1];
9293 byte part_exists[VOLMAXPARTS+1];
9297 memset(vol_count, 0, sizeof(vol_count));
9298 memset(part_exists, 0, sizeof(part_exists));
9302 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9304 vol_count[id] = diskP->vol_list.len;
9305 part_exists[id] = 1;
9309 for (i = 0; i <= VOLMAXPARTS; i++) {
9310 if (part_exists[i]) {
9311 /* XXX while this is currently safe, it is a violation
9312 * of the VGetPartitionById_r interface contract. */
9313 diskP = VGetPartitionById_r(i, 0);
9315 Log("Partition %s has %d online volumes\n",
9316 VPartitionPath(diskP), diskP->vol_list.len);
9323 /* print extended VLRU statistics */
9324 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9325 afs_uint32 idx, cur, lpos;
9330 Log("VLRU State Dump:\n\n");
9332 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9333 Log("\t%s:\n", vlru_idx_to_string(idx));
9336 for (cur = vlru_stats.queue_info[idx].start;
9337 cur < vlru_stats.queue_info[idx].len;
9339 line[lpos++] = vlru_stats.vec[cur].volid;
9341 Log("\t\t%u, %u, %u, %u, %u,\n",
9342 line[0], line[1], line[2], line[3], line[4]);
9351 Log("\t\t%u, %u, %u, %u, %u\n",
9352 line[0], line[1], line[2], line[3], line[4]);
9357 free(vlru_stats.vec);
9364 VPrintExtendedCacheStats(int flags)
9367 VPrintExtendedCacheStats_r(flags);
9370 #endif /* AFS_DEMAND_ATTACH_FS */
9373 VCanScheduleSalvage(void)
9375 return vol_opts.canScheduleSalvage;
9381 return vol_opts.canUseFSSYNC;
9385 VCanUseSALVSYNC(void)
9387 return vol_opts.canUseSALVSYNC;
9391 VCanUnsafeAttach(void)
9393 return vol_opts.unsafe_attach;