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 ProgramType programType; /* The type of program using the package */
180 static VolumePackageOptions vol_opts;
182 /* extended volume package statistics */
185 #ifdef VOL_LOCK_DEBUG
186 pthread_t vol_glock_holder = 0;
190 /* this parameter needs to be tunable at runtime.
191 * 128 was really inadequate for largish servers -- at 16384 volumes this
192 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
193 * talk about bad spatial locality...
195 * an AVL or splay tree might work a lot better, but we'll just increase
196 * the default hash table size for now
198 #define DEFAULT_VOLUME_HASH_BITS 10
199 #define DEFAULT_VOLUME_HASH_SIZE opr_jhash_size(DEFAULT_VOLUME_HASH_BITS)
200 #define DEFAULT_VOLUME_HASH_MASK opr_jhash_mask(DEFAULT_VOLUME_HASH_BITS)
201 #define VOLUME_HASH(volumeId) \
202 (opr_jhash_int(volumeId, 0) & VolumeHashTable.Mask)
205 * turn volume hash chains into partially ordered lists.
206 * when the threshold is exceeded between two adjacent elements,
207 * perform a chain rebalancing operation.
209 * keep the threshold high in order to keep cache line invalidates
210 * low "enough" on SMPs
212 #define VOLUME_HASH_REORDER_THRESHOLD 200
215 * when possible, don't just reorder single elements, but reorder
216 * entire chains of elements at once. a chain of elements that
217 * exceed the element previous to the pivot by at least CHAIN_THRESH
218 * accesses are moved in front of the chain whose elements have at
219 * least CHAIN_THRESH less accesses than the pivot element
221 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
224 * The per volume uniquifier is bumped by 200 and and written to disk
225 * every 200 file creates.
227 #define VOLUME_UPDATE_UNIQUIFIER_BUMP 200
229 #include "rx/rx_queue.h"
232 VolumeHashTable_t VolumeHashTable = {
233 DEFAULT_VOLUME_HASH_SIZE,
234 DEFAULT_VOLUME_HASH_MASK,
239 static void VInitVolumeHash(void);
242 #ifdef AFS_PTHREAD_ENV
244 * disk partition queue element
246 typedef struct diskpartition_queue_t {
247 struct rx_queue queue; /**< queue header */
248 struct DiskPartition64 *diskP; /**< disk partition table entry */
249 } diskpartition_queue_t;
251 #ifndef AFS_DEMAND_ATTACH_FS
253 typedef struct vinitvolumepackage_thread_t {
254 struct rx_queue queue;
255 pthread_cond_t thread_done_cv;
256 int n_threads_complete;
257 } vinitvolumepackage_thread_t;
258 static void * VInitVolumePackageThread(void * args);
260 #else /* !AFS_DEMAND_ATTTACH_FS */
261 #define VINIT_BATCH_MAX_SIZE 512
264 * disk partition work queue
266 struct partition_queue {
267 struct rx_queue head; /**< diskpartition_queue_t queue */
268 pthread_mutex_t mutex;
273 * volumes parameters for preattach
275 struct volume_init_batch {
276 struct rx_queue queue; /**< queue header */
277 int thread; /**< posting worker thread */
278 int last; /**< indicates thread is done */
279 int size; /**< number of volume ids in batch */
280 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
284 * volume parameters work queue
286 struct volume_init_queue {
287 struct rx_queue head; /**< volume_init_batch queue */
288 pthread_mutex_t mutex;
293 * volume init worker thread parameters
295 struct vinitvolumepackage_thread_param {
296 int nthreads; /**< total number of worker threads */
297 int thread; /**< thread number for this worker thread */
298 struct partition_queue *pq; /**< queue partitions to scan */
299 struct volume_init_queue *vq; /**< queue of volume to preattach */
302 static void *VInitVolumePackageThread(void *args);
303 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
304 static VolumeId VInitNextVolumeId(DIR *dirp);
305 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
307 #endif /* !AFS_DEMAND_ATTACH_FS */
308 #endif /* AFS_PTHREAD_ENV */
310 #ifndef AFS_DEMAND_ATTACH_FS
311 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
312 int * nAttached, int * nUnattached);
313 #endif /* AFS_DEMAND_ATTACH_FS */
316 #ifdef AFS_DEMAND_ATTACH_FS
317 /* demand attach fileserver extensions */
320 * in the future we will support serialization of VLRU state into the fs_state
323 * these structures are the beginning of that effort
325 struct VLRU_DiskHeader {
326 struct versionStamp stamp; /* magic and structure version number */
327 afs_uint32 mtime; /* time of dump to disk */
328 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
331 struct VLRU_DiskEntry {
332 VolumeId vid; /* volume ID */
333 afs_uint32 idx; /* generation */
334 afs_uint32 last_get; /* timestamp of last get */
337 struct VLRU_StartupQueue {
338 struct VLRU_DiskEntry * entry;
343 typedef struct vshutdown_thread_t {
345 pthread_mutex_t lock;
347 pthread_cond_t master_cv;
349 int n_threads_complete;
351 int schedule_version;
354 byte n_parts_done_pass;
355 byte part_thread_target[VOLMAXPARTS+1];
356 byte part_done_pass[VOLMAXPARTS+1];
357 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
358 int stats[4][VOLMAXPARTS+1];
359 } vshutdown_thread_t;
360 static void * VShutdownThread(void * args);
363 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
364 static int VCheckFree(Volume * vp);
367 static void AddVolumeToVByPList_r(Volume * vp);
368 static void DeleteVolumeFromVByPList_r(Volume * vp);
369 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
370 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
371 static void VVByPListWait_r(struct DiskPartition64 * dp);
373 /* online salvager */
375 VCHECK_SALVAGE_OK = 0, /**< no pending salvage */
376 VCHECK_SALVAGE_SCHEDULED = 1, /**< salvage has been scheduled */
377 VCHECK_SALVAGE_ASYNC = 2, /**< salvage being scheduled */
378 VCHECK_SALVAGE_DENIED = 3, /**< salvage not scheduled; denied */
379 VCHECK_SALVAGE_FAIL = 4 /**< salvage not scheduled; failed */
381 static int VCheckSalvage(Volume * vp);
382 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
383 static int VScheduleSalvage_r(Volume * vp);
386 /* Volume hash table */
387 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
388 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
389 static void VHashEndExclusive_r(VolumeHashChainHead * head);
390 static void VHashWait_r(VolumeHashChainHead * head);
393 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
394 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
395 struct rx_queue ** idx);
396 static void ShutdownController(vshutdown_thread_t * params);
397 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
400 static void VLRU_ComputeConstants(void);
401 static void VInitVLRU(void);
402 static void VLRU_Init_Node_r(Volume * vp);
403 static void VLRU_Add_r(Volume * vp);
404 static void VLRU_Delete_r(Volume * vp);
405 static void VLRU_UpdateAccess_r(Volume * vp);
406 static void * VLRU_ScannerThread(void * args);
407 static void VLRU_Scan_r(int idx);
408 static void VLRU_Promote_r(int idx);
409 static void VLRU_Demote_r(int idx);
410 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
413 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
414 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
415 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
418 pthread_key_t VThread_key;
419 VThreadOptions_t VThread_defaults = {
420 0 /**< allow salvsync */
422 #endif /* AFS_DEMAND_ATTACH_FS */
425 struct Lock vol_listLock; /* Lock obtained when listing volumes:
426 * prevents a volume from being missed
427 * if the volume is attached during a
431 /* Common message used when the volume goes off line */
432 char *VSalvageMessage =
433 "Files in this volume are currently unavailable; call operations";
435 int VInit; /* 0 - uninitialized,
436 * 1 - initialized but not all volumes have been attached,
437 * 2 - initialized and all volumes have been attached,
438 * 3 - initialized, all volumes have been attached, and
439 * VConnectFS() has completed. */
441 static int vinit_attach_abort = 0;
443 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
444 * used to stamp volume headers and in-core
445 * vnodes. When the volume goes on-line the
446 * vnode will be invalidated
447 * access only with VOL_LOCK held */
452 /***************************************************/
453 /* Startup routines */
454 /***************************************************/
456 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
457 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
458 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
462 * assign default values to a VolumePackageOptions struct.
464 * Always call this on a VolumePackageOptions struct first, then set any
465 * specific options you want, then call VInitVolumePackage2.
467 * @param[in] pt caller's program type
468 * @param[out] opts volume package options
471 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
473 opts->nLargeVnodes = opts->nSmallVnodes = 5;
476 opts->canScheduleSalvage = 0;
477 opts->canUseFSSYNC = 0;
478 opts->canUseSALVSYNC = 0;
480 opts->interrupt_rxcall = NULL;
481 opts->offline_timeout = -1;
482 opts->offline_shutdown_timeout = -1;
483 opts->usage_threshold = 128;
484 opts->usage_rate_limit = 5;
487 opts->unsafe_attach = 1;
488 #else /* !FAST_RESTART */
489 opts->unsafe_attach = 0;
490 #endif /* !FAST_RESTART */
494 opts->canScheduleSalvage = 1;
495 opts->canUseSALVSYNC = 1;
499 opts->canUseFSSYNC = 1;
503 opts->nLargeVnodes = 0;
504 opts->nSmallVnodes = 0;
506 opts->canScheduleSalvage = 1;
507 opts->canUseFSSYNC = 1;
517 * Set VInit to a certain value, and signal waiters.
519 * @param[in] value the value to set VInit to
524 VSetVInit_r(int value)
527 opr_cv_broadcast(&vol_vinit_cond);
531 VLogOfflineTimeout(const char *type, afs_int32 timeout)
537 Log("VInitVolumePackage: Interrupting clients accessing %s "
538 "immediately\n", type);
540 Log("VInitVolumePackage: Interrupting clients accessing %s "
541 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
546 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
548 int errors = 0; /* Number of errors while finding vice partitions. */
553 #ifndef AFS_PTHREAD_ENV
554 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
555 Log("VInitVolumePackage: offline_timeout and/or "
556 "offline_shutdown_timeout was specified, but the volume package "
557 "does not support these for LWP builds\n");
561 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
562 VLogOfflineTimeout("volumes going offline during shutdown",
563 opts->offline_shutdown_timeout);
565 memset(&VStats, 0, sizeof(VStats));
566 VStats.hdr_cache_size = 200;
568 VInitPartitionPackage();
570 #ifdef AFS_DEMAND_ATTACH_FS
571 if (programType == fileServer) {
574 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
576 opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
579 opr_mutex_init(&vol_glock_mutex);
580 opr_mutex_init(&vol_trans_mutex);
581 opr_cv_init(&vol_put_volume_cond);
582 opr_cv_init(&vol_sleep_cond);
583 opr_cv_init(&vol_init_attach_cond);
584 opr_cv_init(&vol_vinit_cond);
585 #ifndef AFS_PTHREAD_ENV
587 #endif /* AFS_PTHREAD_ENV */
588 Lock_Init(&vol_listLock);
590 srandom(time(0)); /* For VGetVolumeInfo */
592 #ifdef AFS_DEMAND_ATTACH_FS
593 opr_mutex_init(&vol_salvsync_mutex);
594 #endif /* AFS_DEMAND_ATTACH_FS */
596 /* Ok, we have done enough initialization that fileserver can
597 * start accepting calls, even though the volumes may not be
598 * available just yet.
602 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
603 if (programType == salvageServer) {
606 #endif /* AFS_DEMAND_ATTACH_FS */
607 #ifdef FSSYNC_BUILD_SERVER
608 if (programType == fileServer) {
612 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
613 if (VCanUseSALVSYNC()) {
614 /* establish a connection to the salvager at this point */
615 opr_Verify(VConnectSALV() != 0);
617 #endif /* AFS_DEMAND_ATTACH_FS */
619 if (opts->volcache > VStats.hdr_cache_size)
620 VStats.hdr_cache_size = opts->volcache;
621 VInitVolumeHeaderCache(VStats.hdr_cache_size);
623 VInitVnodes(vLarge, opts->nLargeVnodes);
624 VInitVnodes(vSmall, opts->nSmallVnodes);
627 errors = VAttachPartitions();
631 if (programType != fileServer) {
632 errors = VInitAttachVolumes(programType);
638 #ifdef FSSYNC_BUILD_CLIENT
639 if (VCanUseFSSYNC()) {
641 #ifdef AFS_DEMAND_ATTACH_FS
642 if (programType == salvageServer) {
643 Log("Unable to connect to file server; aborted\n");
646 #endif /* AFS_DEMAND_ATTACH_FS */
647 Log("Unable to connect to file server; will retry at need\n");
650 #endif /* FSSYNC_BUILD_CLIENT */
655 #if !defined(AFS_PTHREAD_ENV)
657 * Attach volumes in vice partitions
659 * @param[in] pt calling program type
662 * @note This is the original, non-threaded version of attach parititions.
664 * @post VInit state is 2
667 VInitAttachVolumes(ProgramType pt)
669 opr_Assert(VInit==1);
670 if (pt == fileServer) {
671 struct DiskPartition64 *diskP;
672 /* Attach all the volumes in this partition */
673 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
674 int nAttached = 0, nUnattached = 0;
675 opr_Verify(VAttachVolumesByPartition(diskP,
676 &nAttached, &nUnattached)
681 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
682 LWP_NoYieldSignal(VInitAttachVolumes);
686 #endif /* !AFS_PTHREAD_ENV */
688 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
690 * Attach volumes in vice partitions
692 * @param[in] pt calling program type
695 * @note Threaded version of attach parititions.
697 * @post VInit state is 2
700 VInitAttachVolumes(ProgramType pt)
702 opr_Assert(VInit==1);
703 if (pt == fileServer) {
704 struct DiskPartition64 *diskP;
705 struct vinitvolumepackage_thread_t params;
706 struct diskpartition_queue_t * dpq;
707 int i, threads, parts;
709 pthread_attr_t attrs;
711 opr_cv_init(¶ms.thread_done_cv);
713 params.n_threads_complete = 0;
715 /* create partition work queue */
716 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
717 dpq = malloc(sizeof(struct diskpartition_queue_t));
718 opr_Assert(dpq != NULL);
720 queue_Append(¶ms,dpq);
723 threads = min(parts, vol_attach_threads);
726 /* spawn off a bunch of initialization threads */
727 opr_Verify(pthread_attr_init(&attrs) == 0);
728 opr_Verify(pthread_attr_setdetachstate(&attrs,
729 PTHREAD_CREATE_DETACHED)
732 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
733 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
737 for (i=0; i < threads; i++) {
740 opr_Verify(pthread_create(&tid, &attrs,
741 &VInitVolumePackageThread,
743 AFS_SIGSET_RESTORE();
746 while(params.n_threads_complete < threads) {
747 VOL_CV_WAIT(¶ms.thread_done_cv);
751 opr_Verify(pthread_attr_destroy(&attrs) == 0);
753 /* if we're only going to run one init thread, don't bother creating
755 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
756 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
759 VInitVolumePackageThread(¶ms);
762 opr_cv_destroy(¶ms.thread_done_cv);
765 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
766 opr_cv_broadcast(&vol_init_attach_cond);
772 VInitVolumePackageThread(void * args) {
774 struct DiskPartition64 *diskP;
775 struct vinitvolumepackage_thread_t * params;
776 struct diskpartition_queue_t * dpq;
778 params = (vinitvolumepackage_thread_t *) args;
782 /* Attach all the volumes in this partition */
783 while (queue_IsNotEmpty(params)) {
784 int nAttached = 0, nUnattached = 0;
786 if (vinit_attach_abort) {
787 Log("Aborting initialization\n");
791 dpq = queue_First(params,diskpartition_queue_t);
797 opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
804 params->n_threads_complete++;
805 opr_cv_signal(¶ms->thread_done_cv);
809 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
811 #if defined(AFS_DEMAND_ATTACH_FS)
813 * Attach volumes in vice partitions
815 * @param[in] pt calling program type
818 * @note Threaded version of attach partitions.
820 * @post VInit state is 2
823 VInitAttachVolumes(ProgramType pt)
825 opr_Assert(VInit==1);
826 if (pt == fileServer) {
828 struct DiskPartition64 *diskP;
829 struct partition_queue pq;
830 struct volume_init_queue vq;
832 int i, threads, parts;
834 pthread_attr_t attrs;
836 /* create partition work queue */
839 opr_mutex_init(&pq.mutex);
840 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
841 struct diskpartition_queue_t *dp;
842 dp = malloc(sizeof(struct diskpartition_queue_t));
843 opr_Assert(dp != NULL);
845 queue_Append(&pq, dp);
848 /* number of worker threads; at least one, not to exceed the number of partitions */
849 threads = min(parts, vol_attach_threads);
851 /* create volume work queue */
854 opr_mutex_init(&vq.mutex);
856 opr_Verify(pthread_attr_init(&attrs) == 0);
857 opr_Verify(pthread_attr_setdetachstate(&attrs,
858 PTHREAD_CREATE_DETACHED) == 0);
860 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
861 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
864 /* create threads to scan disk partitions. */
865 for (i=0; i < threads; i++) {
866 struct vinitvolumepackage_thread_param *params;
869 params = malloc(sizeof(struct vinitvolumepackage_thread_param));
873 params->nthreads = threads;
874 params->thread = i+1;
877 opr_Verify(pthread_create(&tid, &attrs,
878 &VInitVolumePackageThread,
879 (void*)params) == 0);
880 AFS_SIGSET_RESTORE();
883 VInitPreAttachVolumes(threads, &vq);
885 opr_Verify(pthread_attr_destroy(&attrs) == 0);
886 opr_cv_destroy(&pq.cv);
887 opr_mutex_destroy(&pq.mutex);
888 opr_cv_destroy(&vq.cv);
889 opr_mutex_destroy(&vq.mutex);
893 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
894 opr_cv_broadcast(&vol_init_attach_cond);
901 * Volume package initialization worker thread. Scan partitions for volume
902 * header files. Gather batches of volume ids and dispatch them to
903 * the main thread to be preattached. The volume preattachement is done
904 * in the main thread to avoid global volume lock contention.
907 VInitVolumePackageThread(void *args)
909 struct vinitvolumepackage_thread_param *params;
910 struct DiskPartition64 *partition;
911 struct partition_queue *pq;
912 struct volume_init_queue *vq;
913 struct volume_init_batch *vb;
916 params = (struct vinitvolumepackage_thread_param *)args;
922 vb = malloc(sizeof(struct volume_init_batch));
924 vb->thread = params->thread;
928 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
929 while((partition = VInitNextPartition(pq))) {
933 Log("Partition %s: pre-attaching volumes\n", partition->name);
934 dirp = opendir(VPartitionPath(partition));
936 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
939 while ((vid = VInitNextVolumeId(dirp))) {
940 Volume *vp = calloc(1, sizeof(Volume));
942 vp->device = partition->device;
943 vp->partition = partition;
945 queue_Init(&vp->vnode_list);
946 queue_Init(&vp->rx_call_list);
947 opr_cv_init(&V_attachCV(vp));
949 vb->batch[vb->size++] = vp;
950 if (vb->size == VINIT_BATCH_MAX_SIZE) {
951 opr_mutex_enter(&vq->mutex);
952 queue_Append(vq, vb);
953 opr_cv_broadcast(&vq->cv);
954 opr_mutex_exit(&vq->mutex);
956 vb = malloc(sizeof(struct volume_init_batch));
958 vb->thread = params->thread;
967 opr_mutex_enter(&vq->mutex);
968 queue_Append(vq, vb);
969 opr_cv_broadcast(&vq->cv);
970 opr_mutex_exit(&vq->mutex);
972 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
978 * Read next element from the pre-populated partition list.
980 static struct DiskPartition64*
981 VInitNextPartition(struct partition_queue *pq)
983 struct DiskPartition64 *partition;
984 struct diskpartition_queue_t *dp; /* queue element */
986 if (vinit_attach_abort) {
987 Log("Aborting volume preattach thread.\n");
991 /* get next partition to scan */
992 opr_mutex_enter(&pq->mutex);
993 if (queue_IsEmpty(pq)) {
994 opr_mutex_exit(&pq->mutex);
997 dp = queue_First(pq, diskpartition_queue_t);
999 opr_mutex_exit(&pq->mutex);
1002 opr_Assert(dp->diskP);
1004 partition = dp->diskP;
1010 * Find next volume id on the partition.
1013 VInitNextVolumeId(DIR *dirp)
1019 while((d = readdir(dirp))) {
1020 if (vinit_attach_abort) {
1021 Log("Aborting volume preattach thread.\n");
1024 ext = strrchr(d->d_name, '.');
1025 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1026 vid = VolumeNumber(d->d_name);
1030 Log("Warning: bogus volume header file: %s\n", d->d_name);
1037 * Preattach volumes in batches to avoid lock contention.
1040 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1042 struct volume_init_batch *vb;
1046 /* dequeue next volume */
1047 opr_mutex_enter(&vq->mutex);
1048 if (queue_IsEmpty(vq)) {
1049 opr_cv_wait(&vq->cv, &vq->mutex);
1051 vb = queue_First(vq, volume_init_batch);
1053 opr_mutex_exit(&vq->mutex);
1057 for (i = 0; i<vb->size; i++) {
1063 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1065 Log("Error looking up volume, code=%d\n", ec);
1068 Log("Warning: Duplicate volume id %" AFS_VOLID_FMT " detected.\n", afs_printable_VolumeId_lu(vp->hashid));
1071 /* put pre-attached volume onto the hash table
1072 * and bring it up to the pre-attached state */
1073 AddVolumeToHashTable(vp, vp->hashid);
1074 AddVolumeToVByPList_r(vp);
1075 VLRU_Init_Node_r(vp);
1076 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1089 #endif /* AFS_DEMAND_ATTACH_FS */
1091 #if !defined(AFS_DEMAND_ATTACH_FS)
1093 * attach all volumes on a given disk partition
1096 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1102 Log("Partition %s: attaching volumes\n", diskP->name);
1103 dirp = opendir(VPartitionPath(diskP));
1105 Log("opendir on Partition %s failed!\n", diskP->name);
1109 while ((dp = readdir(dirp))) {
1111 p = strrchr(dp->d_name, '.');
1113 if (vinit_attach_abort) {
1114 Log("Partition %s: abort attach volumes\n", diskP->name);
1118 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1121 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1123 (*(vp ? nAttached : nUnattached))++;
1124 if (error == VOFFLINE)
1125 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1126 else if (GetLogLevel() >= 5) {
1127 Log("Partition %s: attached volume %d (%s)\n",
1128 diskP->name, VolumeNumber(dp->d_name),
1137 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1142 #endif /* !AFS_DEMAND_ATTACH_FS */
1144 /***************************************************/
1145 /* Shutdown routines */
1146 /***************************************************/
1150 * highly multithreaded volume package shutdown
1152 * with the demand attach fileserver extensions,
1153 * VShutdown has been modified to be multithreaded.
1154 * In order to achieve optimal use of many threads,
1155 * the shutdown code involves one control thread and
1156 * n shutdown worker threads. The control thread
1157 * periodically examines the number of volumes available
1158 * for shutdown on each partition, and produces a worker
1159 * thread allocation schedule. The idea is to eliminate
1160 * redundant scheduling computation on the workers by
1161 * having a single master scheduler.
1163 * The scheduler's objectives are:
1165 * each partition with volumes remaining gets allocated
1166 * at least 1 thread (assuming sufficient threads)
1168 * threads are allocated proportional to the number of
1169 * volumes remaining to be offlined. This ensures that
1170 * the OS I/O scheduler has many requests to elevator
1171 * seek on partitions that will (presumably) take the
1172 * longest amount of time (from now) to finish shutdown
1173 * (3) keep threads busy
1174 * when there are extra threads, they are assigned to
1175 * partitions using a simple round-robin algorithm
1177 * In the future, we may wish to add the ability to adapt
1178 * to the relative performance patterns of each disk
1183 * multi-step shutdown process
1185 * demand attach shutdown is a four-step process. Each
1186 * shutdown "pass" shuts down increasingly more difficult
1187 * volumes. The main purpose is to achieve better cache
1188 * utilization during shutdown.
1191 * shutdown volumes in the unattached, pre-attached
1194 * shutdown attached volumes with cached volume headers
1196 * shutdown all volumes in non-exclusive states
1198 * shutdown all remaining volumes
1201 #ifdef AFS_DEMAND_ATTACH_FS
1207 struct DiskPartition64 * diskP;
1208 struct diskpartition_queue_t * dpq;
1209 vshutdown_thread_t params;
1211 pthread_attr_t attrs;
1213 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1216 Log("VShutdown: aborting attach volumes\n");
1217 vinit_attach_abort = 1;
1218 VOL_CV_WAIT(&vol_init_attach_cond);
1221 for (params.n_parts=0, diskP = DiskPartitionList;
1222 diskP; diskP = diskP->next, params.n_parts++);
1224 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1225 params.n_parts, params.n_parts > 1 ? "s" : "");
1227 vol_shutting_down = 1;
1229 if (vol_attach_threads > 1) {
1230 /* prepare for parallel shutdown */
1231 params.n_threads = vol_attach_threads;
1232 opr_mutex_init(¶ms.lock);
1233 opr_cv_init(¶ms.cv);
1234 opr_cv_init(¶ms.master_cv);
1235 opr_Verify(pthread_attr_init(&attrs) == 0);
1236 opr_Verify(pthread_attr_setdetachstate(&attrs,
1237 PTHREAD_CREATE_DETACHED) == 0);
1238 queue_Init(¶ms);
1240 /* setup the basic partition information structures for
1241 * parallel shutdown */
1242 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1244 struct rx_queue * qp, * nqp;
1248 VVByPListWait_r(diskP);
1249 VVByPListBeginExclusive_r(diskP);
1252 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1253 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1257 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1258 VPartitionPath(diskP), count);
1261 /* build up the pass 0 shutdown work queue */
1262 dpq = malloc(sizeof(struct diskpartition_queue_t));
1263 opr_Assert(dpq != NULL);
1265 queue_Prepend(¶ms, dpq);
1267 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1270 Log("VShutdown: beginning parallel fileserver shutdown\n");
1271 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1272 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1274 /* do pass 0 shutdown */
1275 opr_mutex_enter(¶ms.lock);
1276 for (i=0; i < params.n_threads; i++) {
1277 opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1281 /* wait for all the pass 0 shutdowns to complete */
1282 while (params.n_threads_complete < params.n_threads) {
1283 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1285 params.n_threads_complete = 0;
1287 opr_cv_broadcast(¶ms.cv);
1288 opr_mutex_exit(¶ms.lock);
1290 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1291 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1293 /* run the parallel shutdown scheduler. it will drop the glock internally */
1294 ShutdownController(¶ms);
1296 /* wait for all the workers to finish pass 3 and terminate */
1297 while (params.pass < 4) {
1298 VOL_CV_WAIT(¶ms.cv);
1301 opr_Verify(pthread_attr_destroy(&attrs) == 0);
1302 opr_cv_destroy(¶ms.cv);
1303 opr_cv_destroy(¶ms.master_cv);
1304 opr_mutex_destroy(¶ms.lock);
1306 /* drop the VByPList exclusive reservations */
1307 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1308 VVByPListEndExclusive_r(diskP);
1309 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1310 VPartitionPath(diskP),
1311 params.stats[0][diskP->index],
1312 params.stats[1][diskP->index],
1313 params.stats[2][diskP->index],
1314 params.stats[3][diskP->index]);
1317 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1319 /* if we're only going to run one shutdown thread, don't bother creating
1321 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1323 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1324 VShutdownByPartition_r(diskP);
1328 Log("VShutdown: complete.\n");
1331 #else /* AFS_DEMAND_ATTACH_FS */
1341 Log("VShutdown: aborting attach volumes\n");
1342 vinit_attach_abort = 1;
1343 #ifdef AFS_PTHREAD_ENV
1344 VOL_CV_WAIT(&vol_init_attach_cond);
1346 LWP_WaitProcess(VInitAttachVolumes);
1347 #endif /* AFS_PTHREAD_ENV */
1350 Log("VShutdown: shutting down on-line volumes...\n");
1351 vol_shutting_down = 1;
1352 for (i = 0; i < VolumeHashTable.Size; i++) {
1353 /* try to hold first volume in the hash table */
1354 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1357 if (GetLogLevel() >= 5)
1358 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1359 afs_printable_VolumeId_lu(vp->hashid));
1361 /* next, take the volume offline (drops reference count) */
1362 VOffline_r(vp, "File server was shut down");
1366 Log("VShutdown: complete.\n");
1368 #endif /* AFS_DEMAND_ATTACH_FS */
1374 opr_Assert(VInit>0);
1381 * stop new activity (e.g. SALVSYNC) from occurring
1383 * Use this to make the volume package less busy; for example, during
1384 * shutdown. This doesn't actually shutdown/detach anything in the
1385 * volume package, but prevents certain processes from ocurring. For
1386 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1387 * could also use this to prevent new volume attachment, or prevent
1388 * other programs from checking out volumes, etc.
1393 #ifdef AFS_DEMAND_ATTACH_FS
1394 /* make sure we don't try to contact the salvageserver, since it may
1395 * not be around anymore */
1396 vol_disallow_salvsync = 1;
1400 #ifdef AFS_DEMAND_ATTACH_FS
1403 * shutdown control thread
1406 ShutdownController(vshutdown_thread_t * params)
1409 struct DiskPartition64 * diskP;
1411 vshutdown_thread_t shadow;
1413 ShutdownCreateSchedule(params);
1415 while ((params->pass < 4) &&
1416 (params->n_threads_complete < params->n_threads)) {
1417 /* recompute schedule once per second */
1419 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1423 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1424 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1425 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1426 shadow.n_threads_complete, shadow.n_parts_done_pass);
1427 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1429 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1431 diskP->vol_list.len,
1432 shadow.part_thread_target[id],
1433 shadow.part_done_pass[id],
1434 shadow.part_pass_head[id]);
1440 ShutdownCreateSchedule(params);
1444 /* create the shutdown thread work schedule.
1445 * this scheduler tries to implement fairness
1446 * by allocating at least 1 thread to each
1447 * partition with volumes to be shutdown,
1448 * and then it attempts to allocate remaining
1449 * threads based upon the amount of work left
1452 ShutdownCreateSchedule(vshutdown_thread_t * params)
1454 struct DiskPartition64 * diskP;
1455 int sum, thr_workload, thr_left;
1456 int part_residue[VOLMAXPARTS+1];
1459 /* compute the total number of outstanding volumes */
1461 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1462 sum += diskP->vol_list.len;
1465 params->schedule_version++;
1466 params->vol_remaining = sum;
1471 /* compute average per-thread workload */
1472 thr_workload = sum / params->n_threads;
1473 if (sum % params->n_threads)
1476 thr_left = params->n_threads;
1477 memset(&part_residue, 0, sizeof(part_residue));
1479 /* for fairness, give every partition with volumes remaining
1480 * at least one thread */
1481 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1483 if (diskP->vol_list.len) {
1484 params->part_thread_target[id] = 1;
1487 params->part_thread_target[id] = 0;
1491 if (thr_left && thr_workload) {
1492 /* compute length-weighted workloads */
1495 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1497 delta = (diskP->vol_list.len / thr_workload) -
1498 params->part_thread_target[id];
1502 if (delta < thr_left) {
1503 params->part_thread_target[id] += delta;
1506 params->part_thread_target[id] += thr_left;
1514 /* try to assign any leftover threads to partitions that
1515 * had volume lengths closer to needing thread_target+1 */
1516 int max_residue, max_id = 0;
1518 /* compute the residues */
1519 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1521 part_residue[id] = diskP->vol_list.len -
1522 (params->part_thread_target[id] * thr_workload);
1525 /* now try to allocate remaining threads to partitions with the
1526 * highest residues */
1529 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1531 if (part_residue[id] > max_residue) {
1532 max_residue = part_residue[id];
1541 params->part_thread_target[max_id]++;
1543 part_residue[max_id] = 0;
1548 /* punt and give any remaining threads equally to each partition */
1550 if (thr_left >= params->n_parts) {
1551 alloc = thr_left / params->n_parts;
1552 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1554 params->part_thread_target[id] += alloc;
1559 /* finish off the last of the threads */
1560 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1562 params->part_thread_target[id]++;
1568 /* worker thread for parallel shutdown */
1570 VShutdownThread(void * args)
1572 vshutdown_thread_t * params;
1573 int found, pass, schedule_version_save, count;
1574 struct DiskPartition64 *diskP;
1575 struct diskpartition_queue_t * dpq;
1578 params = (vshutdown_thread_t *) args;
1580 /* acquire the shutdown pass 0 lock */
1581 opr_mutex_enter(¶ms->lock);
1583 /* if there's still pass 0 work to be done,
1584 * get a work entry, and do a pass 0 shutdown */
1585 if (queue_IsNotEmpty(params)) {
1586 dpq = queue_First(params, diskpartition_queue_t);
1588 opr_mutex_exit(¶ms->lock);
1594 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1596 params->stats[0][diskP->index] = count;
1597 opr_mutex_enter(¶ms->lock);
1600 params->n_threads_complete++;
1601 if (params->n_threads_complete == params->n_threads) {
1602 /* notify control thread that all workers have completed pass 0 */
1603 opr_cv_signal(¶ms->master_cv);
1605 while (params->pass == 0) {
1606 opr_cv_wait(¶ms->cv, ¶ms->lock);
1610 opr_mutex_exit(¶ms->lock);
1613 pass = params->pass;
1614 opr_Assert(pass > 0);
1616 /* now escalate through the more complicated shutdowns */
1618 schedule_version_save = params->schedule_version;
1620 /* find a disk partition to work on */
1621 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1623 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1624 params->part_thread_target[id]--;
1631 /* hmm. for some reason the controller thread couldn't find anything for
1632 * us to do. let's see if there's anything we can do */
1633 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1635 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1638 } else if (!params->part_done_pass[id]) {
1639 params->part_done_pass[id] = 1;
1640 params->n_parts_done_pass++;
1642 Log("VShutdown: done shutting down volumes on partition %s.\n",
1643 VPartitionPath(diskP));
1649 /* do work on this partition until either the controller
1650 * creates a new schedule, or we run out of things to do
1651 * on this partition */
1654 while (!params->part_done_pass[id] &&
1655 (schedule_version_save == params->schedule_version)) {
1656 /* ShutdownVolumeWalk_r will drop the glock internally */
1657 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1658 if (!params->part_done_pass[id]) {
1659 params->part_done_pass[id] = 1;
1660 params->n_parts_done_pass++;
1662 Log("VShutdown: done shutting down volumes on partition %s.\n",
1663 VPartitionPath(diskP));
1671 params->stats[pass][id] += count;
1673 /* ok, everyone is done this pass, proceed */
1676 params->n_threads_complete++;
1677 while (params->pass == pass) {
1678 if (params->n_threads_complete == params->n_threads) {
1679 /* we are the last thread to complete, so we will
1680 * reinitialize worker pool state for the next pass */
1681 params->n_threads_complete = 0;
1682 params->n_parts_done_pass = 0;
1684 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1686 params->part_done_pass[id] = 0;
1687 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1690 /* compute a new thread schedule before releasing all the workers */
1691 ShutdownCreateSchedule(params);
1693 /* wake up all the workers */
1694 opr_cv_broadcast(¶ms->cv);
1697 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1698 pass, params->n_threads, params->n_parts);
1701 VOL_CV_WAIT(¶ms->cv);
1704 pass = params->pass;
1718 /* shut down all volumes on a given disk partition
1720 * note that this function will not allow mp-fast
1721 * shutdown of a partition */
1723 VShutdownByPartition_r(struct DiskPartition64 * dp)
1729 /* wait for other exclusive ops to finish */
1730 VVByPListWait_r(dp);
1732 /* begin exclusive access */
1733 VVByPListBeginExclusive_r(dp);
1735 /* pick the low-hanging fruit first,
1736 * then do the complicated ones last
1737 * (has the advantage of keeping
1738 * in-use volumes up until the bitter end) */
1739 for (pass = 0, total=0; pass < 4; pass++) {
1740 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1741 total += pass_stats[pass];
1744 /* end exclusive access */
1745 VVByPListEndExclusive_r(dp);
1747 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1748 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1753 /* internal shutdown functionality
1755 * for multi-pass shutdown:
1756 * 0 to only "shutdown" {pre,un}attached and error state volumes
1757 * 1 to also shutdown attached volumes w/ volume header loaded
1758 * 2 to also shutdown attached volumes w/o volume header loaded
1759 * 3 to also shutdown exclusive state volumes
1761 * caller MUST hold exclusive access on the hash chain
1762 * because we drop vol_glock_mutex internally
1764 * this function is reentrant for passes 1--3
1765 * (e.g. multiple threads can cooperate to
1766 * shutdown a partition mp-fast)
1768 * pass 0 is not scaleable because the volume state data is
1769 * synchronized by vol_glock mutex, and the locking overhead
1770 * is too high to drop the lock long enough to do linked list
1774 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1776 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1778 const char *pass_strs[4] = {"{un/pre}attached vols", "vols w/ vol header loaded", "vols w/o vol header loaded", "vols with exclusive state"};
1780 while (ShutdownVolumeWalk_r(dp, pass, &q)) {
1783 Log("VShutdownByPartition: ... shut down %d volumes on %s in pass %d (%s)\n", i, VPartitionPath(dp), pass, pass_strs[pass]);
1790 /* conditionally shutdown one volume on partition dp
1791 * returns 1 if a volume was shutdown in this pass,
1794 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1795 struct rx_queue ** idx)
1797 struct rx_queue *qp, *nqp;
1802 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1803 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1807 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1808 (V_attachState(vp) != VOL_STATE_ERROR) &&
1809 (V_attachState(vp) != VOL_STATE_DELETED) &&
1810 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1814 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1815 (vp->header == NULL)) {
1819 if (VIsExclusiveState(V_attachState(vp))) {
1824 DeleteVolumeFromVByPList_r(vp);
1825 VShutdownVolume_r(vp);
1835 * shutdown a specific volume
1837 /* caller MUST NOT hold a heavyweight ref on vp */
1839 VShutdownVolume_r(Volume * vp)
1843 VCreateReservation_r(vp);
1845 if (GetLogLevel() >= 5) {
1846 Log("VShutdownVolume_r: vid=%" AFS_VOLID_FMT ", device=%d, state=%u\n",
1847 afs_printable_VolumeId_lu(vp->hashid), vp->partition->device,
1848 (unsigned int) V_attachState(vp));
1851 /* wait for other blocking ops to finish */
1852 VWaitExclusiveState_r(vp);
1854 opr_Assert(VIsValidState(V_attachState(vp)));
1856 switch(V_attachState(vp)) {
1857 case VOL_STATE_SALVAGING:
1858 /* Leave salvaging volumes alone. Any in-progress salvages will
1859 * continue working after viced shuts down. This is intentional.
1862 case VOL_STATE_PREATTACHED:
1863 case VOL_STATE_ERROR:
1864 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1865 case VOL_STATE_UNATTACHED:
1866 case VOL_STATE_DELETED:
1868 case VOL_STATE_GOING_OFFLINE:
1869 case VOL_STATE_SHUTTING_DOWN:
1870 case VOL_STATE_ATTACHED:
1873 if (GetLogLevel() >= 5)
1874 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1875 afs_printable_VolumeId_lu(vp->hashid));
1877 /* take the volume offline (drops reference count) */
1878 VOffline_r(vp, "File server was shut down");
1885 VCancelReservation_r(vp);
1889 #endif /* AFS_DEMAND_ATTACH_FS */
1892 /***************************************************/
1893 /* Header I/O routines */
1894 /***************************************************/
1897 HeaderName(bit32 magic)
1900 case VOLUMEINFOMAGIC:
1901 return "volume info";
1902 case SMALLINDEXMAGIC:
1903 return "small index";
1904 case LARGEINDEXMAGIC:
1905 return "large index";
1906 case LINKTABLEMAGIC:
1907 return "link table";
1912 /* open a descriptor for the inode (h),
1913 * read in an on-disk structure into buffer (to) of size (size),
1914 * verify versionstamp in structure has magic (magic) and
1915 * optionally verify version (version) if (version) is nonzero
1918 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1921 struct versionStamp *vsn;
1923 afs_sfsize_t nbytes;
1928 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1936 Log("ReadHeader: Failed to open %s header file "
1937 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1938 PrintInode(stmp, h->ih_ino), errno);
1943 vsn = (struct versionStamp *)to;
1944 nbytes = FDH_PREAD(fdP, to, size, 0);
1946 Log("ReadHeader: Failed to read %s header file "
1947 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1948 PrintInode(stmp, h->ih_ino), errno);
1950 FDH_REALLYCLOSE(fdP);
1953 if (nbytes != size) {
1954 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1955 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%d, read=%d\n",
1956 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1957 PrintInode(stmp, h->ih_ino), size, (int)nbytes);
1959 FDH_REALLYCLOSE(fdP);
1962 if (vsn->magic != magic) {
1963 Log("ReadHeader: Incorrect magic for %s header file "
1964 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=0x%x, read=0x%x\n",
1965 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1966 PrintInode(stmp, h->ih_ino), magic, vsn->magic);
1968 FDH_REALLYCLOSE(fdP);
1974 /* Check is conditional, in case caller wants to inspect version himself */
1975 if (version && vsn->version != version) {
1976 Log("ReadHeader: Incorrect version for %s header file "
1977 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%x, read=%x\n",
1978 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid), PrintInode(stmp, h->ih_ino),
1979 version, vsn->version);
1985 WriteVolumeHeader_r(Error * ec, Volume * vp)
1987 IHandle_t *h = V_diskDataHandle(vp);
1997 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1998 != sizeof(V_disk(vp))) {
2000 FDH_REALLYCLOSE(fdP);
2006 /* VolumeHeaderToDisk
2007 * Allows for storing 64 bit inode numbers in on-disk volume header
2010 /* convert in-memory representation of a volume header to the
2011 * on-disk representation of a volume header */
2013 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2016 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2017 dh->stamp = h->stamp;
2019 dh->parent = h->parent;
2021 #ifdef AFS_64BIT_IOPS_ENV
2022 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2023 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2024 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2025 dh->smallVnodeIndex_hi =
2026 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2027 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2028 dh->largeVnodeIndex_hi =
2029 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2030 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2031 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2033 dh->volumeInfo_lo = h->volumeInfo;
2034 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2035 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2036 dh->linkTable_lo = h->linkTable;
2040 /* DiskToVolumeHeader
2041 * Converts an on-disk representation of a volume header to
2042 * the in-memory representation of a volume header.
2044 * Makes the assumption that AFS has *always*
2045 * zero'd the volume header file so that high parts of inode
2046 * numbers are 0 in older (SGI EFS) volume header files.
2049 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2051 memset(h, 0, sizeof(VolumeHeader_t));
2052 h->stamp = dh->stamp;
2054 h->parent = dh->parent;
2056 #ifdef AFS_64BIT_IOPS_ENV
2058 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2060 h->smallVnodeIndex =
2061 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2062 smallVnodeIndex_hi << 32);
2064 h->largeVnodeIndex =
2065 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2066 largeVnodeIndex_hi << 32);
2068 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2070 h->volumeInfo = dh->volumeInfo_lo;
2071 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2072 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2073 h->linkTable = dh->linkTable_lo;
2078 /***************************************************/
2079 /* Volume Attachment routines */
2080 /***************************************************/
2082 #ifdef AFS_DEMAND_ATTACH_FS
2084 * pre-attach a volume given its path.
2086 * @param[out] ec outbound error code
2087 * @param[in] partition partition path string
2088 * @param[in] name volume id string
2090 * @return volume object pointer
2092 * @note A pre-attached volume will only have its partition
2093 * and hashid fields initialized. At first call to
2094 * VGetVolume, the volume will be fully attached.
2098 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2102 vp = VPreAttachVolumeByName_r(ec, partition, name);
2108 * pre-attach a volume given its path.
2110 * @param[out] ec outbound error code
2111 * @param[in] partition path to vice partition
2112 * @param[in] name volume id string
2114 * @return volume object pointer
2116 * @pre VOL_LOCK held
2118 * @internal volume package internal use only.
2121 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2123 return VPreAttachVolumeById_r(ec,
2125 VolumeNumber(name));
2129 * pre-attach a volume given its path and numeric volume id.
2131 * @param[out] ec error code return
2132 * @param[in] partition path to vice partition
2133 * @param[in] volumeId numeric volume id
2135 * @return volume object pointer
2137 * @pre VOL_LOCK held
2139 * @internal volume package internal use only.
2142 VPreAttachVolumeById_r(Error * ec,
2147 struct DiskPartition64 *partp;
2151 opr_Assert(programType == fileServer);
2153 if (!(partp = VGetPartition_r(partition, 0))) {
2155 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2159 /* ensure that any vp we pass to VPreAttachVolumeByVp_r
2160 * is NOT in exclusive state.
2163 vp = VLookupVolume_r(ec, volumeId, NULL);
2169 if (vp && VIsExclusiveState(V_attachState(vp))) {
2170 VCreateReservation_r(vp);
2171 VWaitExclusiveState_r(vp);
2172 VCancelReservation_r(vp);
2174 goto retry; /* look up volume again */
2177 /* vp == NULL or vp not exclusive both OK */
2179 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2183 * preattach a volume.
2185 * @param[out] ec outbound error code
2186 * @param[in] partp pointer to partition object
2187 * @param[in] vp pointer to volume object
2188 * @param[in] vid volume id
2190 * @return volume object pointer
2192 * @pre VOL_LOCK is held.
2194 * @pre vp (if specified) must not be in exclusive state.
2196 * @warning Returned volume object pointer does not have to
2197 * equal the pointer passed in as argument vp. There
2198 * are potential race conditions which can result in
2199 * the pointers having different values. It is up to
2200 * the caller to make sure that references are handled
2201 * properly in this case.
2203 * @note If there is already a volume object registered with
2204 * the same volume id, its pointer MUST be passed as
2205 * argument vp. Failure to do so will result in a silent
2206 * failure to preattach.
2208 * @internal volume package internal use only.
2211 VPreAttachVolumeByVp_r(Error * ec,
2212 struct DiskPartition64 * partp,
2220 /* don't proceed unless it's safe */
2222 opr_Assert(!VIsExclusiveState(V_attachState(vp)));
2225 /* check to see if pre-attach already happened */
2227 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2228 (V_attachState(vp) != VOL_STATE_DELETED) &&
2229 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2230 !VIsErrorState(V_attachState(vp))) {
2232 * pre-attach is a no-op in all but the following cases:
2234 * - volume is unattached
2235 * - volume is in an error state
2236 * - volume is pre-attached
2238 Log("VPreattachVolumeByVp_r: volume %" AFS_VOLID_FMT " not in quiescent state (state %u flags 0x%x)\n",
2239 afs_printable_VolumeId_lu(vid), V_attachState(vp),
2243 /* we're re-attaching a volume; clear out some old state */
2244 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2246 if (V_partition(vp) != partp) {
2247 /* XXX potential race */
2248 DeleteVolumeFromVByPList_r(vp);
2251 /* if we need to allocate a new Volume struct,
2252 * go ahead and drop the vol glock, otherwise
2253 * do the basic setup synchronised, as it's
2254 * probably not worth dropping the lock */
2257 /* allocate the volume structure */
2258 vp = nvp = calloc(1, sizeof(Volume));
2259 opr_Assert(vp != NULL);
2260 queue_Init(&vp->vnode_list);
2261 queue_Init(&vp->rx_call_list);
2262 opr_cv_init(&V_attachCV(vp));
2265 /* link the volume with its associated vice partition */
2266 vp->device = partp->device;
2267 vp->partition = partp;
2270 vp->specialStatus = 0;
2272 /* if we dropped the lock, reacquire the lock,
2273 * check for pre-attach races, and then add
2274 * the volume to the hash table */
2277 nvp = VLookupVolume_r(ec, vid, NULL);
2282 } else if (nvp) { /* race detected */
2287 /* hack to make up for VChangeState_r() decrementing
2288 * the old state counter */
2289 VStats.state_levels[0]++;
2293 /* put pre-attached volume onto the hash table
2294 * and bring it up to the pre-attached state */
2295 AddVolumeToHashTable(vp, vp->hashid);
2296 AddVolumeToVByPList_r(vp);
2297 VLRU_Init_Node_r(vp);
2298 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2300 if (GetLogLevel() >= 5)
2301 Log("VPreAttachVolumeByVp_r: volume %" AFS_VOLID_FMT " pre-attached\n", afs_printable_VolumeId_lu(vp->hashid));
2309 #endif /* AFS_DEMAND_ATTACH_FS */
2311 /* Attach an existing volume, given its pathname, and return a
2312 pointer to the volume header information. The volume also
2313 normally goes online at this time. An offline volume
2314 must be reattached to make it go online */
2316 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2320 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2326 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2329 struct DiskPartition64 *partp;
2334 #ifdef AFS_DEMAND_ATTACH_FS
2335 VolumeStats stats_save;
2337 #endif /* AFS_DEMAND_ATTACH_FS */
2341 volumeId = VolumeNumber(name);
2343 if (!(partp = VGetPartition_r(partition, 0))) {
2345 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2349 if (VRequiresPartLock()) {
2350 opr_Assert(VInit == 3);
2351 VLockPartition_r(partition);
2352 } else if (programType == fileServer) {
2353 #ifdef AFS_DEMAND_ATTACH_FS
2354 /* lookup the volume in the hash table */
2355 vp = VLookupVolume_r(ec, volumeId, NULL);
2361 /* save any counters that are supposed to
2362 * be monotonically increasing over the
2363 * lifetime of the fileserver */
2364 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2366 memset(&stats_save, 0, sizeof(VolumeStats));
2369 /* if there's something in the hash table, and it's not
2370 * in the pre-attach state, then we may need to detach
2371 * it before proceeding */
2372 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2373 VCreateReservation_r(vp);
2374 VWaitExclusiveState_r(vp);
2376 /* at this point state must be one of:
2386 if (vp->specialStatus == VBUSY)
2389 /* if it's already attached, see if we can return it */
2390 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2391 VGetVolumeByVp_r(ec, vp);
2392 if (V_inUse(vp) == fileServer) {
2393 VCancelReservation_r(vp);
2397 /* otherwise, we need to detach, and attempt to re-attach */
2398 VDetachVolume_r(ec, vp);
2400 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2403 /* if it isn't fully attached, delete from the hash tables,
2404 and let the refcounter handle the rest */
2405 DeleteVolumeFromHashTable(vp);
2406 DeleteVolumeFromVByPList_r(vp);
2409 VCancelReservation_r(vp);
2413 /* pre-attach volume if it hasn't been done yet */
2415 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2416 (V_attachState(vp) == VOL_STATE_DELETED) ||
2417 (V_attachState(vp) == VOL_STATE_ERROR)) {
2419 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2425 opr_Assert(vp != NULL);
2427 /* handle pre-attach races
2429 * multiple threads can race to pre-attach a volume,
2430 * but we can't let them race beyond that
2432 * our solution is to let the first thread to bring
2433 * the volume into an exclusive state win; the other
2434 * threads just wait until it finishes bringing the
2435 * volume online, and then they do a vgetvolumebyvp
2437 if (svp && (svp != vp)) {
2438 /* wait for other exclusive ops to finish */
2439 VCreateReservation_r(vp);
2440 VWaitExclusiveState_r(vp);
2442 /* get a heavyweight ref, kill the lightweight ref, and return */
2443 VGetVolumeByVp_r(ec, vp);
2444 VCancelReservation_r(vp);
2448 /* at this point, we are chosen as the thread to do
2449 * demand attachment for this volume. all other threads
2450 * doing a getvolume on vp->hashid will block until we finish */
2452 /* make sure any old header cache entries are invalidated
2453 * before proceeding */
2454 FreeVolumeHeader(vp);
2456 VChangeState_r(vp, VOL_STATE_ATTACHING);
2458 /* restore any saved counters */
2459 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2460 #else /* AFS_DEMAND_ATTACH_FS */
2461 vp = VGetVolume_r(ec, volumeId);
2463 if (V_inUse(vp) == fileServer)
2465 if (vp->specialStatus == VBUSY)
2467 VDetachVolume_r(ec, vp);
2469 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2473 #endif /* AFS_DEMAND_ATTACH_FS */
2477 strcpy(path, VPartitionPath(partp));
2481 strcat(path, OS_DIRSEP);
2485 vp = (Volume *) calloc(1, sizeof(Volume));
2486 opr_Assert(vp != NULL);
2487 vp->hashid = volumeId;
2488 vp->device = partp->device;
2489 vp->partition = partp;
2490 queue_Init(&vp->vnode_list);
2491 queue_Init(&vp->rx_call_list);
2492 #ifdef AFS_DEMAND_ATTACH_FS
2493 opr_cv_init(&V_attachCV(vp));
2494 #endif /* AFS_DEMAND_ATTACH_FS */
2497 /* attach2 is entered without any locks, and returns
2498 * with vol_glock_mutex held */
2499 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2501 if (VCanUseFSSYNC() && vp) {
2502 #ifdef AFS_DEMAND_ATTACH_FS
2503 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2504 /* mark volume header as in use so that volser crashes lead to a
2505 * salvage attempt */
2506 VUpdateVolume_r(ec, vp, 0);
2508 /* for dafs, we should tell the fileserver, except for V_PEEK
2509 * where we know it is not necessary */
2510 if (mode == V_PEEK) {
2511 vp->needsPutBack = 0;
2513 vp->needsPutBack = VOL_PUTBACK;
2515 #else /* !AFS_DEMAND_ATTACH_FS */
2516 /* duplicate computation in fssync.c about whether the server
2517 * takes the volume offline or not. If the volume isn't
2518 * offline, we must not return it when we detach the volume,
2519 * or the server will abort */
2520 if (mode == V_READONLY || mode == V_PEEK
2521 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2522 vp->needsPutBack = 0;
2524 vp->needsPutBack = VOL_PUTBACK;
2525 #endif /* !AFS_DEMAND_ATTACH_FS */
2527 #ifdef FSSYNC_BUILD_CLIENT
2528 /* Only give back the vol to the fileserver if we checked it out; attach2
2529 * will set checkedOut only if we successfully checked it out from the
2531 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2533 #ifdef AFS_DEMAND_ATTACH_FS
2534 /* If we couldn't attach but we scheduled a salvage, we already
2535 * notified the fileserver; don't online it now */
2536 if (*ec != VSALVAGING)
2537 #endif /* AFS_DEMAND_ATTACH_FS */
2538 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2541 if (programType == fileServer && vp) {
2542 #ifdef AFS_DEMAND_ATTACH_FS
2544 * we can get here in cases where we don't "own"
2545 * the volume (e.g. volume owned by a utility).
2546 * short circuit around potential disk header races.
2548 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2552 VUpdateVolume_r(ec, vp, 0);
2554 Log("VAttachVolume: Error updating volume\n");
2559 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2560 #ifndef AFS_DEMAND_ATTACH_FS
2561 /* This is a hack: by temporarily setting the incore
2562 * dontSalvage flag ON, the volume will be put back on the
2563 * Update list (with dontSalvage OFF again). It will then
2564 * come back in N minutes with DONT_SALVAGE eventually
2565 * set. This is the way that volumes that have never had
2566 * it set get it set; or that volumes that have been
2567 * offline without DONT SALVAGE having been set also
2568 * eventually get it set */
2569 V_dontSalvage(vp) = DONT_SALVAGE;
2570 #endif /* !AFS_DEMAND_ATTACH_FS */
2571 VAddToVolumeUpdateList_r(ec, vp);
2573 Log("VAttachVolume: Error adding volume to update list\n");
2579 if (GetLogLevel() != 0)
2580 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n", afs_printable_VolumeId_lu(V_id(vp)),
2585 if (VRequiresPartLock()) {
2586 VUnlockPartition_r(partition);
2589 #ifdef AFS_DEMAND_ATTACH_FS
2590 /* attach failed; make sure we're in error state */
2591 if (vp && !VIsErrorState(V_attachState(vp))) {
2592 VChangeState_r(vp, VOL_STATE_ERROR);
2594 #endif /* AFS_DEMAND_ATTACH_FS */
2601 #ifdef AFS_DEMAND_ATTACH_FS
2602 /* VAttachVolumeByVp_r
2604 * finish attaching a volume that is
2605 * in a less than fully attached state
2607 /* caller MUST hold a ref count on vp */
2609 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2611 char name[VMAXPATHLEN];
2613 struct DiskPartition64 *partp;
2617 Volume * nvp = NULL;
2618 VolumeStats stats_save;
2622 /* volume utility should never call AttachByVp */
2623 opr_Assert(programType == fileServer);
2625 volumeId = vp->hashid;
2626 partp = vp->partition;
2627 VolumeExternalName_r(volumeId, name, sizeof(name));
2630 /* if another thread is performing a blocking op, wait */
2631 VWaitExclusiveState_r(vp);
2633 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2635 /* if it's already attached, see if we can return it */
2636 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2637 VGetVolumeByVp_r(ec, vp);
2638 if (V_inUse(vp) == fileServer) {
2641 if (vp->specialStatus == VBUSY)
2643 VDetachVolume_r(ec, vp);
2645 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2651 /* pre-attach volume if it hasn't been done yet */
2653 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2654 (V_attachState(vp) == VOL_STATE_DELETED) ||
2655 (V_attachState(vp) == VOL_STATE_ERROR)) {
2656 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2662 VCreateReservation_r(nvp);
2667 opr_Assert(vp != NULL);
2668 VChangeState_r(vp, VOL_STATE_ATTACHING);
2670 /* restore monotonically increasing stats */
2671 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2675 /* compute path to disk header */
2676 strcpy(path, VPartitionPath(partp));
2680 strcat(path, OS_DIRSEP);
2685 * NOTE: attach2 is entered without any locks, and returns
2686 * with vol_glock_mutex held */
2687 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2690 * the event that an error was encountered, or
2691 * the volume was not brought to an attached state
2692 * for any reason, skip to the end. We cannot
2693 * safely call VUpdateVolume unless we "own" it.
2697 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2701 VUpdateVolume_r(ec, vp, 0);
2703 Log("VAttachVolume: Error updating volume %" AFS_VOLID_FMT "\n",
2704 afs_printable_VolumeId_lu(vp->hashid));
2708 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2709 #ifndef AFS_DEMAND_ATTACH_FS
2710 /* This is a hack: by temporarily setting the incore
2711 * dontSalvage flag ON, the volume will be put back on the
2712 * Update list (with dontSalvage OFF again). It will then
2713 * come back in N minutes with DONT_SALVAGE eventually
2714 * set. This is the way that volumes that have never had
2715 * it set get it set; or that volumes that have been
2716 * offline without DONT SALVAGE having been set also
2717 * eventually get it set */
2718 V_dontSalvage(vp) = DONT_SALVAGE;
2719 #endif /* !AFS_DEMAND_ATTACH_FS */
2720 VAddToVolumeUpdateList_r(ec, vp);
2722 Log("VAttachVolume: Error adding volume %" AFS_VOLID_FMT " to update list\n",
2723 afs_printable_VolumeId_lu(vp->hashid));
2729 if (GetLogLevel() != 0)
2730 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n",
2731 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
2734 VCancelReservation_r(nvp);
2737 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2738 if (vp && !VIsErrorState(V_attachState(vp))) {
2739 VChangeState_r(vp, VOL_STATE_ERROR);
2748 * lock a volume on disk (non-blocking).
2750 * @param[in] vp The volume to lock
2751 * @param[in] locktype READ_LOCK or WRITE_LOCK
2753 * @return operation status
2754 * @retval 0 success, lock was obtained
2755 * @retval EBUSY a conflicting lock was held by another process
2756 * @retval EIO error acquiring lock
2758 * @pre If we're in the fileserver, vp is in an exclusive state
2760 * @pre vp is not already locked
2763 VLockVolumeNB(Volume *vp, int locktype)
2767 opr_Assert(programType != fileServer
2768 || VIsExclusiveState(V_attachState(vp)));
2769 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2771 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2773 V_attachFlags(vp) |= VOL_LOCKED;
2780 * unlock a volume on disk that was locked with VLockVolumeNB.
2782 * @param[in] vp volume to unlock
2784 * @pre If we're in the fileserver, vp is in an exclusive state
2786 * @pre vp has already been locked
2789 VUnlockVolume(Volume *vp)
2791 opr_Assert(programType != fileServer
2792 || VIsExclusiveState(V_attachState(vp)));
2793 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2795 VUnlockVolumeById(vp->hashid, vp->partition);
2797 V_attachFlags(vp) &= ~VOL_LOCKED;
2799 #endif /* AFS_DEMAND_ATTACH_FS */
2802 * read in a vol header, possibly lock the vol header, and possibly check out
2803 * the vol header from the fileserver, as part of volume attachment.
2805 * @param[out] ec error code
2806 * @param[in] vp volume pointer object
2807 * @param[in] partp disk partition object of the attaching partition
2808 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2810 * @param[in] peek 1 to just try to read in the volume header and make sure
2811 * we don't try to lock the vol, or check it out from
2812 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2814 * @param[out] acheckedOut If we successfully checked-out the volume from
2815 * the fileserver (if we needed to), this is set
2816 * to 1, otherwise it is untouched.
2818 * @note As part of DAFS volume attachment, the volume header may be either
2819 * read- or write-locked to ensure mutual exclusion of certain volume
2820 * operations. In some cases in order to determine whether we need to
2821 * read- or write-lock the header, we need to read in the header to see
2822 * if the volume is RW or not. So, if we read in the header under a
2823 * read-lock and determine that we actually need a write-lock on the
2824 * volume header, this function will drop the read lock, acquire a write
2825 * lock, and read the header in again.
2828 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2829 int mode, int peek, int *acheckedOut)
2831 struct VolumeDiskHeader diskHeader;
2832 struct VolumeHeader header;
2835 int lock_tries = 0, checkout_tries = 0;
2837 VolumeId volid = vp->hashid;
2838 #ifdef FSSYNC_BUILD_CLIENT
2839 int checkout, done_checkout = 0;
2840 #endif /* FSSYNC_BUILD_CLIENT */
2841 #ifdef AFS_DEMAND_ATTACH_FS
2842 int locktype = 0, use_locktype = -1;
2843 #endif /* AFS_DEMAND_ATTACH_FS */
2849 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2850 Log("VAttachVolume: retried too many times trying to lock header for "
2851 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2852 VPartitionPath(partp));
2856 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2857 Log("VAttachVolume: retried too many times trying to checkout "
2858 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2859 VPartitionPath(partp));
2864 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2865 /* short-circuit the 'volume does not exist' case */
2870 #ifdef FSSYNC_BUILD_CLIENT
2871 checkout = !done_checkout;
2873 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2875 memset(&res, 0, sizeof(res));
2877 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2880 if (res.hdr.reason == FSYNC_SALVAGE) {
2881 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2882 afs_printable_uint32_lu(volid));
2885 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2886 afs_printable_uint32_lu(volid));
2887 *ec = VNOVOL; /* XXXX */
2895 #ifdef AFS_DEMAND_ATTACH_FS
2896 if (use_locktype < 0) {
2897 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2898 * if it turns out to be RW */
2899 locktype = VVolLockType(mode, 0);
2902 /* a previous try says we should use use_locktype to lock the volume,
2904 locktype = use_locktype;
2907 if (!peek && locktype) {
2908 code = VLockVolumeNB(vp, locktype);
2910 if (code == EBUSY) {
2911 Log("VAttachVolume: another program has vol %lu locked\n",
2912 afs_printable_uint32_lu(volid));
2914 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2915 code, afs_printable_uint32_lu(volid));
2922 #endif /* AFS_DEMAND_ATTACH_FS */
2924 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2934 DiskToVolumeHeader(&header, &diskHeader);
2936 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2937 header.largeVnodeIndex);
2938 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2939 header.smallVnodeIndex);
2940 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2942 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2945 /* only need to do this once */
2947 GetVolumeHeader(vp);
2951 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2952 /* demand attach changes the V_PEEK mechanism
2954 * we can now suck the current disk data structure over
2955 * the fssync interface without going to disk
2957 * (technically, we don't need to restrict this feature
2958 * to demand attach fileservers. However, I'm trying
2959 * to limit the number of common code changes)
2961 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2963 res.payload.len = sizeof(VolumeDiskData);
2964 res.payload.buf = &(V_disk(vp));
2966 if (FSYNC_VolOp(vp->hashid,
2968 FSYNC_VOL_QUERY_HDR,
2971 goto disk_header_loaded;
2974 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2975 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2976 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2978 #ifdef AFS_DEMAND_ATTACH_FS
2981 IncUInt64(&VStats.hdr_loads);
2982 IncUInt64(&vp->stats.hdr_loads);
2984 #endif /* AFS_DEMAND_ATTACH_FS */
2987 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2988 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2992 #ifdef AFS_DEMAND_ATTACH_FS
2993 # ifdef FSSYNC_BUILD_CLIENT
2995 # endif /* FSSYNC_BUILD_CLIENT */
2997 /* if the lock type we actually used to lock the volume is different than
2998 * the lock type we should have used, retry with the lock type we should
3000 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
3001 if (locktype != use_locktype) {
3005 #endif /* AFS_DEMAND_ATTACH_FS */
3010 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
3011 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
3013 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
3015 if (code == SYNC_DENIED) {
3016 /* must retry checkout; fileserver no longer thinks we have
3022 } else if (code != SYNC_OK) {
3026 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3029 /* either we are going to be called again for a second pass, or we
3030 * encountered an error; clean up in either case */
3032 #ifdef AFS_DEMAND_ATTACH_FS
3033 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3036 #endif /* AFS_DEMAND_ATTACH_FS */
3037 if (vp->linkHandle) {
3038 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3039 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3040 IH_RELEASE(vp->diskDataHandle);
3041 IH_RELEASE(vp->linkHandle);
3047 FreeVolumeHeader(vp);
3057 #ifdef AFS_DEMAND_ATTACH_FS
3059 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3060 Volume *vp, int *acheckedOut)
3064 if (vp->pending_vol_op) {
3068 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3070 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3072 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3073 } else if (code == 0) {
3074 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3077 /* we need the vol header to determine if the volume can be
3078 * left online for the vop, so... get the header */
3082 /* attach header with peek=1 to avoid checking out the volume
3083 * or locking it; we just want the header info, we're not
3084 * messing with the volume itself at all */
3085 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3092 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3093 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3095 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3098 /* make sure we grab a new vol header and re-open stuff on
3099 * actual attachment; we can't keep the data we grabbed, since
3100 * it was not done under a lock and thus not safe */
3101 FreeVolumeHeader(vp);
3102 VReleaseVolumeHandles_r(vp);
3105 /* see if the pending volume op requires exclusive access */
3106 switch (vp->pending_vol_op->vol_op_state) {
3107 case FSSYNC_VolOpPending:
3108 /* this should never happen */
3109 opr_Assert(vp->pending_vol_op->vol_op_state
3110 != FSSYNC_VolOpPending);
3113 case FSSYNC_VolOpRunningUnknown:
3114 /* this should never happen; we resolved 'unknown' above */
3115 opr_Assert(vp->pending_vol_op->vol_op_state
3116 != FSSYNC_VolOpRunningUnknown);
3119 case FSSYNC_VolOpRunningOffline:
3120 /* mark the volume down */
3122 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3124 /* do not set V_offlineMessage here; we don't have ownership of
3125 * the volume (and probably do not have the header loaded), so we
3126 * can't alter the disk header */
3128 /* check to see if we should set the specialStatus flag */
3129 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3130 /* don't overwrite specialStatus if it was already set to
3131 * something else (e.g. VMOVED) */
3132 if (!vp->specialStatus) {
3133 vp->specialStatus = VBUSY;
3145 #endif /* AFS_DEMAND_ATTACH_FS */
3148 * volume attachment helper function.
3150 * @param[out] ec error code
3151 * @param[in] volumeId volume ID of the attaching volume
3152 * @param[in] path full path to the volume header .vol file
3153 * @param[in] partp disk partition object for the attaching partition
3154 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3155 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3156 * DAFS) should already be initialized
3157 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3158 * if there is a volume operation running for this volume
3159 * that should set the volume to VBUSY during its run. 0
3160 * otherwise. (see VVolOpSetVBusy_r)
3161 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3163 * @param[out] acheckedOut If we successfully checked-out the volume from
3164 * the fileserver (if we needed to), this is set
3165 * to 1, otherwise it is 0.
3167 * @return pointer to the semi-attached volume pointer
3168 * @retval NULL an error occurred (check value of *ec)
3169 * @retval vp volume successfully attaching
3171 * @pre no locks held
3173 * @post VOL_LOCK held
3176 attach2(Error * ec, VolumeId volumeId, char *path, struct DiskPartition64 *partp,
3177 Volume * vp, int isbusy, int mode, int *acheckedOut)
3179 /* have we read in the header successfully? */
3180 int read_header = 0;
3182 #ifdef AFS_DEMAND_ATTACH_FS
3183 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3187 /* in the case of an error, to what state should the volume be
3189 VolState error_state = VOL_STATE_ERROR;
3190 #endif /* AFS_DEMAND_ATTACH_FS */
3194 vp->vnodeIndex[vLarge].handle = NULL;
3195 vp->vnodeIndex[vSmall].handle = NULL;
3196 vp->diskDataHandle = NULL;
3197 vp->linkHandle = NULL;
3201 #ifdef AFS_DEMAND_ATTACH_FS
3202 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3204 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3207 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3208 #endif /* !AFS_DEMAND_ATTACH_FS */
3210 if (*ec == VNOVOL) {
3211 /* if the volume doesn't exist, skip straight to 'error' so we don't
3212 * request a salvage */
3213 goto unlocked_error;
3219 /* ensure that we don't override specialStatus if it was set to
3220 * something else (e.g. VMOVED) */
3221 if (isbusy && !vp->specialStatus) {
3222 vp->specialStatus = VBUSY;
3224 vp->shuttingDown = 0;
3225 vp->goingOffline = 0;
3227 #ifdef AFS_DEMAND_ATTACH_FS
3228 vp->stats.last_attach = FT_ApproxTime();
3229 vp->stats.attaches++;
3233 IncUInt64(&VStats.attaches);
3234 vp->cacheCheck = ++VolumeCacheCheck;
3235 /* just in case this ever rolls over */
3236 if (!vp->cacheCheck)
3237 vp->cacheCheck = ++VolumeCacheCheck;
3240 #ifdef AFS_DEMAND_ATTACH_FS
3241 V_attachFlags(vp) |= VOL_HDR_LOADED;
3242 vp->stats.last_hdr_load = vp->stats.last_attach;
3243 #endif /* AFS_DEMAND_ATTACH_FS */
3247 struct IndexFileHeader iHead;
3250 * We just read in the diskstuff part of the header. If the detailed
3251 * volume stats area has not yet been initialized, we should bzero the
3252 * area and mark it as initialized.
3254 if (!(V_stat_initialized(vp))) {
3255 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3256 V_stat_initialized(vp) = 1;
3259 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3260 (char *)&iHead, sizeof(iHead),
3261 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3264 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3269 struct IndexFileHeader iHead;
3271 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3272 (char *)&iHead, sizeof(iHead),
3273 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3276 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3280 #ifdef AFS_NAMEI_ENV
3282 struct versionStamp stamp;
3284 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3285 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3288 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3291 #endif /* AFS_NAMEI_ENV */
3293 #if defined(AFS_DEMAND_ATTACH_FS)
3294 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3296 if (!VCanScheduleSalvage()) {
3297 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3299 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3304 /* volume operation in progress */
3306 /* we have already transitioned the vp away from ATTACHING state, so we
3307 * can go right to the end of attach2, and we do not need to transition
3309 goto error_notbroken;
3311 #else /* AFS_DEMAND_ATTACH_FS */
3313 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3314 goto unlocked_error;
3316 #endif /* AFS_DEMAND_ATTACH_FS */
3318 if (V_needsSalvaged(vp)) {
3319 if (vp->specialStatus)
3320 vp->specialStatus = 0;
3322 #if defined(AFS_DEMAND_ATTACH_FS)
3323 if (!VCanScheduleSalvage()) {
3324 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3326 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3329 #else /* AFS_DEMAND_ATTACH_FS */
3331 #endif /* AFS_DEMAND_ATTACH_FS */
3337 vp->nextVnodeUnique = V_uniquifier(vp);
3339 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3340 if (!V_needsSalvaged(vp)) {
3341 V_needsSalvaged(vp) = 1;
3342 VUpdateVolume_r(ec, vp, 0);
3344 #if defined(AFS_DEMAND_ATTACH_FS)
3345 if (!VCanScheduleSalvage()) {
3346 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3348 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3351 #else /* AFS_DEMAND_ATTACH_FS */
3352 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3354 #endif /* AFS_DEMAND_ATTACH_FS */
3359 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3360 /* Only check destroyMe if we are the fileserver, since the
3361 * volserver et al sometimes need to work with volumes with
3362 * destroyMe set. Examples are 'temporary' volumes the
3363 * volserver creates, and when we create a volume (destroyMe
3364 * is set on creation; sometimes a separate volserver
3365 * transaction is created to clear destroyMe).
3368 #if defined(AFS_DEMAND_ATTACH_FS)
3369 /* schedule a salvage so the volume goes away on disk */
3370 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3371 VChangeState_r(vp, VOL_STATE_ERROR);
3374 #endif /* AFS_DEMAND_ATTACH_FS */
3375 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3380 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3381 #ifndef BITMAP_LATER
3382 if (programType == fileServer && VolumeWriteable(vp)) {
3384 for (i = 0; i < nVNODECLASSES; i++) {
3385 VGetBitmap_r(ec, vp, i);
3387 #ifdef AFS_DEMAND_ATTACH_FS
3388 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3390 #endif /* AFS_DEMAND_ATTACH_FS */
3391 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3397 #endif /* BITMAP_LATER */
3399 if (VInit >= 2 && V_needsCallback(vp)) {
3400 if (V_BreakVolumeCallbacks) {
3401 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3402 afs_printable_uint32_lu(V_id(vp)));
3403 V_needsCallback(vp) = 0;
3405 (*V_BreakVolumeCallbacks) (V_id(vp));
3408 VUpdateVolume_r(ec, vp, 0);
3410 #ifdef FSSYNC_BUILD_CLIENT
3411 else if (VCanUseFSSYNC()) {
3412 afs_int32 fsync_code;
3414 V_needsCallback(vp) = 0;
3416 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3420 V_needsCallback(vp) = 1;
3421 Log("Error trying to tell the fileserver to break callbacks for "
3422 "changed volume %lu; error code %ld\n",
3423 afs_printable_uint32_lu(V_id(vp)),
3424 afs_printable_int32_ld(fsync_code));
3426 VUpdateVolume_r(ec, vp, 0);
3429 #endif /* FSSYNC_BUILD_CLIENT */
3432 Log("VAttachVolume: error %d clearing needsCallback on volume "
3433 "%lu; needs salvage\n", (int)*ec,
3434 afs_printable_uint32_lu(V_id(vp)));
3435 #ifdef AFS_DEMAND_ATTACH_FS
3436 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3438 #else /* !AFS_DEMAND_ATTACH_FS */
3440 #endif /* !AFS_DEMAND_ATTACh_FS */
3445 if (programType == fileServer) {
3446 if (vp->specialStatus)
3447 vp->specialStatus = 0;
3448 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3449 V_inUse(vp) = fileServer;
3450 V_offlineMessage(vp)[0] = '\0';
3452 #ifdef AFS_DEMAND_ATTACH_FS
3453 /* check if the volume is actually usable. only do this for DAFS; for
3454 * non-DAFS, volumes that are not inService/blessed can still be
3455 * attached, even if clients cannot access them. this is relevant
3456 * because for non-DAFS, we try to attach the volume when e.g.
3457 * volserver gives us back then vol when its done with it, but
3458 * volserver may give us back a volume that is not inService/blessed. */
3462 /* Put the vol into PREATTACHED state, so if someone tries to
3463 * access it again, we try to attach, see that we're not blessed,
3464 * and give a VNOVOL error again. Putting it into UNATTACHED state
3465 * would result in a VOFFLINE error instead. */
3466 error_state = VOL_STATE_PREATTACHED;
3468 /* mimic e.g. GetVolume errors */
3469 if (!V_blessed(vp)) {
3470 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3471 FreeVolumeHeader(vp);
3472 } else if (!V_inService(vp)) {
3473 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3474 /* the volume is offline and should be unattached */
3476 error_state = VOL_STATE_UNATTACHED;
3477 FreeVolumeHeader(vp);
3479 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3481 error_state = VOL_STATE_ERROR;
3482 /* see if we can recover */
3483 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3488 #endif /* AFS_DEMAND_ATTACH_FS */
3490 #ifdef AFS_DEMAND_ATTACH_FS
3491 if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3492 V_inUse(vp) = programType;
3493 #endif /* AFS_DEMAND_ATTACH_FS */
3494 V_checkoutMode(vp) = mode;
3497 AddVolumeToHashTable(vp, vp->hashid);
3498 #ifdef AFS_DEMAND_ATTACH_FS
3499 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3502 if ((programType != fileServer) ||
3503 (V_inUse(vp) == fileServer)) {
3504 AddVolumeToVByPList_r(vp);
3506 VChangeState_r(vp, VOL_STATE_ATTACHED);
3508 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3517 #ifdef AFS_DEMAND_ATTACH_FS
3518 if (!VIsErrorState(V_attachState(vp))) {
3519 if (programType != fileServer && *ec == VNOVOL) {
3520 /* do not log anything in this case; it is common for
3521 * non-fileserver programs to fail here with VNOVOL, since that
3522 * is what happens when they simply try to use a volume, but that
3523 * volume doesn't exist. */
3525 } else if (VIsErrorState(error_state)) {
3526 Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3527 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3528 V_attachFlags(vp), *ec);
3530 VChangeState_r(vp, error_state);
3532 #endif /* AFS_DEMAND_ATTACH_FS */
3535 VReleaseVolumeHandles_r(vp);
3538 #ifdef AFS_DEMAND_ATTACH_FS
3540 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3541 /* The salvage could not be scheduled with the salvage server
3542 * due to a hard error. Reset the error code to prevent retry loops by
3544 if (*ec == VSALVAGING) {
3553 #else /* !AFS_DEMAND_ATTACH_FS */
3555 #endif /* !AFS_DEMAND_ATTACH_FS */
3559 /* Attach an existing volume.
3560 The volume also normally goes online at this time.
3561 An offline volume must be reattached to make it go online.
3565 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3569 retVal = VAttachVolume_r(ec, volumeId, mode);
3575 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3578 VGetVolumePath(ec, volumeId, &part, &name);
3582 vp = VGetVolume_r(&error, volumeId);
3584 opr_Assert(V_inUse(vp) == 0);
3585 VDetachVolume_r(ec, vp);
3589 return VAttachVolumeByName_r(ec, part, name, mode);
3592 /* Increment a reference count to a volume, sans context swaps. Requires
3593 * possibly reading the volume header in from the disk, since there's
3594 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3596 * N.B. This call can fail if we can't read in the header!! In this case
3597 * we still guarantee we won't context swap, but the ref count won't be
3598 * incremented (otherwise we'd violate the invariant).
3600 /* NOTE: with the demand attach fileserver extensions, the global lock
3601 * is dropped within VHold */
3602 #ifdef AFS_DEMAND_ATTACH_FS
3604 VHold_r(Volume * vp)
3608 VCreateReservation_r(vp);
3609 VWaitExclusiveState_r(vp);
3611 LoadVolumeHeader(&error, vp);
3613 VCancelReservation_r(vp);
3617 VCancelReservation_r(vp);
3620 #else /* AFS_DEMAND_ATTACH_FS */
3622 VHold_r(Volume * vp)
3626 LoadVolumeHeader(&error, vp);
3632 #endif /* AFS_DEMAND_ATTACH_FS */
3634 /**** volume timeout-related stuff ****/
3636 #ifdef AFS_PTHREAD_ENV
3638 static struct timespec *shutdown_timeout;
3639 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3642 VTimedOut(const struct timespec *ts)
3647 if (ts->tv_sec == 0) {
3648 /* short-circuit; this will have always timed out */
3652 code = gettimeofday(&tv, NULL);
3654 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3655 /* assume no timeout; failure mode is we just wait longer than normal
3656 * instead of returning errors when we shouldn't */
3660 if (tv.tv_sec < ts->tv_sec ||
3661 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3670 * Calculate an absolute timeout.
3672 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3673 * NULL, the memory is not touched
3674 * @param[in] timeout How long the timeout should be from now
3676 * @return timeout to use
3677 * @retval NULL no timeout; wait forever
3678 * @retval non-NULL the given value for "ts"
3682 static struct timespec *
3683 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3693 ts->tv_sec = ts->tv_nsec = 0;
3697 code = gettimeofday(&now, NULL);
3699 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3703 ts->tv_sec = now.tv_sec + timeout;
3704 ts->tv_nsec = now.tv_usec * 1000;
3710 * Initialize the shutdown_timeout global.
3713 VShutdownTimeoutInit(void)
3715 struct timespec *ts;
3717 ts = malloc(sizeof(*ts));
3719 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3721 if (!shutdown_timeout) {
3727 * Figure out the timeout that should be used for waiting for offline volumes.
3729 * @param[out] ats Storage space for a local timeout value if needed
3731 * @return The timeout value that should be used
3732 * @retval NULL No timeout; wait forever for offlining volumes
3733 * @retval non-NULL A pointer to the absolute time that should be used as
3734 * the deadline for waiting for offlining volumes.
3736 * @note If we return non-NULL, the pointer we return may or may not be the
3739 static const struct timespec *
3740 VOfflineTimeout(struct timespec *ats)
3742 if (vol_shutting_down) {
3743 opr_Verify(pthread_once(&shutdown_timeout_once,
3744 VShutdownTimeoutInit) == 0);
3745 return shutdown_timeout;
3747 return VCalcTimeout(ats, vol_opts.offline_timeout);
3751 #else /* AFS_PTHREAD_ENV */
3753 /* Waiting a certain amount of time for offlining volumes is not supported
3754 * for LWP due to a lack of primitives. So, we never time out */
3755 # define VTimedOut(x) (0)
3756 # define VOfflineTimeout(x) (NULL)
3758 #endif /* !AFS_PTHREAD_ENV */
3766 retVal = VHold_r(vp);
3773 VIsGoingOffline_r(struct Volume *vp)
3777 if (vp->goingOffline) {
3778 if (vp->specialStatus) {
3779 code = vp->specialStatus;
3780 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3791 * Tell the caller if a volume is waiting to go offline.
3793 * @param[in] vp The volume we want to know about
3795 * @return volume status
3796 * @retval 0 volume is not waiting to go offline, go ahead and use it
3797 * @retval nonzero volume is waiting to offline, and give the returned code
3798 * as an error to anyone accessing the volume
3800 * @pre VOL_LOCK is NOT held
3801 * @pre caller holds a heavyweight reference on vp
3804 VIsGoingOffline(struct Volume *vp)
3809 code = VIsGoingOffline_r(vp);
3816 * Register an RX call with a volume.
3818 * @param[inout] ec Error code; if unset when passed in, may be set if
3819 * the volume starts going offline
3820 * @param[out] client_ec @see GetVolume
3821 * @param[in] vp Volume struct
3822 * @param[in] cbv VCallByVol struct containing the RX call to register
3824 * @pre VOL_LOCK held
3825 * @pre caller holds heavy ref on vp
3830 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3833 #ifdef AFS_DEMAND_ATTACH_FS
3835 /* just in case the volume started going offline after we got the
3836 * reference to it... otherwise, if the volume started going
3837 * offline right at the end of GetVolume(), we might race with the
3838 * RX call scanner, and return success and add our cbv to the
3839 * rx_call_list _after_ the scanner has scanned the list. */
3840 *ec = VIsGoingOffline_r(vp);
3846 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3847 VWaitStateChange_r(vp);
3849 #endif /* AFS_DEMAND_ATTACH_FS */
3851 queue_Prepend(&vp->rx_call_list, cbv);
3856 * Deregister an RX call with a volume.
3858 * @param[in] vp Volume struct
3859 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3861 * @pre VOL_LOCK held
3862 * @pre caller holds heavy ref on vp
3867 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3869 if (cbv && queue_IsOnQueue(cbv)) {
3870 #ifdef AFS_DEMAND_ATTACH_FS
3871 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3872 VWaitStateChange_r(vp);
3874 #endif /* AFS_DEMAND_ATTACH_FS */
3880 /***************************************************/
3881 /* get and put volume routines */
3882 /***************************************************/
3885 * put back a heavyweight reference to a volume object.
3887 * @param[in] vp volume object pointer
3889 * @pre VOL_LOCK held
3891 * @post heavyweight volume reference put back.
3892 * depending on state, volume may have been taken offline,
3893 * detached, salvaged, freed, etc.
3895 * @internal volume package internal use only
3898 VPutVolume_r(Volume * vp)
3900 opr_Verify(--vp->nUsers >= 0);
3901 if (vp->nUsers == 0) {
3903 ReleaseVolumeHeader(vp->header);
3904 #ifdef AFS_DEMAND_ATTACH_FS
3905 if (!VCheckDetach(vp)) {
3909 #else /* AFS_DEMAND_ATTACH_FS */
3911 #endif /* AFS_DEMAND_ATTACH_FS */
3916 VPutVolume(Volume * vp)
3924 * Puts a volume reference obtained with VGetVolumeWithCall.
3926 * @param[in] vp Volume struct
3927 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3929 * @pre VOL_LOCK is NOT held
3932 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3935 VDeregisterCall_r(vp, cbv);
3940 /* Get a pointer to an attached volume. The pointer is returned regardless
3941 of whether or not the volume is in service or on/off line. An error
3942 code, however, is returned with an indication of the volume's status */
3944 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3948 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3954 * Get a volume reference associated with an RX call.
3956 * @param[out] ec @see GetVolume
3957 * @param[out] client_ec @see GetVolume
3958 * @param[in] volumeId @see GetVolume
3959 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3960 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3961 * with an error if the volume is going offline.
3962 * @param[in] cbv Contains an RX call to be associated with this volume
3963 * reference. This call may be interrupted if the volume is
3964 * requested to go offline while we hold a ref on it. Give NULL
3965 * to not associate an RX call with this reference.
3967 * @return @see GetVolume
3969 * @note for LWP builds, ts must be NULL
3971 * @note A reference obtained with this function MUST be put back with
3972 * VPutVolumeWithCall
3975 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3976 const struct timespec *ts, struct VCallByVol *cbv)
3980 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3981 VRegisterCall_r(ec, client_ec, retVal, cbv);
3987 VGetVolume_r(Error * ec, VolumeId volumeId)
3989 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3992 /* try to get a volume we've previously looked up */
3993 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3995 VGetVolumeByVp_r(Error * ec, Volume * vp)
3997 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
4001 * private interface for getting a volume handle
4003 * @param[out] ec error code (0 if no error)
4004 * @param[out] client_ec wire error code to be given to clients
4005 * @param[in] volumeId ID of the volume we want
4006 * @param[in] hint optional hint for hash lookups, or NULL
4007 * @param[in] timeout absolute deadline for waiting for the volume to go
4008 * offline, if it is going offline. NULL to wait forever.
4010 * @return a volume handle for the specified volume
4011 * @retval NULL an error occurred, or the volume is in such a state that
4012 * we cannot load a header or return any volume struct
4014 * @note for DAFS, caller must NOT hold a ref count on 'hint'
4016 * @note 'timeout' is only checked if the volume is actually going offline; so
4017 * if you pass timeout->tv_sec = 0, this will exhibit typical
4018 * nonblocking behavior.
4020 * @note for LWP builds, 'timeout' must be NULL
4023 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
4024 const struct timespec *timeout)
4027 /* pull this profiling/debugging code out of regular builds */
4029 #define VGET_CTR_INC(x) x++
4030 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
4031 0, V7 = 0, V8 = 0, V9 = 0;
4032 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
4034 #define VGET_CTR_INC(x)
4036 #ifdef AFS_DEMAND_ATTACH_FS
4037 Volume *avp, * rvp = hint;
4041 * if VInit is zero, the volume package dynamic
4042 * data structures have not been initialized yet,
4043 * and we must immediately return an error
4049 *client_ec = VOFFLINE;
4054 #ifdef AFS_DEMAND_ATTACH_FS
4056 VCreateReservation_r(rvp);
4058 #endif /* AFS_DEMAND_ATTACH_FS */
4066 vp = VLookupVolume_r(ec, volumeId, vp);
4072 #ifdef AFS_DEMAND_ATTACH_FS
4073 if (rvp && (rvp != vp)) {
4074 /* break reservation on old vp */
4075 VCancelReservation_r(rvp);
4078 #endif /* AFS_DEMAND_ATTACH_FS */
4084 /* Until we have reached an initialization level of 2
4085 * we don't know whether this volume exists or not.
4086 * We can't sleep and retry later because before a volume
4087 * is attached, the caller tries to get it first. Just
4088 * return VOFFLINE and the caller can choose whether to
4089 * retry the command or not. */
4099 IncUInt64(&VStats.hdr_gets);
4101 #ifdef AFS_DEMAND_ATTACH_FS
4102 /* block if someone else is performing an exclusive op on this volume */
4105 VCreateReservation_r(rvp);
4107 VWaitExclusiveState_r(vp);
4109 /* short circuit with VNOVOL in the following circumstances:
4112 * - VOL_STATE_SHUTTING_DOWN
4114 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4115 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4122 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4123 * VNOVOL for VOL_STATE_DELETED
4125 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4126 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4127 (V_attachState(vp) == VOL_STATE_DELETED)) {
4128 if (vp->specialStatus) {
4129 *ec = vp->specialStatus;
4130 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4139 /* allowable states:
4146 if (vp->salvage.requested) {
4147 VUpdateSalvagePriority_r(vp);
4150 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4151 if (vp->specialStatus) {
4152 *ec = vp->specialStatus;
4156 avp = VAttachVolumeByVp_r(ec, vp, 0);
4159 /* VAttachVolumeByVp_r can return a pointer
4160 * != the vp passed to it under certain
4161 * conditions; make sure we don't leak
4162 * reservations if that happens */
4164 VCancelReservation_r(rvp);
4166 VCreateReservation_r(rvp);
4177 if (vp->specialStatus) {
4178 *ec = vp->specialStatus;
4183 if (vp->specialStatus) {
4184 *ec = vp->specialStatus;
4197 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4199 /* see CheckVnode() in afsfileprocs.c for an explanation
4200 * of this error code logic */
4201 afs_uint32 now = FT_ApproxTime();
4202 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4205 *client_ec = VRESTARTING;
4213 if (VIsErrorState(V_attachState(vp))) {
4214 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4215 * it, or transition it out of that state */
4224 * this test MUST happen after VAttachVolymeByVp, so we have no
4225 * conflicting vol op. (attach2 would have errored out if we had one;
4226 * specifically attach_check_vop must have detected a conflicting vop)
4228 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4230 #endif /* AFS_DEMAND_ATTACH_FS */
4232 LoadVolumeHeader(ec, vp);
4235 /* Only log the error if it was a totally unexpected error. Simply
4236 * a missing inode is likely to be caused by the volume being deleted */
4237 if (errno != ENXIO || GetLogLevel() != 0)
4238 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4239 afs_printable_VolumeId_lu(vp->hashid));
4240 #ifdef AFS_DEMAND_ATTACH_FS
4241 if (VCanScheduleSalvage()) {
4242 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4247 #else /* AFS_DEMAND_ATTACH_FS */
4250 #endif /* AFS_DEMAND_ATTACH_FS */
4255 if (vp->shuttingDown) {
4262 if (programType == fileServer) {
4264 if (vp->goingOffline) {
4265 if (timeout && VTimedOut(timeout)) {
4266 /* we've timed out; don't wait for the vol */
4269 #ifdef AFS_DEMAND_ATTACH_FS
4270 /* wait for the volume to go offline */
4271 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4272 VTimedWaitStateChange_r(vp, timeout, NULL);
4274 #elif defined(AFS_PTHREAD_ENV)
4275 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4276 #else /* AFS_PTHREAD_ENV */
4277 /* LWP has no timed wait, so the caller better not be
4279 opr_Assert(!timeout);
4280 LWP_WaitProcess(VPutVolume);
4281 #endif /* AFS_PTHREAD_ENV */
4285 if (vp->specialStatus) {
4287 *ec = vp->specialStatus;
4288 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4291 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4302 #ifdef AFS_DEMAND_ATTACH_FS
4303 /* if no error, bump nUsers */
4306 VLRU_UpdateAccess_r(vp);
4309 VCancelReservation_r(rvp);
4312 if (client_ec && !*client_ec) {
4315 #else /* AFS_DEMAND_ATTACH_FS */
4316 /* if no error, bump nUsers */
4323 #endif /* AFS_DEMAND_ATTACH_FS */
4326 opr_Assert(vp || *ec);
4331 /***************************************************/
4332 /* Volume offline/detach routines */
4333 /***************************************************/
4335 /* caller MUST hold a heavyweight ref on vp */
4336 #ifdef AFS_DEMAND_ATTACH_FS
4338 VTakeOffline_r(Volume * vp)
4342 opr_Assert(vp->nUsers > 0);
4343 opr_Assert(programType == fileServer);
4345 VCreateReservation_r(vp);
4346 VWaitExclusiveState_r(vp);
4348 vp->goingOffline = 1;
4349 V_needsSalvaged(vp) = 1;
4351 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4352 VCancelReservation_r(vp);
4354 #else /* AFS_DEMAND_ATTACH_FS */
4356 VTakeOffline_r(Volume * vp)
4358 opr_Assert(vp->nUsers > 0);
4359 opr_Assert(programType == fileServer);
4361 vp->goingOffline = 1;
4362 V_needsSalvaged(vp) = 1;
4364 #endif /* AFS_DEMAND_ATTACH_FS */
4367 VTakeOffline(Volume * vp)
4375 * force a volume offline.
4377 * @param[in] vp volume object pointer
4378 * @param[in] flags flags (see note below)
4380 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4381 * used when VUpdateVolume_r needs to call VForceOffline_r
4382 * (which in turn would normally call VUpdateVolume_r)
4384 * @see VUpdateVolume_r
4386 * @pre VOL_LOCK must be held.
4387 * for DAFS, caller must hold ref.
4389 * @note for DAFS, it _is safe_ to call this function from an
4392 * @post needsSalvaged flag is set.
4393 * for DAFS, salvage is requested.
4394 * no further references to the volume through the volume
4395 * package will be honored.
4396 * all file descriptor and vnode caches are invalidated.
4398 * @warning this is a heavy-handed interface. it results in
4399 * a volume going offline regardless of the current
4400 * reference count state.
4402 * @internal volume package internal use only
4405 VForceOffline_r(Volume * vp, int flags)
4409 #ifdef AFS_DEMAND_ATTACH_FS
4410 VChangeState_r(vp, VOL_STATE_ERROR);
4415 strcpy(V_offlineMessage(vp),
4416 "Forced offline due to internal error: volume needs to be salvaged");
4417 Log("Volume %" AFS_VOLID_FMT " forced offline: it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4420 vp->goingOffline = 0;
4421 V_needsSalvaged(vp) = 1;
4422 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4423 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4426 #ifdef AFS_DEMAND_ATTACH_FS
4427 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4428 #endif /* AFS_DEMAND_ATTACH_FS */
4430 #ifdef AFS_PTHREAD_ENV
4431 opr_cv_broadcast(&vol_put_volume_cond);
4432 #else /* AFS_PTHREAD_ENV */
4433 LWP_NoYieldSignal(VPutVolume);
4434 #endif /* AFS_PTHREAD_ENV */
4436 VReleaseVolumeHandles_r(vp);
4440 * force a volume offline.
4442 * @param[in] vp volume object pointer
4444 * @see VForceOffline_r
4447 VForceOffline(Volume * vp)
4450 VForceOffline_r(vp, 0);
4455 * Iterate over the RX calls associated with a volume, and interrupt them.
4457 * @param[in] vp The volume whose RX calls we want to scan
4459 * @pre VOL_LOCK held
4462 VScanCalls_r(struct Volume *vp)
4464 struct VCallByVol *cbv, *ncbv;
4466 #ifdef AFS_DEMAND_ATTACH_FS
4467 VolState state_save;
4470 if (queue_IsEmpty(&vp->rx_call_list))
4471 return; /* no calls to interrupt */
4472 if (!vol_opts.interrupt_rxcall)
4473 return; /* we have no function with which to interrupt calls */
4474 err = VIsGoingOffline_r(vp);
4476 return; /* we're not going offline anymore */
4478 #ifdef AFS_DEMAND_ATTACH_FS
4479 VWaitExclusiveState_r(vp);
4480 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4482 #endif /* AFS_DEMAND_ATTACH_FS */
4484 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4485 if (GetLogLevel() != 0) {
4486 struct rx_peer *peer;
4488 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4490 Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4491 "from it; kicking client off with error %ld\n",
4492 afs_printable_VolumeId_lu(vp->hashid),
4493 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4494 (unsigned) ntohs(rx_PortOf(peer)),
4497 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4500 #ifdef AFS_DEMAND_ATTACH_FS
4502 VChangeState_r(vp, state_save);
4503 #endif /* AFS_DEMAND_ATTACH_FS */
4506 #ifdef AFS_DEMAND_ATTACH_FS
4508 * Wait for a vp to go offline.
4510 * @param[out] ec 1 if a salvage on the volume has been requested and
4511 * salvok == 0, 0 otherwise
4512 * @param[in] vp The volume to wait for
4513 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4514 * has been requested to salvage. Otherwise we keep waiting
4515 * until the volume has gone offline.
4517 * @pre VOL_LOCK held
4518 * @pre caller holds a lightweight ref on vp
4523 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4525 struct timespec timeout_ts;
4526 const struct timespec *ts;
4529 ts = VOfflineTimeout(&timeout_ts);
4533 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4534 if (!salvok && vp->salvage.requested) {
4538 VTimedWaitStateChange_r(vp, ts, &timedout);
4541 /* we didn't time out, so the volume must be offline, so we're done */
4545 /* If we got here, we timed out waiting for the volume to go offline.
4546 * Kick off the accessing RX calls and wait again */
4550 while (!VIsOfflineState(V_attachState(vp))) {
4551 if (!salvok && vp->salvage.requested) {
4556 VWaitStateChange_r(vp);
4560 #else /* AFS_DEMAND_ATTACH_FS */
4563 * Wait for a volume to go offline.
4565 * @pre VOL_LOCK held
4567 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4570 VWaitForOffline_r(Error *ec, VolumeId volid)
4573 const struct timespec *ts;
4574 #ifdef AFS_PTHREAD_ENV
4575 struct timespec timeout_ts;
4578 ts = VOfflineTimeout(&timeout_ts);
4580 vp = GetVolume(ec, NULL, volid, NULL, ts);
4582 /* error occurred so bad that we can't even get a vp; we have no
4583 * information on the vol so we don't know whether to wait, so just
4587 if (!VIsGoingOffline_r(vp)) {
4588 /* volume is no longer going offline, so we're done */
4593 /* If we got here, we timed out waiting for the volume to go offline.
4594 * Kick off the accessing RX calls and wait again */
4600 vp = VGetVolume_r(ec, volid);
4602 /* In case it was reattached... */
4606 #endif /* !AFS_DEMAND_ATTACH_FS */
4608 /* The opposite of VAttachVolume. The volume header is written to disk, with
4609 the inUse bit turned off. A copy of the header is maintained in memory,
4610 however (which is why this is VOffline, not VDetach).
4613 VOffline_r(Volume * vp, char *message)
4616 #ifndef AFS_DEMAND_ATTACH_FS
4617 VolumeId vid = V_id(vp);
4620 opr_Assert(programType != volumeUtility && programType != volumeServer);
4625 if (V_offlineMessage(vp)[0] == '\0')
4626 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4627 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4629 vp->goingOffline = 1;
4630 #ifdef AFS_DEMAND_ATTACH_FS
4631 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4632 VCreateReservation_r(vp);
4634 VWaitForOfflineByVp_r(&error, vp, 1);
4635 VCancelReservation_r(vp);
4636 #else /* AFS_DEMAND_ATTACH_FS */
4638 VWaitForOffline_r(&error, vid);
4639 #endif /* AFS_DEMAND_ATTACH_FS */
4642 #ifdef AFS_DEMAND_ATTACH_FS
4644 * Take a volume offline in order to perform a volume operation.
4646 * @param[inout] ec address in which to store error code
4647 * @param[in] vp volume object pointer
4648 * @param[in] message volume offline status message
4651 * - VOL_LOCK is held
4652 * - caller MUST hold a heavyweight ref on vp
4655 * - volume is taken offline
4656 * - if possible, volume operation is promoted to running state
4657 * - on failure, *ec is set to nonzero
4659 * @note Although this function does not return any value, it may
4660 * still fail to promote our pending volume operation to
4661 * a running state. Any caller MUST check the value of *ec,
4662 * and MUST NOT blindly assume success.
4664 * @warning if the caller does not hold a lightweight ref on vp,
4665 * then it MUST NOT reference vp after this function
4666 * returns to the caller.
4668 * @internal volume package internal use only
4671 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4674 opr_Assert(vp->pending_vol_op);
4680 if (V_offlineMessage(vp)[0] == '\0')
4681 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4682 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4684 vp->goingOffline = 1;
4685 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4686 VCreateReservation_r(vp);
4689 if (vp->pending_vol_op->com.programType != salvageServer) {
4690 /* do not give corrupted volumes to the volserver */
4695 VWaitForOfflineByVp_r(ec, vp, salvok);
4697 VCancelReservation_r(vp);
4699 #endif /* AFS_DEMAND_ATTACH_FS */
4702 VOffline(Volume * vp, char *message)
4705 VOffline_r(vp, message);
4709 /* This gets used for the most part by utility routines that don't want
4710 * to keep all the volume headers around. Generally, the file server won't
4711 * call this routine, because then the offline message in the volume header
4712 * (or other information) won't be available to clients. For NAMEI, also
4713 * close the file handles. However, the fileserver does call this during
4714 * an attach following a volume operation.
4717 VDetachVolume_r(Error * ec, Volume * vp)
4719 #ifdef FSSYNC_BUILD_CLIENT
4721 struct DiskPartition64 *tpartp;
4722 int notifyServer = 0;
4723 int useDone = FSYNC_VOL_ON;
4725 if (VCanUseFSSYNC()) {
4726 notifyServer = vp->needsPutBack;
4727 if (V_destroyMe(vp) == DESTROY_ME)
4728 useDone = FSYNC_VOL_LEAVE_OFF;
4729 # ifdef AFS_DEMAND_ATTACH_FS
4730 else if (!V_blessed(vp) || !V_inService(vp))
4731 useDone = FSYNC_VOL_LEAVE_OFF;
4734 # ifdef AFS_DEMAND_ATTACH_FS
4735 if (V_needsSalvaged(vp)) {
4737 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4740 tpartp = vp->partition;
4742 #endif /* FSSYNC_BUILD_CLIENT */
4744 *ec = 0; /* always "succeeds" */
4745 DeleteVolumeFromHashTable(vp);
4746 vp->shuttingDown = 1;
4747 #ifdef AFS_DEMAND_ATTACH_FS
4748 DeleteVolumeFromVByPList_r(vp);
4750 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4752 if (programType != fileServer)
4754 #endif /* AFS_DEMAND_ATTACH_FS */
4756 /* Will be detached sometime in the future--this is OK since volume is offline */
4758 /* XXX the following code should really be moved to VCheckDetach() since the volume
4759 * is not technically detached until the refcounts reach zero
4761 #ifdef FSSYNC_BUILD_CLIENT
4762 if (VCanUseFSSYNC() && notifyServer) {
4763 if (notifyServer == VOL_PUTBACK_DELETE) {
4764 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4765 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4766 * to signify a deleted volume. */
4767 useDone = FSYNC_VOL_DONE;
4770 * Note: The server is not notified in the case of a bogus volume
4771 * explicitly to make it possible to create a volume, do a partial
4772 * restore, then abort the operation without ever putting the volume
4773 * online. This is essential in the case of a volume move operation
4774 * between two partitions on the same server. In that case, there
4775 * would be two instances of the same volume, one of them bogus,
4776 * which the file server would attempt to put on line
4778 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4779 /* XXX this code path is only hit by volume utilities, thus
4780 * V_BreakVolumeCallbacks will always be NULL. if we really
4781 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4783 /* Dettaching it so break all callbacks on it */
4784 if (V_BreakVolumeCallbacks) {
4785 Log("volume %u detached; breaking all call backs\n", volume);
4786 (*V_BreakVolumeCallbacks) (volume);
4790 #endif /* FSSYNC_BUILD_CLIENT */
4794 VDetachVolume(Error * ec, Volume * vp)
4797 VDetachVolume_r(ec, vp);
4802 /***************************************************/
4803 /* Volume fd/inode handle closing routines */
4804 /***************************************************/
4806 /* For VDetachVolume, we close all cached file descriptors, but keep
4807 * the Inode handles in case we need to read from a busy volume.
4809 /* for demand attach, caller MUST hold ref count on vp */
4811 VCloseVolumeHandles_r(Volume * vp)
4813 #ifdef AFS_DEMAND_ATTACH_FS
4814 VolState state_save;
4816 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4821 DFlushVolume(vp->hashid);
4823 #ifdef AFS_DEMAND_ATTACH_FS
4827 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4828 VCloseVnodeFiles_r(vp);
4830 #ifdef AFS_DEMAND_ATTACH_FS
4834 /* Too time consuming and unnecessary for the volserver */
4835 if (programType == fileServer) {
4836 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4837 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4838 IH_CONDSYNC(vp->diskDataHandle);
4839 #ifdef AFS_NAMEI_ENV
4840 IH_CONDSYNC(vp->linkHandle);
4841 #endif /* AFS_NAMEI_ENV */
4844 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4845 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4846 IH_REALLYCLOSE(vp->diskDataHandle);
4847 IH_REALLYCLOSE(vp->linkHandle);
4849 #ifdef AFS_DEMAND_ATTACH_FS
4850 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4855 VChangeState_r(vp, state_save);
4859 /* For both VForceOffline and VOffline, we close all relevant handles.
4860 * For VOffline, if we re-attach the volume, the files may possible be
4861 * different than before.
4863 /* for demand attach, caller MUST hold a ref count on vp */
4865 VReleaseVolumeHandles_r(Volume * vp)
4867 #ifdef AFS_DEMAND_ATTACH_FS
4868 VolState state_save;
4870 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4875 DFlushVolume(vp->hashid);
4877 #ifdef AFS_DEMAND_ATTACH_FS
4881 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4883 #ifdef AFS_DEMAND_ATTACH_FS
4887 /* Too time consuming and unnecessary for the volserver */
4888 if (programType == fileServer) {
4889 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4890 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4891 IH_CONDSYNC(vp->diskDataHandle);
4892 #ifdef AFS_NAMEI_ENV
4893 IH_CONDSYNC(vp->linkHandle);
4894 #endif /* AFS_NAMEI_ENV */
4897 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4898 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4899 IH_RELEASE(vp->diskDataHandle);
4900 IH_RELEASE(vp->linkHandle);
4902 #ifdef AFS_DEMAND_ATTACH_FS
4903 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4908 VChangeState_r(vp, state_save);
4913 /***************************************************/
4914 /* Volume write and fsync routines */
4915 /***************************************************/
4918 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4920 #ifdef AFS_DEMAND_ATTACH_FS
4921 VolState state_save;
4923 if (flags & VOL_UPDATE_WAIT) {
4924 VCreateReservation_r(vp);
4925 VWaitExclusiveState_r(vp);
4930 if (programType == fileServer) {
4932 V_uniquifier(vp) = V_nextVnodeUnique(vp);
4935 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4936 if (V_uniquifier(vp) < V_nextVnodeUnique(vp)) {
4937 /* uniquifier rolled over; reset the counters */
4938 V_nextVnodeUnique(vp) = 2; /* 1 is reserved for the root vnode */
4940 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4945 #ifdef AFS_DEMAND_ATTACH_FS
4946 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4950 WriteVolumeHeader_r(ec, vp);
4952 #ifdef AFS_DEMAND_ATTACH_FS
4954 VChangeState_r(vp, state_save);
4955 if (flags & VOL_UPDATE_WAIT) {
4956 VCancelReservation_r(vp);
4961 Log("VUpdateVolume: error updating volume header, volume %" AFS_VOLID_FMT " (%s)\n",
4962 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
4963 /* try to update on-disk header,
4964 * while preventing infinite recursion */
4965 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4966 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4972 VUpdateVolume(Error * ec, Volume * vp)
4975 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4980 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4984 #ifdef AFS_DEMAND_ATTACH_FS
4985 VolState state_save;
4988 if (flags & VOL_SYNC_WAIT) {
4989 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4991 VUpdateVolume_r(ec, vp, 0);
4994 #ifdef AFS_DEMAND_ATTACH_FS
4995 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4998 fdP = IH_OPEN(V_diskDataHandle(vp));
4999 opr_Assert(fdP != NULL);
5000 code = FDH_SYNC(fdP);
5001 opr_Assert(code == 0);
5003 #ifdef AFS_DEMAND_ATTACH_FS
5005 VChangeState_r(vp, state_save);
5011 VSyncVolume(Error * ec, Volume * vp)
5014 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
5019 /***************************************************/
5020 /* Volume dealloaction routines */
5021 /***************************************************/
5023 #ifdef AFS_DEMAND_ATTACH_FS
5025 FreeVolume(Volume * vp)
5027 /* free the heap space, iff it's safe.
5028 * otherwise, pull it out of the hash table, so it
5029 * will get deallocated when all refs to it go away */
5030 if (!VCheckFree(vp)) {
5031 DeleteVolumeFromHashTable(vp);
5032 DeleteVolumeFromVByPList_r(vp);
5034 /* make sure we invalidate the header cache entry */
5035 FreeVolumeHeader(vp);
5038 #endif /* AFS_DEMAND_ATTACH_FS */
5041 ReallyFreeVolume(Volume * vp)
5046 #ifdef AFS_DEMAND_ATTACH_FS
5048 VChangeState_r(vp, VOL_STATE_FREED);
5049 if (vp->pending_vol_op)
5050 free(vp->pending_vol_op);
5051 #endif /* AFS_DEMAND_ATTACH_FS */
5052 for (i = 0; i < nVNODECLASSES; i++)
5053 if (vp->vnodeIndex[i].bitmap)
5054 free(vp->vnodeIndex[i].bitmap);
5055 FreeVolumeHeader(vp);
5056 #ifndef AFS_DEMAND_ATTACH_FS
5057 DeleteVolumeFromHashTable(vp);
5058 #endif /* AFS_DEMAND_ATTACH_FS */
5062 /* check to see if we should shutdown this volume
5063 * returns 1 if volume was freed, 0 otherwise */
5064 #ifdef AFS_DEMAND_ATTACH_FS
5066 VCheckDetach(Volume * vp)
5071 if (vp->nUsers || vp->nWaiters)
5074 if (vp->shuttingDown) {
5076 if ((programType != fileServer) &&
5077 (V_inUse(vp) == programType) &&
5078 ((V_checkoutMode(vp) == V_VOLUPD) ||
5079 (V_checkoutMode(vp) == V_SECRETLY) ||
5080 ((V_checkoutMode(vp) == V_CLONE) &&
5081 (VolumeWriteable(vp))))) {
5083 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5085 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " "
5086 "failed with errno %d\n", afs_printable_VolumeId_lu(vp->hashid), errno);
5089 VReleaseVolumeHandles_r(vp);
5091 ReallyFreeVolume(vp);
5092 if (programType == fileServer) {
5093 opr_cv_broadcast(&vol_put_volume_cond);
5098 #else /* AFS_DEMAND_ATTACH_FS */
5100 VCheckDetach(Volume * vp)
5108 if (vp->shuttingDown) {
5110 if ((programType != fileServer) &&
5111 (V_inUse(vp) == programType) &&
5112 ((V_checkoutMode(vp) == V_VOLUPD) ||
5113 (V_checkoutMode(vp) == V_SECRETLY) ||
5114 ((V_checkoutMode(vp) == V_CLONE) &&
5115 (VolumeWriteable(vp))))) {
5117 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5119 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " failed with errno %d\n",
5120 afs_printable_VolumeId_lu(vp->hashid), errno);
5123 VReleaseVolumeHandles_r(vp);
5124 ReallyFreeVolume(vp);
5125 if (programType == fileServer) {
5126 #if defined(AFS_PTHREAD_ENV)
5127 opr_cv_broadcast(&vol_put_volume_cond);
5128 #else /* AFS_PTHREAD_ENV */
5129 LWP_NoYieldSignal(VPutVolume);
5130 #endif /* AFS_PTHREAD_ENV */
5135 #endif /* AFS_DEMAND_ATTACH_FS */
5137 /* check to see if we should offline this volume
5138 * return 1 if volume went offline, 0 otherwise */
5139 #ifdef AFS_DEMAND_ATTACH_FS
5141 VCheckOffline(Volume * vp)
5145 if (vp->goingOffline && !vp->nUsers) {
5147 opr_Assert(programType == fileServer);
5148 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5149 (V_attachState(vp) != VOL_STATE_FREED) &&
5150 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5151 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5152 (V_attachState(vp) != VOL_STATE_DELETED));
5156 * VOL_STATE_GOING_OFFLINE
5157 * VOL_STATE_SHUTTING_DOWN
5158 * VIsErrorState(V_attachState(vp))
5159 * VIsExclusiveState(V_attachState(vp))
5162 VCreateReservation_r(vp);
5163 VChangeState_r(vp, VOL_STATE_OFFLINING);
5166 /* must clear the goingOffline flag before we drop the glock */
5167 vp->goingOffline = 0;
5172 /* perform async operations */
5173 VUpdateVolume_r(&error, vp, 0);
5174 VCloseVolumeHandles_r(vp);
5176 if (GetLogLevel() != 0) {
5177 if (V_offlineMessage(vp)[0]) {
5178 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5179 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5180 V_offlineMessage(vp));
5182 Log("VOffline: Volume %lu (%s) is now offline\n",
5183 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5187 /* invalidate the volume header cache entry */
5188 FreeVolumeHeader(vp);
5190 /* if nothing changed state to error or salvaging,
5191 * drop state to unattached */
5192 if (!VIsErrorState(V_attachState(vp))) {
5193 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5195 VCancelReservation_r(vp);
5196 /* no usage of vp is safe beyond this point */
5200 #else /* AFS_DEMAND_ATTACH_FS */
5202 VCheckOffline(Volume * vp)
5206 if (vp->goingOffline && !vp->nUsers) {
5208 opr_Assert(programType == fileServer);
5211 vp->goingOffline = 0;
5213 VUpdateVolume_r(&error, vp, 0);
5214 VCloseVolumeHandles_r(vp);
5215 if (GetLogLevel() != 0) {
5216 if (V_offlineMessage(vp)[0]) {
5217 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5218 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5219 V_offlineMessage(vp));
5221 Log("VOffline: Volume %lu (%s) is now offline\n",
5222 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5225 FreeVolumeHeader(vp);
5226 #ifdef AFS_PTHREAD_ENV
5227 opr_cv_broadcast(&vol_put_volume_cond);
5228 #else /* AFS_PTHREAD_ENV */
5229 LWP_NoYieldSignal(VPutVolume);
5230 #endif /* AFS_PTHREAD_ENV */
5234 #endif /* AFS_DEMAND_ATTACH_FS */
5236 /***************************************************/
5237 /* demand attach fs ref counting routines */
5238 /***************************************************/
5240 #ifdef AFS_DEMAND_ATTACH_FS
5241 /* the following two functions handle reference counting for
5242 * asynchronous operations on volume structs.
5244 * their purpose is to prevent a VDetachVolume or VShutdown
5245 * from free()ing the Volume struct during an async i/o op */
5247 /* register with the async volume op ref counter */
5248 /* VCreateReservation_r moved into inline code header because it
5249 * is now needed in vnode.c -- tkeiser 11/20/2007
5253 * decrement volume-package internal refcount.
5255 * @param vp volume object pointer
5257 * @internal volume package internal use only
5260 * @arg VOL_LOCK is held
5261 * @arg lightweight refcount held
5263 * @post volume waiters refcount is decremented; volume may
5264 * have been deallocated/shutdown/offlined/salvaged/
5265 * whatever during the process
5267 * @warning once you have tossed your last reference (you can acquire
5268 * lightweight refs recursively) it is NOT SAFE to reference
5269 * a volume object pointer ever again
5271 * @see VCreateReservation_r
5273 * @note DEMAND_ATTACH_FS only
5276 VCancelReservation_r(Volume * vp)
5278 opr_Verify(--vp->nWaiters >= 0);
5279 if (vp->nWaiters == 0) {
5281 if (!VCheckDetach(vp)) {
5288 /* check to see if we should free this volume now
5289 * return 1 if volume was freed, 0 otherwise */
5291 VCheckFree(Volume * vp)
5294 if ((vp->nUsers == 0) &&
5295 (vp->nWaiters == 0) &&
5296 !(V_attachFlags(vp) & (VOL_IN_HASH |
5300 ReallyFreeVolume(vp);
5305 #endif /* AFS_DEMAND_ATTACH_FS */
5308 /***************************************************/
5309 /* online volume operations routines */
5310 /***************************************************/
5312 #ifdef AFS_DEMAND_ATTACH_FS
5314 * register a volume operation on a given volume.
5316 * @param[in] vp volume object
5317 * @param[in] vopinfo volume operation info object
5319 * @pre VOL_LOCK is held
5321 * @post volume operation info object attached to volume object.
5322 * volume operation statistics updated.
5324 * @note by "attached" we mean a copy of the passed in object is made
5326 * @internal volume package internal use only
5329 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5331 FSSYNC_VolOp_info * info;
5333 /* attach a vol op info node to the volume struct */
5334 info = malloc(sizeof(FSSYNC_VolOp_info));
5335 opr_Assert(info != NULL);
5336 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5337 vp->pending_vol_op = info;
5340 vp->stats.last_vol_op = FT_ApproxTime();
5341 vp->stats.vol_ops++;
5342 IncUInt64(&VStats.vol_ops);
5348 * deregister the volume operation attached to this volume.
5350 * @param[in] vp volume object pointer
5352 * @pre VOL_LOCK is held
5354 * @post the volume operation info object is detached from the volume object
5356 * @internal volume package internal use only
5359 VDeregisterVolOp_r(Volume * vp)
5361 if (vp->pending_vol_op) {
5362 free(vp->pending_vol_op);
5363 vp->pending_vol_op = NULL;
5367 #endif /* AFS_DEMAND_ATTACH_FS */
5370 * determine whether it is safe to leave a volume online during
5371 * the volume operation described by the vopinfo object.
5373 * @param[in] vp volume object
5374 * @param[in] vopinfo volume operation info object
5376 * @return whether it is safe to leave volume online
5377 * @retval 0 it is NOT SAFE to leave the volume online
5378 * @retval 1 it is safe to leave the volume online during the operation
5381 * @arg VOL_LOCK is held
5382 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5383 * this condition is met)
5385 * @internal volume package internal use only
5388 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5390 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5391 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5392 (vopinfo->com.reason == V_READONLY ||
5393 (!VolumeWriteable(vp) &&
5394 (vopinfo->com.reason == V_CLONE ||
5395 vopinfo->com.reason == V_DUMP)))));
5399 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5402 * @param[in] vp volume object
5403 * @param[in] vopinfo volume operation info object
5405 * @return whether it is safe to leave volume online
5406 * @retval 0 it is NOT SAFE to leave the volume online
5407 * @retval 1 it is safe to leave the volume online during the operation
5408 * @retval -1 unsure; volume header is required in order to know whether or
5409 * not is is safe to leave the volume online
5411 * @pre VOL_LOCK is held
5413 * @internal volume package internal use only
5416 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5418 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5419 * assume that we don't know VolumeWriteable; return -1 if the answer
5420 * depends on VolumeWriteable */
5422 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5425 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5426 vopinfo->com.reason == V_READONLY) {
5430 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5431 (vopinfo->com.reason == V_CLONE ||
5432 vopinfo->com.reason == V_DUMP)) {
5434 /* must know VolumeWriteable */
5441 * determine whether VBUSY should be set during this volume operation.
5443 * @param[in] vp volume object
5444 * @param[in] vopinfo volume operation info object
5446 * @return whether VBUSY should be set
5447 * @retval 0 VBUSY does NOT need to be set
5448 * @retval 1 VBUSY SHOULD be set
5450 * @pre VOL_LOCK is held
5452 * @internal volume package internal use only
5455 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5457 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5458 vopinfo->com.reason == FSYNC_SALVAGE) ||
5459 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5460 (vopinfo->com.reason == V_CLONE ||
5461 vopinfo->com.reason == V_DUMP)));
5465 /***************************************************/
5466 /* online salvager routines */
5467 /***************************************************/
5468 #if defined(AFS_DEMAND_ATTACH_FS)
5471 * offline a volume to let it be salvaged.
5473 * @param[in] vp Volume to offline
5475 * @return whether we offlined the volume successfully
5476 * @retval 0 volume was not offlined
5477 * @retval 1 volume is now offline
5479 * @note This is similar to VCheckOffline, but slightly different. We do not
5480 * deal with vp->goingOffline, and we try to avoid touching the volume
5481 * header except just to set needsSalvaged
5483 * @pre VOL_LOCK held
5484 * @pre vp->nUsers == 0
5485 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5488 VOfflineForSalvage_r(struct Volume *vp)
5492 VCreateReservation_r(vp);
5493 VWaitExclusiveState_r(vp);
5495 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5496 /* Someone's using the volume, or someone got to scheduling the salvage
5497 * before us. I don't think either of these should be possible, as we
5498 * should gain no new heavyweight references while we're trying to
5499 * salvage, but just to be sure... */
5500 VCancelReservation_r(vp);
5504 VChangeState_r(vp, VOL_STATE_OFFLINING);
5508 V_needsSalvaged(vp) = 1;
5509 /* ignore error; updating needsSalvaged is just best effort */
5510 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5512 VCloseVolumeHandles_r(vp);
5514 FreeVolumeHeader(vp);
5516 /* volume has been effectively offlined; we can mark it in the SALVAGING
5517 * state now, which lets FSSYNC give it away */
5518 VChangeState_r(vp, VOL_STATE_SALVAGING);
5520 VCancelReservation_r(vp);
5526 * check whether a salvage needs to be performed on this volume.
5528 * @param[in] vp pointer to volume object
5530 * @return status code
5531 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5532 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5533 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5534 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5535 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5537 * @pre VOL_LOCK is held
5539 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5540 * then a salvage will be requested
5542 * @note this is one of the event handlers called by VCancelReservation_r
5544 * @note the caller must check if the volume needs to be freed after calling
5545 * this; the volume may not have any references or be on any lists after
5546 * we return, and we do not free it
5548 * @see VCancelReservation_r
5550 * @internal volume package internal use only.
5553 VCheckSalvage(Volume * vp)
5555 int ret = VCHECK_SALVAGE_OK;
5557 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5558 if (!vp->salvage.requested) {
5559 return VCHECK_SALVAGE_OK;
5562 return VCHECK_SALVAGE_ASYNC;
5565 /* prevent recursion; some of the code below creates and removes
5566 * lightweight refs, which can call VCheckSalvage */
5567 if (vp->salvage.scheduling) {
5568 return VCHECK_SALVAGE_ASYNC;
5570 vp->salvage.scheduling = 1;
5572 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5573 if (!VOfflineForSalvage_r(vp)) {
5574 vp->salvage.scheduling = 0;
5575 return VCHECK_SALVAGE_FAIL;
5579 if (vp->salvage.requested) {
5580 ret = VScheduleSalvage_r(vp);
5582 vp->salvage.scheduling = 0;
5583 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5588 * request volume salvage.
5590 * @param[out] ec computed client error code
5591 * @param[in] vp volume object pointer
5592 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5593 * @param[in] flags see flags note below
5596 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5597 * not been fully attached
5599 * @pre VOL_LOCK is held.
5601 * @post volume state is changed.
5602 * for fileserver, salvage will be requested once refcount reaches zero.
5604 * @return operation status code
5605 * @retval 0 volume salvage will occur
5606 * @retval 1 volume salvage could not be scheduled
5610 * @note in the fileserver, this call does not synchronously schedule a volume
5611 * salvage. rather, it sets volume state so that when volume refcounts
5612 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5613 * nUsers and nWaiters must be zero.
5615 * @internal volume package internal use only.
5618 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5622 * for DAFS volume utilities that are not supposed to schedule salvages,
5623 * just transition to error state instead
5625 if (!VCanScheduleSalvage()) {
5626 VChangeState_r(vp, VOL_STATE_ERROR);
5631 if (programType != fileServer && !VCanUseFSSYNC()) {
5632 VChangeState_r(vp, VOL_STATE_ERROR);
5637 if (!vp->salvage.requested) {
5638 vp->salvage.requested = 1;
5639 vp->salvage.reason = reason;
5640 vp->stats.last_salvage = FT_ApproxTime();
5642 /* Note that it is not possible for us to reach this point if a
5643 * salvage is already running on this volume (even if the fileserver
5644 * was restarted during the salvage). If a salvage were running, the
5645 * salvager would have write-locked the volume header file, so when
5646 * we tried to lock the volume header, the lock would have failed,
5647 * and we would have failed during attachment prior to calling
5648 * VRequestSalvage. So we know that we can schedule salvages without
5649 * fear of a salvage already running for this volume. */
5651 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5653 /* if we don't need to offline the volume, we can go directly
5654 * to SALVAGING. SALVAGING says the volume is offline and is
5655 * either salvaging or ready to be handed to the salvager.
5656 * SALVAGE_REQ says that we want to salvage the volume, but we
5657 * are waiting for it to go offline first. */
5658 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5659 VChangeState_r(vp, VOL_STATE_SALVAGING);
5661 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5662 if (vp->nUsers == 0) {
5663 /* normally VOfflineForSalvage_r would be called from
5664 * PutVolume et al when nUsers reaches 0, but if
5665 * it's already 0, just do it ourselves, since PutVolume
5666 * isn't going to get called */
5667 VOfflineForSalvage_r(vp);
5670 /* If we are non-fileserver, we're telling the fileserver to
5671 * salvage the vol, so we don't need to give it back separately. */
5672 vp->needsPutBack = 0;
5676 Log("VRequestSalvage: volume %" AFS_VOLID_FMT " online salvaged too many times; forced offline.\n", afs_printable_VolumeId_lu(vp->hashid));
5678 /* make sure neither VScheduleSalvage_r nor
5679 * VUpdateSalvagePriority_r try to schedule another salvage */
5680 vp->salvage.requested = vp->salvage.scheduled = 0;
5682 VChangeState_r(vp, VOL_STATE_ERROR);
5686 if ((flags & VOL_SALVAGE_NO_OFFLINE)) {
5687 /* Here, we free the header for the volume, but make sure to only
5688 * do this if VOL_SALVAGE_NO_OFFLINE is specified. The reason for
5689 * this requires a bit of explanation.
5691 * Normally, the volume header will be freed when the volume goes
5692 * goes offline. However, if VOL_SALVAGE_NO_OFFLINE has been
5693 * specified, the volume was in the process of being attached when
5694 * we discovered that it needed salvaging. Thus, the volume will
5695 * never go offline, since it never went fully online in the first
5696 * place. Specifically, we do not call VOfflineForSalvage_r above,
5697 * and we never get rid of the volume via VPutVolume_r; the volume
5698 * has not been initialized enough for those to work.
5700 * So instead, explicitly free the volume header here. If we do not
5701 * do this, we are wasting a header that some other volume could be
5702 * using, since the header remains attached to the volume. Also if
5703 * we do not free the header here, we end up with a volume where
5704 * nUsers == 0, but the volume has a header that is not on the
5705 * header LRU. Some code expects that all nUsers == 0 volumes have
5706 * their header on the header LRU (or have no header).
5708 * Also note that we must not free the volume header here if
5709 * VOL_SALVAGE_NO_OFFLINE is not set. Since, if
5710 * VOL_SALVAGE_NO_OFFLINE is not set, someone else may have a
5711 * reference to this volume, and they assume they can use the
5712 * volume's header. If we free the volume out from under them, they
5713 * can easily segfault.
5715 FreeVolumeHeader(vp);
5722 * update salvageserver scheduling priority for a volume.
5724 * @param[in] vp pointer to volume object
5726 * @return operation status
5728 * @retval 1 request denied, or SALVSYNC communications failure
5730 * @pre VOL_LOCK is held.
5732 * @post in-core salvage priority counter is incremented. if at least
5733 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5734 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5735 * to update its priority queue. if no salvage is scheduled,
5736 * this function is a no-op.
5738 * @note DAFS fileserver only
5740 * @note this should be called whenever a VGetVolume fails due to a
5741 * pending salvage request
5743 * @todo should set exclusive state and drop glock around salvsync call
5745 * @internal volume package internal use only.
5748 VUpdateSalvagePriority_r(Volume * vp)
5752 #ifdef SALVSYNC_BUILD_CLIENT
5757 now = FT_ApproxTime();
5759 /* update the salvageserver priority queue occasionally so that
5760 * frequently requested volumes get moved to the head of the queue
5762 if ((vp->salvage.scheduled) &&
5763 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5764 code = SALVSYNC_SalvageVolume(vp->hashid,
5765 VPartitionPath(vp->partition),
5770 vp->stats.last_salvage_req = now;
5771 if (code != SYNC_OK) {
5775 #endif /* SALVSYNC_BUILD_CLIENT */
5780 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5782 /* A couple of little helper functions. These return true if we tried to
5783 * use this mechanism to schedule a salvage, false if we haven't tried.
5784 * If we did try a salvage then the results are contained in code.
5788 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5789 #ifdef SALVSYNC_BUILD_CLIENT
5790 if (VCanUseSALVSYNC()) {
5791 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over SALVSYNC\n",
5792 afs_printable_VolumeId_lu(vp->hashid), partName);
5794 /* can't use V_id() since there's no guarantee
5795 * we have the disk data header at this point */
5796 *code = SALVSYNC_SalvageVolume(vp->hashid,
5809 try_FSSYNC(Volume *vp, char *partName, int *code) {
5810 #ifdef FSSYNC_BUILD_CLIENT
5811 if (VCanUseFSSYNC()) {
5812 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over FSSYNC\n",
5813 afs_printable_VolumeId_lu(vp->hashid), partName);
5816 * If we aren't the fileserver, tell the fileserver the volume
5817 * needs to be salvaged. We could directly tell the
5818 * salvageserver, but the fileserver keeps track of some stats
5819 * related to salvages, and handles some other salvage-related
5820 * complications for us.
5822 *code = FSYNC_VolOp(vp->hashid, partName,
5823 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5826 #endif /* FSSYNC_BUILD_CLIENT */
5831 * schedule a salvage with the salvage server or fileserver.
5833 * @param[in] vp pointer to volume object
5835 * @return operation status
5836 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5837 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5838 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5839 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5840 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5843 * @arg VOL_LOCK is held.
5844 * @arg nUsers and nWaiters should be zero.
5846 * @post salvageserver or fileserver is sent a salvage request
5848 * @note If we are the fileserver, the request will be sent to the salvage
5849 * server over SALVSYNC. If we are not the fileserver, the request will be
5850 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5852 * @note the caller must check if the volume needs to be freed after calling
5853 * this; the volume may not have any references or be on any lists after
5854 * we return, and we do not free it
5858 * @internal volume package internal use only.
5861 VScheduleSalvage_r(Volume * vp)
5863 int ret = VCHECK_SALVAGE_SCHEDULED;
5865 VolState state_save;
5866 VThreadOptions_t * thread_opts;
5869 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5871 if (vp->nWaiters || vp->nUsers) {
5872 return VCHECK_SALVAGE_ASYNC;
5875 /* prevent endless salvage,attach,salvage,attach,... loops */
5876 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5877 return VCHECK_SALVAGE_FAIL;
5881 * don't perform salvsync ops on certain threads
5883 thread_opts = pthread_getspecific(VThread_key);
5884 if (thread_opts == NULL) {
5885 thread_opts = &VThread_defaults;
5887 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5888 return VCHECK_SALVAGE_ASYNC;
5891 if (vp->salvage.scheduled) {
5892 return VCHECK_SALVAGE_SCHEDULED;
5895 VCreateReservation_r(vp);
5896 VWaitExclusiveState_r(vp);
5899 * XXX the scheduling process should really be done asynchronously
5900 * to avoid fssync deadlocks
5902 if (vp->salvage.scheduled) {
5903 ret = VCHECK_SALVAGE_SCHEDULED;
5905 /* if we haven't previously scheduled a salvage, do so now
5907 * set the volume to an exclusive state and drop the lock
5908 * around the SALVSYNC call
5910 strlcpy(partName, vp->partition->name, sizeof(partName));
5911 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5914 opr_Verify(try_SALVSYNC(vp, partName, &code)
5915 || try_FSSYNC(vp, partName, &code));
5918 VChangeState_r(vp, state_save);
5920 if (code == SYNC_OK) {
5921 ret = VCHECK_SALVAGE_SCHEDULED;
5922 vp->salvage.scheduled = 1;
5923 vp->stats.last_salvage_req = FT_ApproxTime();
5924 if (VCanUseSALVSYNC()) {
5925 /* don't record these stats for non-fileservers; let the
5926 * fileserver take care of these */
5927 vp->stats.salvages++;
5928 IncUInt64(&VStats.salvages);
5932 case SYNC_BAD_COMMAND:
5933 case SYNC_COM_ERROR:
5934 ret = VCHECK_SALVAGE_FAIL;
5937 ret = VCHECK_SALVAGE_DENIED;
5938 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5939 "denied\n", afs_printable_VolumeId_lu(vp->hashid));
5942 ret = VCHECK_SALVAGE_FAIL;
5943 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5944 "failed\n", afs_printable_VolumeId_lu(vp->hashid));
5947 ret = VCHECK_SALVAGE_FAIL;
5948 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5949 "received unknown protocol error %d\n",
5950 afs_printable_VolumeId_lu(vp->hashid), code);
5954 if (VCanUseFSSYNC()) {
5955 VChangeState_r(vp, VOL_STATE_ERROR);
5960 /* NB: this is cancelling the reservation we obtained above, but we do
5961 * not call VCancelReservation_r, since that may trigger the vp dtor,
5962 * possibly free'ing the vp. We need to keep the vp around after
5963 * this, as the caller may reference vp without any refs. Instead, it
5964 * is the duty of the caller to inspect 'vp' after we return to see if
5965 * needs to be freed. */
5966 opr_Verify(--vp->nWaiters >= 0);
5969 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5971 #ifdef SALVSYNC_BUILD_CLIENT
5974 * connect to the salvageserver SYNC service.
5976 * @return operation status
5980 * @post connection to salvageserver SYNC service established
5982 * @see VConnectSALV_r
5983 * @see VDisconnectSALV
5984 * @see VReconnectSALV
5991 retVal = VConnectSALV_r();
5997 * connect to the salvageserver SYNC service.
5999 * @return operation status
6003 * @pre VOL_LOCK is held.
6005 * @post connection to salvageserver SYNC service established
6008 * @see VDisconnectSALV_r
6009 * @see VReconnectSALV_r
6010 * @see SALVSYNC_clientInit
6012 * @internal volume package internal use only.
6015 VConnectSALV_r(void)
6017 return SALVSYNC_clientInit();
6021 * disconnect from the salvageserver SYNC service.
6023 * @return operation status
6026 * @pre client should have a live connection to the salvageserver
6028 * @post connection to salvageserver SYNC service destroyed
6030 * @see VDisconnectSALV_r
6032 * @see VReconnectSALV
6035 VDisconnectSALV(void)
6038 VDisconnectSALV_r();
6044 * disconnect from the salvageserver SYNC service.
6046 * @return operation status
6050 * @arg VOL_LOCK is held.
6051 * @arg client should have a live connection to the salvageserver.
6053 * @post connection to salvageserver SYNC service destroyed
6055 * @see VDisconnectSALV
6056 * @see VConnectSALV_r
6057 * @see VReconnectSALV_r
6058 * @see SALVSYNC_clientFinis
6060 * @internal volume package internal use only.
6063 VDisconnectSALV_r(void)
6065 return SALVSYNC_clientFinis();
6069 * disconnect and then re-connect to the salvageserver SYNC service.
6071 * @return operation status
6075 * @pre client should have a live connection to the salvageserver
6077 * @post old connection is dropped, and a new one is established
6080 * @see VDisconnectSALV
6081 * @see VReconnectSALV_r
6084 VReconnectSALV(void)
6088 retVal = VReconnectSALV_r();
6094 * disconnect and then re-connect to the salvageserver SYNC service.
6096 * @return operation status
6101 * @arg VOL_LOCK is held.
6102 * @arg client should have a live connection to the salvageserver.
6104 * @post old connection is dropped, and a new one is established
6106 * @see VConnectSALV_r
6107 * @see VDisconnectSALV
6108 * @see VReconnectSALV
6109 * @see SALVSYNC_clientReconnect
6111 * @internal volume package internal use only.
6114 VReconnectSALV_r(void)
6116 return SALVSYNC_clientReconnect();
6118 #endif /* SALVSYNC_BUILD_CLIENT */
6119 #endif /* AFS_DEMAND_ATTACH_FS */
6122 /***************************************************/
6123 /* FSSYNC routines */
6124 /***************************************************/
6126 /* This must be called by any volume utility which needs to run while the
6127 file server is also running. This is separated from VInitVolumePackage2 so
6128 that a utility can fork--and each of the children can independently
6129 initialize communication with the file server */
6130 #ifdef FSSYNC_BUILD_CLIENT
6132 * connect to the fileserver SYNC service.
6134 * @return operation status
6139 * @arg VInit must equal 2.
6140 * @arg Program Type must not be fileserver or salvager.
6142 * @post connection to fileserver SYNC service established
6145 * @see VDisconnectFS
6146 * @see VChildProcReconnectFS
6153 retVal = VConnectFS_r();
6159 * connect to the fileserver SYNC service.
6161 * @return operation status
6166 * @arg VInit must equal 2.
6167 * @arg Program Type must not be fileserver or salvager.
6168 * @arg VOL_LOCK is held.
6170 * @post connection to fileserver SYNC service established
6173 * @see VDisconnectFS_r
6174 * @see VChildProcReconnectFS_r
6176 * @internal volume package internal use only.
6182 opr_Assert((VInit == 2) &&
6183 (programType != fileServer) &&
6184 (programType != salvager));
6185 rc = FSYNC_clientInit();
6193 * disconnect from the fileserver SYNC service.
6196 * @arg client should have a live connection to the fileserver.
6197 * @arg VOL_LOCK is held.
6198 * @arg Program Type must not be fileserver or salvager.
6200 * @post connection to fileserver SYNC service destroyed
6202 * @see VDisconnectFS
6204 * @see VChildProcReconnectFS_r
6206 * @internal volume package internal use only.
6209 VDisconnectFS_r(void)
6211 opr_Assert((programType != fileServer) &&
6212 (programType != salvager));
6213 FSYNC_clientFinis();
6218 * disconnect from the fileserver SYNC service.
6221 * @arg client should have a live connection to the fileserver.
6222 * @arg Program Type must not be fileserver or salvager.
6224 * @post connection to fileserver SYNC service destroyed
6226 * @see VDisconnectFS_r
6228 * @see VChildProcReconnectFS
6239 * connect to the fileserver SYNC service from a child process following a fork.
6241 * @return operation status
6246 * @arg VOL_LOCK is held.
6247 * @arg current FSYNC handle is shared with a parent process
6249 * @post current FSYNC handle is discarded and a new connection to the
6250 * fileserver SYNC service is established
6252 * @see VChildProcReconnectFS
6254 * @see VDisconnectFS_r
6256 * @internal volume package internal use only.
6259 VChildProcReconnectFS_r(void)
6261 return FSYNC_clientChildProcReconnect();
6265 * connect to the fileserver SYNC service from a child process following a fork.
6267 * @return operation status
6271 * @pre current FSYNC handle is shared with a parent process
6273 * @post current FSYNC handle is discarded and a new connection to the
6274 * fileserver SYNC service is established
6276 * @see VChildProcReconnectFS_r
6278 * @see VDisconnectFS
6281 VChildProcReconnectFS(void)
6285 ret = VChildProcReconnectFS_r();
6289 #endif /* FSSYNC_BUILD_CLIENT */
6292 /***************************************************/
6293 /* volume bitmap routines */
6294 /***************************************************/
6297 * Grow the bitmap by the defined increment
6300 VGrowBitmap(struct vnodeIndex *index)
6304 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6305 osi_Assert(bp != NULL);
6307 bp += index->bitmapSize;
6308 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6309 index->bitmapOffset = index->bitmapSize;
6310 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6316 * allocate a vnode bitmap number for the vnode
6318 * @param[out] ec error code
6319 * @param[in] vp volume object pointer
6320 * @param[in] index vnode index number for the vnode
6321 * @param[in] flags flag values described in note
6323 * @note for DAFS, flags parameter controls locking behavior.
6324 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6325 * will create a reservation and block on any other exclusive
6326 * operations. Otherwise, this function assumes the caller
6327 * already has exclusive access to vp, and we just change the
6330 * @pre VOL_LOCK held
6332 * @return bit number allocated
6338 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6339 struct vnodeIndex *index, int flags)
6343 #ifdef AFS_DEMAND_ATTACH_FS
6344 VolState state_save;
6345 #endif /* AFS_DEMAND_ATTACH_FS */
6349 /* This test is probably redundant */
6350 if (!VolumeWriteable(vp)) {
6351 *ec = (bit32) VREADONLY;
6355 #ifdef AFS_DEMAND_ATTACH_FS
6356 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6357 VCreateReservation_r(vp);
6358 VWaitExclusiveState_r(vp);
6360 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6361 #endif /* AFS_DEMAND_ATTACH_FS */
6364 if ((programType == fileServer) && !index->bitmap) {
6366 #ifndef AFS_DEMAND_ATTACH_FS
6367 /* demand attach fs uses the volume state to avoid races.
6368 * specialStatus field is not used at all */
6370 if (vp->specialStatus == VBUSY) {
6371 if (vp->goingOffline) { /* vos dump waiting for the volume to
6372 * go offline. We probably come here
6373 * from AddNewReadableResidency */
6376 while (vp->specialStatus == VBUSY) {
6377 #ifdef AFS_PTHREAD_ENV
6381 #else /* !AFS_PTHREAD_ENV */
6383 #endif /* !AFS_PTHREAD_ENV */
6387 #endif /* !AFS_DEMAND_ATTACH_FS */
6389 if (!index->bitmap) {
6390 #ifndef AFS_DEMAND_ATTACH_FS
6391 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6392 #endif /* AFS_DEMAND_ATTACH_FS */
6393 for (i = 0; i < nVNODECLASSES; i++) {
6394 VGetBitmap_r(ec, vp, i);
6396 #ifdef AFS_DEMAND_ATTACH_FS
6397 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6398 #else /* AFS_DEMAND_ATTACH_FS */
6399 DeleteVolumeFromHashTable(vp);
6400 vp->shuttingDown = 1; /* Let who has it free it. */
6401 vp->specialStatus = 0;
6402 #endif /* AFS_DEMAND_ATTACH_FS */
6406 #ifndef AFS_DEMAND_ATTACH_FS
6408 vp->specialStatus = 0; /* Allow others to have access. */
6409 #endif /* AFS_DEMAND_ATTACH_FS */
6412 #endif /* BITMAP_LATER */
6414 #ifdef AFS_DEMAND_ATTACH_FS
6416 #endif /* AFS_DEMAND_ATTACH_FS */
6417 bp = index->bitmap + index->bitmapOffset;
6418 ep = index->bitmap + index->bitmapSize;
6420 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6422 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6425 o = opr_ffs(~*bp) - 1;
6427 ret = ((bp - index->bitmap) * 8 + o);
6428 #ifdef AFS_DEMAND_ATTACH_FS
6430 #endif /* AFS_DEMAND_ATTACH_FS */
6433 bp += sizeof(bit32) /* i.e. 4 */ ;
6435 /* No bit map entry--must grow bitmap */
6437 bp = index->bitmap + index->bitmapOffset;
6439 ret = index->bitmapOffset * 8;
6440 #ifdef AFS_DEMAND_ATTACH_FS
6442 #endif /* AFS_DEMAND_ATTACH_FS */
6445 #ifdef AFS_DEMAND_ATTACH_FS
6446 VChangeState_r(vp, state_save);
6447 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6448 VCancelReservation_r(vp);
6450 #endif /* AFS_DEMAND_ATTACH_FS */
6455 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6459 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6465 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6466 unsigned bitNumber, int flags)
6468 unsigned int offset;
6472 #ifdef AFS_DEMAND_ATTACH_FS
6473 if (flags & VOL_FREE_BITMAP_WAIT) {
6474 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6475 * state, so ensure we're not in an exclusive volume state when we update
6477 VCreateReservation_r(vp);
6478 VWaitExclusiveState_r(vp);
6485 #endif /* BITMAP_LATER */
6487 offset = bitNumber >> 3;
6488 if (offset >= index->bitmapSize) {
6492 if (offset < index->bitmapOffset)
6493 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6494 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6497 #ifdef AFS_DEMAND_ATTACH_FS
6498 if (flags & VOL_FREE_BITMAP_WAIT) {
6499 VCancelReservation_r(vp);
6502 return; /* make the compiler happy for non-DAFS */
6506 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6510 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6514 /* this function will drop the glock internally.
6515 * for old pthread fileservers, this is safe thanks to vbusy.
6517 * for demand attach fs, caller must have already called
6518 * VCreateReservation_r and VWaitExclusiveState_r */
6520 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6522 StreamHandle_t *file;
6523 afs_sfsize_t nVnodes, size;
6524 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6525 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6526 struct VnodeDiskObject *vnode;
6527 unsigned int unique = 0;
6531 #endif /* BITMAP_LATER */
6532 #ifdef AFS_DEMAND_ATTACH_FS
6533 VolState state_save;
6534 #endif /* AFS_DEMAND_ATTACH_FS */
6538 #ifdef AFS_DEMAND_ATTACH_FS
6539 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6540 #endif /* AFS_DEMAND_ATTACH_FS */
6543 fdP = IH_OPEN(vip->handle);
6544 opr_Assert(fdP != NULL);
6545 file = FDH_FDOPEN(fdP, "r");
6546 opr_Assert(file != NULL);
6547 vnode = malloc(vcp->diskSize);
6548 opr_Assert(vnode != NULL);
6549 size = OS_SIZE(fdP->fd_fd);
6550 opr_Assert(size != -1);
6551 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6553 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6554 * a few files can be created in this volume,
6555 * the whole thing is rounded up to nearest 4
6556 * bytes, because the bit map allocator likes
6559 BitMap = (byte *) calloc(1, vip->bitmapSize);
6560 opr_Assert(BitMap != NULL);
6561 #else /* BITMAP_LATER */
6562 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6563 opr_Assert(vip->bitmap != NULL);
6564 vip->bitmapOffset = 0;
6565 #endif /* BITMAP_LATER */
6566 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6568 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6569 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6571 if (vnode->type != vNull) {
6572 if (vnode->vnodeMagic != vcp->magic) {
6573 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6578 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6579 #else /* BITMAP_LATER */
6580 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6581 #endif /* BITMAP_LATER */
6582 if (unique <= vnode->uniquifier)
6583 unique = vnode->uniquifier + 1;
6585 #ifndef AFS_PTHREAD_ENV
6586 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6589 #endif /* !AFS_PTHREAD_ENV */
6592 if (vp->nextVnodeUnique < unique) {
6593 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6596 /* Paranoia, partly justified--I think fclose after fdopen
6597 * doesn't seem to close fd. In any event, the documentation
6598 * doesn't specify, so it's safer to close it twice.
6606 /* There may have been a racing condition with some other thread, both
6607 * creating the bitmaps for this volume. If the other thread was faster
6608 * the pointer to bitmap should already be filled and we can free ours.
6610 if (vip->bitmap == NULL) {
6611 vip->bitmap = BitMap;
6612 vip->bitmapOffset = 0;
6615 #endif /* BITMAP_LATER */
6616 #ifdef AFS_DEMAND_ATTACH_FS
6617 VChangeState_r(vp, state_save);
6618 #endif /* AFS_DEMAND_ATTACH_FS */
6622 /***************************************************/
6623 /* Volume Path and Volume Number utility routines */
6624 /***************************************************/
6627 * find the first occurrence of a volume header file and return the path.
6629 * @param[out] ec outbound error code
6630 * @param[in] volumeId volume id to find
6631 * @param[out] partitionp pointer to disk partition path string
6632 * @param[out] namep pointer to volume header file name string
6634 * @post path to first occurrence of volume header is returned in partitionp
6635 * and namep, or ec is set accordingly.
6637 * @warning this function is NOT re-entrant -- partitionp and namep point to
6638 * static data segments
6640 * @note if a volume utility inadvertently leaves behind a stale volume header
6641 * on a vice partition, it is possible for callers to get the wrong one,
6642 * depending on the order of the disk partition linked list.
6646 VGetVolumePath(Error * ec, VolumeId volumeId, char **partitionp, char **namep)
6648 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6649 char path[VMAXPATHLEN];
6651 struct DiskPartition64 *dp;
6654 name[0] = OS_DIRSEPC;
6655 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6656 afs_printable_VolumeId_lu(volumeId));
6657 for (dp = DiskPartitionList; dp; dp = dp->next) {
6658 struct afs_stat_st status;
6659 strcpy(path, VPartitionPath(dp));
6661 if (afs_stat(path, &status) == 0) {
6662 strcpy(partition, dp->name);
6669 *partitionp = *namep = NULL;
6671 *partitionp = partition;
6677 * extract a volume number from a volume header filename string.
6679 * @param[in] name volume header filename string
6681 * @return volume number
6683 * @note the string must be of the form VFORMAT. the only permissible
6684 * deviation is a leading OS_DIRSEPC character.
6689 VolumeNumber(char *name)
6691 if (*name == OS_DIRSEPC)
6693 return strtoul(name + 1, NULL, 10);
6697 * compute the volume header filename.
6699 * @param[in] volumeId
6701 * @return volume header filename
6703 * @post volume header filename string is constructed
6705 * @warning this function is NOT re-entrant -- the returned string is
6706 * stored in a static char array. see VolumeExternalName_r
6707 * for a re-entrant equivalent.
6709 * @see VolumeExternalName_r
6711 * @deprecated due to the above re-entrancy warning, this interface should
6712 * be considered deprecated. Please use VolumeExternalName_r
6716 VolumeExternalName(VolumeId volumeId)
6718 static char name[VMAXPATHLEN];
6719 snprintf(name, sizeof name, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6724 * compute the volume header filename.
6726 * @param[in] volumeId
6727 * @param[inout] name array in which to store filename
6728 * @param[in] len length of name array
6730 * @return result code from afs_snprintf
6732 * @see VolumeExternalName
6735 * @note re-entrant equivalent of VolumeExternalName
6738 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6740 return snprintf(name, len, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6744 /***************************************************/
6745 /* Volume Usage Statistics routines */
6746 /***************************************************/
6748 #define OneDay (86400) /* 24 hours' worth of seconds */
6751 Midnight(time_t t) {
6752 struct tm local, *l;
6755 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6756 l = localtime_r(&t, &local);
6762 /* the following is strictly speaking problematic on the
6763 switching day to daylight saving time, after the switch,
6764 as tm_isdst does not match. Similarly, on the looong day when
6765 switching back the OneDay check will not do what naively expected!
6766 The effects are minor, though, and more a matter of interpreting
6768 #ifndef AFS_PTHREAD_ENV
6771 local.tm_hour = local.tm_min=local.tm_sec = 0;
6772 midnight = mktime(&local);
6773 if (midnight != (time_t) -1) return(midnight);
6775 return( (t/OneDay)*OneDay );
6779 /*------------------------------------------------------------------------
6780 * [export] VAdjustVolumeStatistics
6783 * If we've passed midnight, we need to update all the day use
6784 * statistics as well as zeroing the detailed volume statistics
6785 * (if we are implementing them).
6788 * vp : Pointer to the volume structure describing the lucky
6789 * volume being considered for update.
6795 * Nothing interesting.
6799 *------------------------------------------------------------------------*/
6802 VAdjustVolumeStatistics_r(Volume * vp)
6804 unsigned int now = FT_ApproxTime();
6806 if (now - V_dayUseDate(vp) > OneDay) {
6809 ndays = (now - V_dayUseDate(vp)) / OneDay;
6810 for (i = 6; i > ndays - 1; i--)
6811 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6812 for (i = 0; i < ndays - 1 && i < 7; i++)
6813 V_weekUse(vp)[i] = 0;
6815 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6817 V_dayUseDate(vp) = Midnight(now);
6820 * All we need to do is bzero the entire VOL_STATS_BYTES of
6821 * the detailed volume statistics area.
6823 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6826 /*It's been more than a day of collection */
6828 * Always return happily.
6831 } /*VAdjustVolumeStatistics */
6834 VAdjustVolumeStatistics(Volume * vp)
6838 retVal = VAdjustVolumeStatistics_r(vp);
6844 VBumpVolumeUsage_r(Volume * vp)
6846 unsigned int now = FT_ApproxTime();
6847 V_accessDate(vp) = now;
6848 if (now - V_dayUseDate(vp) > OneDay)
6849 VAdjustVolumeStatistics_r(vp);
6851 * Save the volume header image to disk after a threshold of bumps to dayUse,
6852 * at most every usage_rate_limit seconds.
6855 vp->usage_bumps_outstanding++;
6856 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6857 && vp->usage_bumps_next_write <= now) {
6859 vp->usage_bumps_outstanding = 0;
6860 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6861 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6866 VBumpVolumeUsage(Volume * vp)
6869 VBumpVolumeUsage_r(vp);
6874 VSetDiskUsage_r(void)
6876 #ifndef AFS_DEMAND_ATTACH_FS
6877 static int FifteenMinuteCounter = 0;
6881 /* NOTE: Don't attempt to access the partitions list until the
6882 * initialization level indicates that all volumes are attached,
6883 * which implies that all partitions are initialized. */
6884 #ifdef AFS_PTHREAD_ENV
6885 VOL_CV_WAIT(&vol_vinit_cond);
6886 #else /* AFS_PTHREAD_ENV */
6888 #endif /* AFS_PTHREAD_ENV */
6891 VResetDiskUsage_r();
6893 #ifndef AFS_DEMAND_ATTACH_FS
6894 if (++FifteenMinuteCounter == 3) {
6895 FifteenMinuteCounter = 0;
6898 #endif /* !AFS_DEMAND_ATTACH_FS */
6910 /***************************************************/
6911 /* Volume Update List routines */
6912 /***************************************************/
6914 /* The number of minutes that a volume hasn't been updated before the
6915 * "Dont salvage" flag in the volume header will be turned on */
6916 #define SALVAGE_INTERVAL (10*60)
6921 * volume update list functionality has been moved into the VLRU
6922 * the DONT_SALVAGE flag is now set during VLRU demotion
6925 #ifndef AFS_DEMAND_ATTACH_FS
6926 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6927 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6928 static int updateSize = 0; /* number of entries possible */
6929 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6930 #endif /* !AFS_DEMAND_ATTACH_FS */
6933 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6936 vp->updateTime = FT_ApproxTime();
6937 if (V_dontSalvage(vp) == 0)
6939 V_dontSalvage(vp) = 0;
6940 VSyncVolume_r(ec, vp, 0);
6941 #ifdef AFS_DEMAND_ATTACH_FS
6942 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6943 #else /* !AFS_DEMAND_ATTACH_FS */
6946 if (UpdateList == NULL) {
6947 updateSize = UPDATE_LIST_SIZE;
6948 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6950 if (nUpdatedVolumes == updateSize) {
6952 if (updateSize > 524288) {
6953 Log("warning: there is likely a bug in the volume update scanner\n");
6956 UpdateList = realloc(UpdateList,
6957 sizeof(VolumeId) * updateSize);
6960 opr_Assert(UpdateList != NULL);
6961 UpdateList[nUpdatedVolumes++] = V_id(vp);
6962 #endif /* !AFS_DEMAND_ATTACH_FS */
6965 #ifndef AFS_DEMAND_ATTACH_FS
6967 VScanUpdateList(void)
6972 afs_uint32 now = FT_ApproxTime();
6973 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6974 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6976 UpdateList[i - gap] = UpdateList[i];
6978 /* XXX this routine needlessly messes up the Volume LRU by
6979 * breaking the LRU temporal-locality assumptions.....
6980 * we should use a special volume header allocator here */
6981 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6984 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6985 V_dontSalvage(vp) = DONT_SALVAGE;
6986 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6994 #ifndef AFS_PTHREAD_ENV
6996 #endif /* !AFS_PTHREAD_ENV */
6998 nUpdatedVolumes -= gap;
7000 #endif /* !AFS_DEMAND_ATTACH_FS */
7003 /***************************************************/
7004 /* Volume LRU routines */
7005 /***************************************************/
7010 * with demand attach fs, we attempt to soft detach(1)
7011 * volumes which have not been accessed in a long time
7012 * in order to speed up fileserver shutdown
7014 * (1) by soft detach we mean a process very similar
7015 * to VOffline, except the final state of the
7016 * Volume will be VOL_STATE_PREATTACHED, instead
7017 * of the usual VOL_STATE_UNATTACHED
7019 #ifdef AFS_DEMAND_ATTACH_FS
7021 /* implementation is reminiscent of a generational GC
7023 * queue 0 is newly attached volumes. this queue is
7024 * sorted by attach timestamp
7026 * queue 1 is volumes that have been around a bit
7027 * longer than queue 0. this queue is sorted by
7030 * queue 2 is volumes tha have been around the longest.
7031 * this queue is unsorted
7033 * queue 3 is volumes that have been marked as
7034 * candidates for soft detachment. this queue is
7037 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
7038 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
7041 * definition of a VLRU queue.
7044 volatile struct rx_queue q;
7051 * main VLRU data structure.
7054 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
7057 /** time interval (in seconds) between promotion passes for
7058 * each young generation queue. */
7059 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
7061 /** time interval (in seconds) between soft detach candidate
7062 * scans for each generation queue.
7064 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
7065 * we perform a soft detach pass. */
7066 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
7068 /* scheduler state */
7069 int next_idx; /**< next queue to receive attention */
7070 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
7071 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
7073 int scanner_state; /**< state of scanner thread */
7074 pthread_cond_t cv; /**< state transition CV */
7077 /** global VLRU state */
7078 static struct VLRU volume_LRU;
7081 * defined states for VLRU scanner thread.
7084 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7085 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7086 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7087 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7088 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7089 } vlru_thread_state_t;
7091 /* vlru disk data header stuff */
7092 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7093 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7095 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7096 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7099 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7100 * soft detachment. */
7101 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7103 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7104 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7106 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7107 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7109 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7110 static afs_uint32 VLRU_enabled = 1;
7112 /* queue synchronization routines */
7113 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7114 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7115 static void VLRU_Wait_r(struct VLRU_q * q);
7118 * set VLRU subsystem tunable parameters.
7120 * @param[in] option tunable option to modify
7121 * @param[in] val new value for tunable parameter
7123 * @pre @c VInitVolumePackage2 has not yet been called.
7125 * @post tunable parameter is modified
7129 * @note valid option parameters are:
7130 * @arg @c VLRU_SET_THRESH
7131 * set the period of inactivity after which
7132 * volumes are eligible for soft detachment
7133 * @arg @c VLRU_SET_INTERVAL
7134 * set the time interval between calls
7135 * to the volume LRU "garbage collector"
7136 * @arg @c VLRU_SET_MAX
7137 * set the max number of volumes to deallocate
7141 VLRU_SetOptions(int option, afs_uint32 val)
7143 if (option == VLRU_SET_THRESH) {
7144 VLRU_offline_thresh = val;
7145 } else if (option == VLRU_SET_INTERVAL) {
7146 VLRU_offline_interval = val;
7147 } else if (option == VLRU_SET_MAX) {
7148 VLRU_offline_max = val;
7149 } else if (option == VLRU_SET_ENABLED) {
7152 VLRU_ComputeConstants();
7156 * compute VLRU internal timing parameters.
7158 * @post VLRU scanner thread internal timing parameters are computed
7160 * @note computes internal timing parameters based upon user-modifiable
7161 * tunable parameters.
7165 * @internal volume package internal use only.
7168 VLRU_ComputeConstants(void)
7170 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7172 /* compute the candidate scan interval */
7173 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7175 /* compute the promotion intervals */
7176 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7177 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7180 /* compute the gen 0 scan interval */
7181 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7183 /* compute the gen 0 scan interval */
7184 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7189 * initialize VLRU subsystem.
7191 * @pre this function has not yet been called
7193 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7197 * @internal volume package internal use only.
7203 pthread_attr_t attrs;
7206 if (!VLRU_enabled) {
7207 Log("VLRU: disabled\n");
7211 /* initialize each of the VLRU queues */
7212 for (i = 0; i < VLRU_QUEUES; i++) {
7213 queue_Init(&volume_LRU.q[i]);
7214 volume_LRU.q[i].len = 0;
7215 volume_LRU.q[i].busy = 0;
7216 opr_cv_init(&volume_LRU.q[i].cv);
7219 /* setup the timing constants */
7220 VLRU_ComputeConstants();
7222 /* XXX put inside log level check? */
7223 Log("VLRU: starting scanner with the following configuration parameters:\n");
7224 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7225 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7226 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7227 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7228 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7229 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7231 /* start up the VLRU scanner */
7232 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7233 if (programType == fileServer) {
7234 opr_cv_init(&volume_LRU.cv);
7235 opr_Verify(pthread_attr_init(&attrs) == 0);
7236 opr_Verify(pthread_attr_setdetachstate(&attrs,
7237 PTHREAD_CREATE_DETACHED) == 0);
7238 opr_Verify(pthread_create(&tid, &attrs,
7239 &VLRU_ScannerThread, NULL) == 0);
7244 * initialize the VLRU-related fields of a newly allocated volume object.
7246 * @param[in] vp pointer to volume object
7249 * @arg @c VOL_LOCK is held.
7250 * @arg volume object is not on a VLRU queue.
7252 * @post VLRU fields are initialized to indicate that volume object is not
7253 * currently registered with the VLRU subsystem
7257 * @internal volume package interal use only.
7260 VLRU_Init_Node_r(Volume * vp)
7265 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7266 vp->vlru.idx = VLRU_QUEUE_INVALID;
7270 * add a volume object to a VLRU queue.
7272 * @param[in] vp pointer to volume object
7275 * @arg @c VOL_LOCK is held.
7276 * @arg caller MUST hold a lightweight ref on @p vp.
7277 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7279 * @post the volume object is added to the appropriate VLRU queue
7281 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7282 * then the volume is added to that queue. Otherwise, the value
7283 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7284 * volume is added to the NEW generation queue.
7286 * @note @c VOL_LOCK may be dropped internally
7288 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7289 * during the add operation, and is restored to the previous
7290 * state prior to return.
7294 * @internal volume package internal use only.
7297 VLRU_Add_r(Volume * vp)
7300 VolState state_save;
7305 if (queue_IsOnQueue(&vp->vlru))
7308 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7311 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7312 idx = VLRU_QUEUE_NEW;
7315 VLRU_Wait_r(&volume_LRU.q[idx]);
7317 /* repeat check since VLRU_Wait_r may have dropped
7319 if (queue_IsNotOnQueue(&vp->vlru)) {
7321 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7322 volume_LRU.q[idx].len++;
7323 V_attachFlags(vp) |= VOL_ON_VLRU;
7324 vp->stats.last_promote = FT_ApproxTime();
7327 VChangeState_r(vp, state_save);
7331 * delete a volume object from a VLRU queue.
7333 * @param[in] vp pointer to volume object
7336 * @arg @c VOL_LOCK is held.
7337 * @arg caller MUST hold a lightweight ref on @p vp.
7338 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7340 * @post volume object is removed from the VLRU queue
7342 * @note @c VOL_LOCK may be dropped internally
7346 * @todo We should probably set volume state to something exlcusive
7347 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7349 * @internal volume package internal use only.
7352 VLRU_Delete_r(Volume * vp)
7359 if (queue_IsNotOnQueue(&vp->vlru))
7365 if (idx == VLRU_QUEUE_INVALID)
7367 VLRU_Wait_r(&volume_LRU.q[idx]);
7368 } while (idx != vp->vlru.idx);
7370 /* now remove from the VLRU and update
7371 * the appropriate counter */
7372 queue_Remove(&vp->vlru);
7373 volume_LRU.q[idx].len--;
7374 vp->vlru.idx = VLRU_QUEUE_INVALID;
7375 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7379 * tell the VLRU subsystem that a volume was just accessed.
7381 * @param[in] vp pointer to volume object
7384 * @arg @c VOL_LOCK is held
7385 * @arg caller MUST hold a lightweight ref on @p vp
7386 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7388 * @post volume VLRU access statistics are updated. If the volume was on
7389 * the VLRU soft detach candidate queue, it is moved to the NEW
7392 * @note @c VOL_LOCK may be dropped internally
7396 * @internal volume package internal use only.
7399 VLRU_UpdateAccess_r(Volume * vp)
7401 Volume * rvp = NULL;
7406 if (queue_IsNotOnQueue(&vp->vlru))
7409 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7411 /* update the access timestamp */
7412 vp->stats.last_get = FT_ApproxTime();
7415 * if the volume is on the soft detach candidate
7416 * list, we need to safely move it back to a
7417 * regular generation. this has to be done
7418 * carefully so we don't race against the scanner
7422 /* if this volume is on the soft detach candidate queue,
7423 * then grab exclusive access to the necessary queues */
7424 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7426 VCreateReservation_r(rvp);
7428 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7429 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7430 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7431 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7434 /* make sure multiple threads don't race to update */
7435 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7436 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7440 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7441 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7442 VCancelReservation_r(rvp);
7447 * switch a volume between two VLRU queues.
7449 * @param[in] vp pointer to volume object
7450 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7451 * @param[in] append controls whether the volume will be appended or
7452 * prepended to the queue. A nonzero value means it will
7453 * be appended; zero means it will be prepended.
7455 * @pre The new (and old, if applicable) queue(s) must either be owned
7456 * exclusively by the calling thread for asynchronous manipulation,
7457 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7458 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7459 * for further details of the queue asynchronous processing mechanism.
7461 * @post If the volume object was already on a VLRU queue, it is
7462 * removed from the queue. Depending on the value of the append
7463 * parameter, the volume object is either appended or prepended
7464 * to the VLRU queue referenced by the new_idx parameter.
7468 * @see VLRU_BeginExclusive_r
7469 * @see VLRU_EndExclusive_r
7472 * @internal volume package internal use only.
7475 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7477 if (queue_IsNotOnQueue(&vp->vlru))
7480 queue_Remove(&vp->vlru);
7481 volume_LRU.q[vp->vlru.idx].len--;
7483 /* put the volume back on the correct generational queue */
7485 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7487 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7490 volume_LRU.q[new_idx].len++;
7491 vp->vlru.idx = new_idx;
7495 * VLRU background thread.
7497 * The VLRU Scanner Thread is responsible for periodically scanning through
7498 * each VLRU queue looking for volumes which should be moved to another
7499 * queue, or soft detached.
7501 * @param[in] args unused thread arguments parameter
7503 * @return unused thread return value
7504 * @retval NULL always
7506 * @internal volume package internal use only.
7509 VLRU_ScannerThread(void * args)
7511 afs_uint32 now, min_delay, delay;
7512 int i, min_idx, min_op, overdue, state;
7514 /* set t=0 for promotion cycle to be
7515 * fileserver startup */
7516 now = FT_ApproxTime();
7517 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7518 volume_LRU.last_promotion[i] = now;
7521 /* don't start the scanner until VLRU_offline_thresh
7522 * plus a small delay for VInitVolumePackage2 to finish
7525 sleep(VLRU_offline_thresh + 60);
7527 /* set t=0 for scan cycle to be now */
7528 now = FT_ApproxTime();
7529 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7530 volume_LRU.last_scan[i] = now;
7534 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7535 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7538 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7539 /* check to see if we've been asked to pause */
7540 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7541 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7542 opr_cv_broadcast(&volume_LRU.cv);
7544 VOL_CV_WAIT(&volume_LRU.cv);
7545 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7548 /* scheduling can happen outside the glock */
7551 /* figure out what is next on the schedule */
7553 /* figure out a potential schedule for the new generation first */
7555 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7558 if (min_delay > volume_LRU.scan_interval[0]) {
7559 /* unsigned overflow -- we're overdue to run this scan */
7564 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7566 i = VLRU_QUEUE_CANDIDATE;
7567 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7568 if (delay < min_delay) {
7572 if (delay > volume_LRU.scan_interval[i]) {
7573 /* unsigned overflow -- we're overdue to run this scan */
7580 /* if we're still not overdue for something, figure out schedules for promotions */
7581 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7582 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7583 if (delay < min_delay) {
7588 if (delay > volume_LRU.promotion_interval[i]) {
7589 /* unsigned overflow -- we're overdue to run this promotion */
7598 /* sleep as needed */
7603 /* do whatever is next */
7606 VLRU_Promote_r(min_idx);
7607 VLRU_Demote_r(min_idx+1);
7609 VLRU_Scan_r(min_idx);
7611 now = FT_ApproxTime();
7614 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7616 /* signal that scanner is down */
7617 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7618 opr_cv_broadcast(&volume_LRU.cv);
7624 * promote volumes from one VLRU generation to the next.
7626 * This routine scans a VLRU generation looking for volumes which are
7627 * eligible to be promoted to the next generation. All volumes which
7628 * meet the eligibility requirement are promoted.
7630 * Promotion eligibility is based upon meeting both of the following
7633 * @arg The volume has been accessed since the last promotion:
7634 * @c (vp->stats.last_get >= vp->stats.last_promote)
7635 * @arg The last promotion occurred at least
7636 * @c volume_LRU.promotion_interval[idx] seconds ago
7638 * As a performance optimization, promotions are "globbed". In other
7639 * words, we promote arbitrarily large contiguous sublists of elements
7642 * @param[in] idx VLRU queue index to scan
7646 * @internal VLRU internal use only.
7649 VLRU_Promote_r(int idx)
7651 int len, chaining, promote;
7652 afs_uint32 now, thresh;
7653 struct rx_queue *qp, *nqp;
7654 Volume * vp, *start = NULL, *end = NULL;
7656 /* get exclusive access to two chains, and drop the glock */
7657 VLRU_Wait_r(&volume_LRU.q[idx]);
7658 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7659 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7660 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7663 thresh = volume_LRU.promotion_interval[idx];
7664 now = FT_ApproxTime();
7667 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7668 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7669 promote = (((vp->stats.last_promote + thresh) <= now) &&
7670 (vp->stats.last_get >= vp->stats.last_promote));
7678 /* promote and prepend chain */
7679 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7693 /* promote and prepend */
7694 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7698 volume_LRU.q[idx].len -= len;
7699 volume_LRU.q[idx+1].len += len;
7702 /* release exclusive access to the two chains */
7704 volume_LRU.last_promotion[idx] = now;
7705 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7706 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7709 /* run the demotions */
7711 VLRU_Demote_r(int idx)
7714 int len, chaining, demote;
7715 afs_uint32 now, thresh;
7716 struct rx_queue *qp, *nqp;
7717 Volume * vp, *start = NULL, *end = NULL;
7718 Volume ** salv_flag_vec = NULL;
7719 int salv_vec_offset = 0;
7721 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7723 /* get exclusive access to two chains, and drop the glock */
7724 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7725 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7726 VLRU_Wait_r(&volume_LRU.q[idx]);
7727 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7730 /* no big deal if this allocation fails */
7731 if (volume_LRU.q[idx].len) {
7732 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7735 now = FT_ApproxTime();
7736 thresh = volume_LRU.promotion_interval[idx-1];
7739 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7740 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7741 demote = (((vp->stats.last_promote + thresh) <= now) &&
7742 (vp->stats.last_get < (now - thresh)));
7744 /* we now do volume update list DONT_SALVAGE flag setting during
7745 * demotion passes */
7746 if (salv_flag_vec &&
7747 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7749 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7750 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7751 salv_flag_vec[salv_vec_offset++] = vp;
7752 VCreateReservation_r(vp);
7761 /* demote and append chain */
7762 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7776 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7780 volume_LRU.q[idx].len -= len;
7781 volume_LRU.q[idx-1].len += len;
7784 /* release exclusive access to the two chains */
7786 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7787 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7789 /* now go back and set the DONT_SALVAGE flags as appropriate */
7790 if (salv_flag_vec) {
7792 for (i = 0; i < salv_vec_offset; i++) {
7793 vp = salv_flag_vec[i];
7794 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7795 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7796 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7799 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7800 V_dontSalvage(vp) = DONT_SALVAGE;
7801 VUpdateVolume_r(&ec, vp, 0);
7805 VCancelReservation_r(vp);
7807 free(salv_flag_vec);
7811 /* run a pass of the VLRU GC scanner */
7813 VLRU_Scan_r(int idx)
7815 afs_uint32 now, thresh;
7816 struct rx_queue *qp, *nqp;
7820 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7822 /* gain exclusive access to the idx VLRU */
7823 VLRU_Wait_r(&volume_LRU.q[idx]);
7824 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7826 if (idx != VLRU_QUEUE_CANDIDATE) {
7827 /* gain exclusive access to the candidate VLRU */
7828 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7829 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7832 now = FT_ApproxTime();
7833 thresh = now - VLRU_offline_thresh;
7835 /* perform candidate selection and soft detaching */
7836 if (idx == VLRU_QUEUE_CANDIDATE) {
7837 /* soft detach some volumes from the candidate pool */
7841 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7842 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7843 if (i >= VLRU_offline_max) {
7846 /* check timestamp to see if it's a candidate for soft detaching */
7847 if (vp->stats.last_get <= thresh) {
7849 if (VCheckSoftDetach(vp, thresh))
7855 /* scan for volumes to become soft detach candidates */
7856 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7857 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7859 /* check timestamp to see if it's a candidate for soft detaching */
7860 if (vp->stats.last_get <= thresh) {
7861 VCheckSoftDetachCandidate(vp, thresh);
7864 if (!(i&0x7f)) { /* lock coarsening optimization */
7872 /* relinquish exclusive access to the VLRU chains */
7876 volume_LRU.last_scan[idx] = now;
7877 if (idx != VLRU_QUEUE_CANDIDATE) {
7878 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7880 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7883 /* check whether volume is safe to soft detach
7884 * caller MUST NOT hold a ref count on vp */
7886 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7890 if (vp->nUsers || vp->nWaiters)
7893 if (vp->stats.last_get <= thresh) {
7894 ret = VSoftDetachVolume_r(vp, thresh);
7900 /* check whether volume should be made a
7901 * soft detach candidate */
7903 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7906 if (vp->nUsers || vp->nWaiters)
7911 opr_Assert(idx == VLRU_QUEUE_NEW);
7913 if (vp->stats.last_get <= thresh) {
7914 /* move to candidate pool */
7915 queue_Remove(&vp->vlru);
7916 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7917 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7918 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7919 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7927 /* begin exclusive access on VLRU */
7929 VLRU_BeginExclusive_r(struct VLRU_q * q)
7931 opr_Assert(q->busy == 0);
7935 /* end exclusive access on VLRU */
7937 VLRU_EndExclusive_r(struct VLRU_q * q)
7939 opr_Assert(q->busy);
7941 opr_cv_broadcast(&q->cv);
7944 /* wait for another thread to end exclusive access on VLRU */
7946 VLRU_Wait_r(struct VLRU_q * q)
7949 VOL_CV_WAIT(&q->cv);
7954 * volume soft detach
7956 * caller MUST NOT hold a ref count on vp */
7958 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7963 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7965 ts_save = vp->stats.last_get;
7966 if (ts_save > thresh)
7969 if (vp->nUsers || vp->nWaiters)
7972 if (VIsExclusiveState(V_attachState(vp))) {
7976 switch (V_attachState(vp)) {
7977 case VOL_STATE_UNATTACHED:
7978 case VOL_STATE_PREATTACHED:
7979 case VOL_STATE_ERROR:
7980 case VOL_STATE_GOING_OFFLINE:
7981 case VOL_STATE_SHUTTING_DOWN:
7982 case VOL_STATE_SALVAGING:
7983 case VOL_STATE_DELETED:
7984 volume_LRU.q[vp->vlru.idx].len--;
7986 /* create and cancel a reservation to
7987 * give the volume an opportunity to
7989 VCreateReservation_r(vp);
7990 queue_Remove(&vp->vlru);
7991 vp->vlru.idx = VLRU_QUEUE_INVALID;
7992 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7993 VCancelReservation_r(vp);
7999 /* hold the volume and take it offline.
8000 * no need for reservations, as VHold_r
8001 * takes care of that internally. */
8002 if (VHold_r(vp) == 0) {
8003 /* vhold drops the glock, so now we should
8004 * check to make sure we aren't racing against
8005 * other threads. if we are racing, offlining vp
8006 * would be wasteful, and block the scanner for a while
8010 (vp->shuttingDown) ||
8011 (vp->goingOffline) ||
8012 (vp->stats.last_get != ts_save)) {
8013 /* looks like we're racing someone else. bail */
8017 /* pull it off the VLRU */
8018 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
8019 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
8020 queue_Remove(&vp->vlru);
8021 vp->vlru.idx = VLRU_QUEUE_INVALID;
8022 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
8024 /* take if offline */
8025 VOffline_r(vp, "volume has been soft detached");
8027 /* invalidate the volume header cache */
8028 FreeVolumeHeader(vp);
8031 IncUInt64(&VStats.soft_detaches);
8032 vp->stats.soft_detaches++;
8034 /* put in pre-attached state so demand
8035 * attacher can work on it */
8036 VChangeState_r(vp, VOL_STATE_PREATTACHED);
8042 #endif /* AFS_DEMAND_ATTACH_FS */
8045 /***************************************************/
8046 /* Volume Header Cache routines */
8047 /***************************************************/
8050 * volume header cache.
8052 struct volume_hdr_LRU_t volume_hdr_LRU;
8055 * initialize the volume header cache.
8057 * @param[in] howMany number of header cache entries to preallocate
8059 * @pre VOL_LOCK held. Function has never been called before.
8061 * @post howMany cache entries are allocated, initialized, and added
8062 * to the LRU list. Header cache statistics are initialized.
8064 * @note only applicable to fileServer program type. Should only be
8065 * called once during volume package initialization.
8067 * @internal volume package internal use only.
8070 VInitVolumeHeaderCache(afs_uint32 howMany)
8072 struct volHeader *hp;
8073 if (programType != fileServer)
8075 queue_Init(&volume_hdr_LRU);
8076 volume_hdr_LRU.stats.free = 0;
8077 volume_hdr_LRU.stats.used = howMany;
8078 volume_hdr_LRU.stats.attached = 0;
8079 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8080 opr_Assert(hp != NULL);
8083 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8084 * to ensure they have the right values
8086 ReleaseVolumeHeader(hp++);
8089 /* get a volume header off of the volume header LRU.
8091 * @return volume header
8092 * @retval NULL no usable volume header is available on the LRU
8094 * @pre VOL_LOCK held
8096 * @post for DAFS, if the returned header is associated with a volume, that
8097 * volume is NOT in an exclusive state
8099 * @internal volume package internal use only.
8101 #ifdef AFS_DEMAND_ATTACH_FS
8102 static struct volHeader*
8103 GetVolHeaderFromLRU(void)
8105 struct volHeader *hd = NULL, *qh, *nqh;
8106 /* Usually, a volume in an exclusive state will not have its header on
8107 * the LRU. However, it is possible for this to occur when a salvage
8108 * request is received over FSSYNC, and possibly in other corner cases.
8109 * So just skip over headers whose volumes are in an exclusive state. We
8110 * could VWaitExclusiveState_r instead, but not waiting is faster and
8112 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8113 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8121 #else /* AFS_DEMAND_ATTACH_FS */
8122 static struct volHeader*
8123 GetVolHeaderFromLRU(void)
8125 struct volHeader *hd = NULL;
8126 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8127 hd = queue_First(&volume_hdr_LRU, volHeader);
8132 #endif /* !AFS_DEMAND_ATTACH_FS */
8135 * get a volume header and attach it to the volume object.
8137 * @param[in] vp pointer to volume object
8139 * @return cache entry status
8140 * @retval 0 volume header was newly attached; cache data is invalid
8141 * @retval 1 volume header was previously attached; cache data is valid
8143 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8145 * @post volume header attached to volume object. if necessary, header cache
8146 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8148 * @note VOL_LOCK may be dropped
8150 * @warning this interface does not load header data from disk. it merely
8151 * attaches a header object to the volume object, and may sync the old
8152 * header cache data out to disk in the process.
8154 * @internal volume package internal use only.
8157 GetVolumeHeader(Volume * vp)
8160 struct volHeader *hd;
8162 static int everLogged = 0;
8164 #ifdef AFS_DEMAND_ATTACH_FS
8165 VolState vp_save = 0, back_save = 0;
8167 /* XXX debug 9/19/05 we've apparently got
8168 * a ref counting bug somewhere that's
8169 * breaking the nUsers == 0 => header on LRU
8171 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8172 Log("nUsers == 0, but header not on LRU\n");
8177 old = (vp->header != NULL); /* old == volume already has a header */
8179 if (programType != fileServer) {
8180 /* for volume utilities, we allocate volHeaders as needed */
8182 hd = calloc(1, sizeof(*vp->header));
8183 opr_Assert(hd != NULL);
8186 #ifdef AFS_DEMAND_ATTACH_FS
8187 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8191 /* for the fileserver, we keep a volume header cache */
8193 /* the header we previously dropped in the lru is
8194 * still available. pull it off the lru and return */
8197 opr_Assert(hd->back == vp);
8198 #ifdef AFS_DEMAND_ATTACH_FS
8199 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8202 hd = GetVolHeaderFromLRU();
8204 /* LRU is empty, so allocate a new volHeader
8205 * this is probably indicative of a leak, so let the user know */
8206 hd = calloc(1, sizeof(struct volHeader));
8207 opr_Assert(hd != NULL);
8209 Log("****Allocated more volume headers, probably leak****\n");
8212 volume_hdr_LRU.stats.free++;
8215 /* this header used to belong to someone else.
8216 * we'll need to check if the header needs to
8217 * be sync'd out to disk */
8219 #ifdef AFS_DEMAND_ATTACH_FS
8220 /* GetVolHeaderFromLRU had better not give us back a header
8221 * with a volume in exclusive state... */
8222 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8225 if (hd->diskstuff.inUse) {
8226 /* volume was in use, so we'll need to sync
8227 * its header to disk */
8229 #ifdef AFS_DEMAND_ATTACH_FS
8230 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8231 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8232 VCreateReservation_r(hd->back);
8236 WriteVolumeHeader_r(&error, hd->back);
8237 /* Ignore errors; catch them later */
8239 #ifdef AFS_DEMAND_ATTACH_FS
8244 hd->back->header = NULL;
8245 #ifdef AFS_DEMAND_ATTACH_FS
8246 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8248 if (hd->diskstuff.inUse) {
8249 VChangeState_r(hd->back, back_save);
8250 VCancelReservation_r(hd->back);
8251 VChangeState_r(vp, vp_save);
8255 volume_hdr_LRU.stats.attached++;
8259 #ifdef AFS_DEMAND_ATTACH_FS
8260 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8263 volume_hdr_LRU.stats.free--;
8264 volume_hdr_LRU.stats.used++;
8266 IncUInt64(&VStats.hdr_gets);
8267 #ifdef AFS_DEMAND_ATTACH_FS
8268 IncUInt64(&vp->stats.hdr_gets);
8269 vp->stats.last_hdr_get = FT_ApproxTime();
8276 * make sure volume header is attached and contains valid cache data.
8278 * @param[out] ec outbound error code
8279 * @param[in] vp pointer to volume object
8281 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8283 * @post header cache entry attached, and loaded with valid data, or
8284 * *ec is nonzero, and the header is released back into the LRU.
8286 * @internal volume package internal use only.
8289 LoadVolumeHeader(Error * ec, Volume * vp)
8291 #ifdef AFS_DEMAND_ATTACH_FS
8292 VolState state_save;
8296 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8297 IncUInt64(&VStats.hdr_loads);
8298 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8301 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8302 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8304 IncUInt64(&vp->stats.hdr_loads);
8305 now = FT_ApproxTime();
8309 V_attachFlags(vp) |= VOL_HDR_LOADED;
8310 vp->stats.last_hdr_load = now;
8312 VChangeState_r(vp, state_save);
8314 #else /* AFS_DEMAND_ATTACH_FS */
8316 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8317 IncUInt64(&VStats.hdr_loads);
8319 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8320 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8323 #endif /* AFS_DEMAND_ATTACH_FS */
8325 /* maintain (nUsers==0) => header in LRU invariant */
8326 FreeVolumeHeader(vp);
8331 * release a header cache entry back into the LRU list.
8333 * @param[in] hd pointer to volume header cache object
8335 * @pre VOL_LOCK held.
8337 * @post header cache object appended onto end of LRU list.
8339 * @note only applicable to fileServer program type.
8341 * @note used to place a header cache entry back into the
8342 * LRU pool without invalidating it as a cache entry.
8344 * @internal volume package internal use only.
8347 ReleaseVolumeHeader(struct volHeader *hd)
8349 if (programType != fileServer)
8351 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8353 queue_Append(&volume_hdr_LRU, hd);
8354 #ifdef AFS_DEMAND_ATTACH_FS
8356 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8359 volume_hdr_LRU.stats.free++;
8360 volume_hdr_LRU.stats.used--;
8364 * free/invalidate a volume header cache entry.
8366 * @param[in] vp pointer to volume object
8368 * @pre VOL_LOCK is held.
8370 * @post For fileserver, header cache entry is returned to LRU, and it is
8371 * invalidated as a cache entry. For volume utilities, the header
8372 * cache entry is freed.
8374 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8375 * whenever it is necessary to invalidate the header cache entry.
8377 * @see ReleaseVolumeHeader
8379 * @internal volume package internal use only.
8382 FreeVolumeHeader(Volume * vp)
8384 struct volHeader *hd = vp->header;
8387 if (programType == fileServer) {
8388 ReleaseVolumeHeader(hd);
8393 #ifdef AFS_DEMAND_ATTACH_FS
8394 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8396 volume_hdr_LRU.stats.attached--;
8401 /***************************************************/
8402 /* Volume Hash Table routines */
8403 /***************************************************/
8406 * set size of volume object hash table.
8408 * @param[in] logsize log(2) of desired hash table size
8410 * @return operation status
8412 * @retval -1 failure
8414 * @pre MUST be called prior to VInitVolumePackage2
8416 * @post Volume Hash Table will have 2^logsize buckets
8419 VSetVolHashSize(int logsize)
8421 /* 64 to 268435456 hash buckets seems like a reasonable range */
8422 if ((logsize < 6 ) || (logsize > 28)) {
8427 VolumeHashTable.Size = opr_jhash_size(logsize);
8428 VolumeHashTable.Mask = opr_jhash_mask(logsize);
8430 /* we can't yet support runtime modification of this
8431 * parameter. we'll need a configuration rwlock to
8432 * make runtime modification feasible.... */
8439 * initialize dynamic data structures for volume hash table.
8441 * @post hash table is allocated, and fields are initialized.
8443 * @internal volume package internal use only.
8446 VInitVolumeHash(void)
8450 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8451 sizeof(VolumeHashChainHead));
8452 opr_Assert(VolumeHashTable.Table != NULL);
8454 for (i=0; i < VolumeHashTable.Size; i++) {
8455 queue_Init(&VolumeHashTable.Table[i]);
8456 #ifdef AFS_DEMAND_ATTACH_FS
8457 opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8458 #endif /* AFS_DEMAND_ATTACH_FS */
8463 * add a volume object to the hash table.
8465 * @param[in] vp pointer to volume object
8466 * @param[in] hashid hash of volume id
8468 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8471 * @post volume is added to hash chain.
8473 * @internal volume package internal use only.
8475 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8476 * asynchronous hash chain reordering to finish.
8479 AddVolumeToHashTable(Volume * vp, VolumeId hashid)
8481 VolumeHashChainHead * head;
8483 if (queue_IsOnQueue(vp))
8486 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8488 #ifdef AFS_DEMAND_ATTACH_FS
8489 /* wait for the hash chain to become available */
8492 V_attachFlags(vp) |= VOL_IN_HASH;
8493 vp->chainCacheCheck = ++head->cacheCheck;
8494 #endif /* AFS_DEMAND_ATTACH_FS */
8497 vp->hashid = hashid;
8498 queue_Append(head, vp);
8502 * delete a volume object from the hash table.
8504 * @param[in] vp pointer to volume object
8506 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8509 * @post volume is removed from hash chain.
8511 * @internal volume package internal use only.
8513 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8514 * asynchronous hash chain reordering to finish.
8517 DeleteVolumeFromHashTable(Volume * vp)
8519 VolumeHashChainHead * head;
8521 if (!queue_IsOnQueue(vp))
8524 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8526 #ifdef AFS_DEMAND_ATTACH_FS
8527 /* wait for the hash chain to become available */
8530 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8532 #endif /* AFS_DEMAND_ATTACH_FS */
8536 /* do NOT reset hashid to zero, as the online
8537 * salvager package may need to know the volume id
8538 * after the volume is removed from the hash */
8542 * lookup a volume object in the hash table given a volume id.
8544 * @param[out] ec error code return
8545 * @param[in] volumeId volume id
8546 * @param[in] hint volume object which we believe could be the correct
8549 * @return volume object pointer
8550 * @retval NULL no such volume id is registered with the hash table.
8552 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8555 * @post volume object with the given id is returned. volume object and
8556 * hash chain access statistics are updated. hash chain may have
8559 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8560 * asynchronous hash chain reordering operation to finish, or
8561 * in order for us to perform an asynchronous chain reordering.
8563 * @note Hash chain reorderings occur when the access count for the
8564 * volume object being looked up exceeds the sum of the previous
8565 * node's (the node ahead of it in the hash chain linked list)
8566 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8568 * @note For DAFS, the hint parameter allows us to short-circuit if the
8569 * cacheCheck fields match between the hash chain head and the
8570 * hint volume object.
8573 VLookupVolume_r(Error * ec, VolumeId volumeId, Volume * hint)
8577 #ifdef AFS_DEMAND_ATTACH_FS
8580 VolumeHashChainHead * head;
8583 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8585 #ifdef AFS_DEMAND_ATTACH_FS
8586 /* wait for the hash chain to become available */
8589 /* check to see if we can short circuit without walking the hash chain */
8590 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8591 IncUInt64(&hint->stats.hash_short_circuits);
8594 #endif /* AFS_DEMAND_ATTACH_FS */
8596 /* someday we need to either do per-chain locks, RWlocks,
8597 * or both for volhash access.
8598 * (and move to a data structure with better cache locality) */
8600 /* search the chain for this volume id */
8601 for(queue_Scan(head, vp, np, Volume)) {
8603 if (vp->hashid == volumeId) {
8608 if (queue_IsEnd(head, vp)) {
8612 #ifdef AFS_DEMAND_ATTACH_FS
8613 /* update hash chain statistics */
8616 FillInt64(lks, 0, looks);
8617 AddUInt64(head->looks, lks, &head->looks);
8618 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8619 IncUInt64(&head->gets);
8624 IncUInt64(&vp->stats.hash_lookups);
8626 /* for demand attach fileserver, we permit occasional hash chain reordering
8627 * so that frequently looked up volumes move towards the head of the chain */
8628 pp = queue_Prev(vp, Volume);
8629 if (!queue_IsEnd(head, pp)) {
8630 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8631 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8632 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8633 VReorderHash_r(head, pp, vp);
8637 /* update the short-circuit cache check */
8638 vp->chainCacheCheck = head->cacheCheck;
8640 #endif /* AFS_DEMAND_ATTACH_FS */
8645 #ifdef AFS_DEMAND_ATTACH_FS
8646 /* perform volume hash chain reordering.
8648 * advance a subchain beginning at vp ahead of
8649 * the adjacent subchain ending at pp */
8651 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8653 Volume *tp, *np, *lp;
8654 afs_uint64 move_thresh;
8656 /* this should never be called if the chain is already busy, so
8657 * no need to wait for other exclusive chain ops to finish */
8659 /* this is a rather heavy set of operations,
8660 * so let's set the chain busy flag and drop
8662 VHashBeginExclusive_r(head);
8665 /* scan forward in the chain from vp looking for the last element
8666 * in the chain we want to advance */
8667 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8668 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8669 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8670 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8674 lp = queue_Prev(tp, Volume);
8676 /* scan backwards from pp to determine where to splice and
8677 * insert the subchain we're advancing */
8678 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8679 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8683 tp = queue_Next(tp, Volume);
8685 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8686 queue_MoveChainBefore(tp,vp,lp);
8689 IncUInt64(&VStats.hash_reorders);
8691 IncUInt64(&head->reorders);
8693 /* wake up any threads waiting for the hash chain */
8694 VHashEndExclusive_r(head);
8698 /* demand-attach fs volume hash
8699 * asynchronous exclusive operations */
8702 * begin an asynchronous exclusive operation on a volume hash chain.
8704 * @param[in] head pointer to volume hash chain head object
8706 * @pre VOL_LOCK held. hash chain is quiescent.
8708 * @post hash chain marked busy.
8710 * @note this interface is used in conjunction with VHashEndExclusive_r and
8711 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8712 * volume hash chain. Its main use case is hash chain reordering, which
8713 * has the potential to be a highly latent operation.
8715 * @see VHashEndExclusive_r
8720 * @internal volume package internal use only.
8723 VHashBeginExclusive_r(VolumeHashChainHead * head)
8725 opr_Assert(head->busy == 0);
8730 * relinquish exclusive ownership of a volume hash chain.
8732 * @param[in] head pointer to volume hash chain head object
8734 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8736 * @post hash chain is marked quiescent. threads awaiting use of
8737 * chain are awakened.
8739 * @see VHashBeginExclusive_r
8744 * @internal volume package internal use only.
8747 VHashEndExclusive_r(VolumeHashChainHead * head)
8749 opr_Assert(head->busy);
8751 opr_cv_broadcast(&head->chain_busy_cv);
8755 * wait for all asynchronous operations on a hash chain to complete.
8757 * @param[in] head pointer to volume hash chain head object
8759 * @pre VOL_LOCK held.
8761 * @post hash chain object is quiescent.
8763 * @see VHashBeginExclusive_r
8764 * @see VHashEndExclusive_r
8768 * @note This interface should be called before any attempt to
8769 * traverse the hash chain. It is permissible for a thread
8770 * to gain exclusive access to the chain, and then perform
8771 * latent operations on the chain asynchronously wrt the
8774 * @warning if waiting is necessary, VOL_LOCK is dropped
8776 * @internal volume package internal use only.
8779 VHashWait_r(VolumeHashChainHead * head)
8781 while (head->busy) {
8782 VOL_CV_WAIT(&head->chain_busy_cv);
8785 #endif /* AFS_DEMAND_ATTACH_FS */
8788 /***************************************************/
8789 /* Volume by Partition List routines */
8790 /***************************************************/
8793 * demand attach fileserver adds a
8794 * linked list of volumes to each
8795 * partition object, thus allowing
8796 * for quick enumeration of all
8797 * volumes on a partition
8800 #ifdef AFS_DEMAND_ATTACH_FS
8802 * add a volume to its disk partition VByPList.
8804 * @param[in] vp pointer to volume object
8806 * @pre either the disk partition VByPList is owned exclusively
8807 * by the calling thread, or the list is quiescent and
8810 * @post volume is added to disk partition VByPList
8814 * @warning it is the caller's responsibility to ensure list
8817 * @see VVByPListWait_r
8818 * @see VVByPListBeginExclusive_r
8819 * @see VVByPListEndExclusive_r
8821 * @internal volume package internal use only.
8824 AddVolumeToVByPList_r(Volume * vp)
8826 if (queue_IsNotOnQueue(&vp->vol_list)) {
8827 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8828 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8829 vp->partition->vol_list.len++;
8834 * delete a volume from its disk partition VByPList.
8836 * @param[in] vp pointer to volume object
8838 * @pre either the disk partition VByPList is owned exclusively
8839 * by the calling thread, or the list is quiescent and
8842 * @post volume is removed from the disk partition VByPList
8846 * @warning it is the caller's responsibility to ensure list
8849 * @see VVByPListWait_r
8850 * @see VVByPListBeginExclusive_r
8851 * @see VVByPListEndExclusive_r
8853 * @internal volume package internal use only.
8856 DeleteVolumeFromVByPList_r(Volume * vp)
8858 if (queue_IsOnQueue(&vp->vol_list)) {
8859 queue_Remove(&vp->vol_list);
8860 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8861 vp->partition->vol_list.len--;
8866 * begin an asynchronous exclusive operation on a VByPList.
8868 * @param[in] dp pointer to disk partition object
8870 * @pre VOL_LOCK held. VByPList is quiescent.
8872 * @post VByPList marked busy.
8874 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8875 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8878 * @see VVByPListEndExclusive_r
8879 * @see VVByPListWait_r
8883 * @internal volume package internal use only.
8885 /* take exclusive control over the list */
8887 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8889 opr_Assert(dp->vol_list.busy == 0);
8890 dp->vol_list.busy = 1;
8894 * relinquish exclusive ownership of a VByPList.
8896 * @param[in] dp pointer to disk partition object
8898 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8900 * @post VByPList is marked quiescent. threads awaiting use of
8901 * the list are awakened.
8903 * @see VVByPListBeginExclusive_r
8904 * @see VVByPListWait_r
8908 * @internal volume package internal use only.
8911 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8913 opr_Assert(dp->vol_list.busy);
8914 dp->vol_list.busy = 0;
8915 opr_cv_broadcast(&dp->vol_list.cv);
8919 * wait for all asynchronous operations on a VByPList to complete.
8921 * @param[in] dp pointer to disk partition object
8923 * @pre VOL_LOCK is held.
8925 * @post disk partition's VByP list is quiescent
8929 * @note This interface should be called before any attempt to
8930 * traverse the VByPList. It is permissible for a thread
8931 * to gain exclusive access to the list, and then perform
8932 * latent operations on the list asynchronously wrt the
8935 * @warning if waiting is necessary, VOL_LOCK is dropped
8937 * @see VVByPListEndExclusive_r
8938 * @see VVByPListBeginExclusive_r
8940 * @internal volume package internal use only.
8943 VVByPListWait_r(struct DiskPartition64 * dp)
8945 while (dp->vol_list.busy) {
8946 VOL_CV_WAIT(&dp->vol_list.cv);
8949 #endif /* AFS_DEMAND_ATTACH_FS */
8951 /***************************************************/
8952 /* Volume Cache Statistics routines */
8953 /***************************************************/
8956 VPrintCacheStats_r(void)
8958 struct VnodeClassInfo *vcp;
8959 vcp = &VnodeClassInfo[vLarge];
8960 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);
8961 vcp = &VnodeClassInfo[vSmall];
8962 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);
8963 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8964 "%"AFS_INT64_FMT" replacements\n",
8965 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8969 VPrintCacheStats(void)
8972 VPrintCacheStats_r();
8976 #ifdef AFS_DEMAND_ATTACH_FS
8978 UInt64ToDouble(afs_uint64 * x)
8980 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8982 SplitInt64(*x, h, l);
8983 return (((double)h) * c32) + ((double) l);
8987 DoubleToPrintable(double x, char * buf, int len)
8989 static double billion = 1000000000.0;
8992 y[0] = (afs_uint32) (x / (billion * billion));
8993 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8994 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8997 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8999 snprintf(buf, len, "%d%09d", y[1], y[2]);
9001 snprintf(buf, len, "%d", y[2]);
9007 struct VLRUExtStatsEntry {
9011 struct VLRUExtStats {
9017 } queue_info[VLRU_QUEUE_INVALID];
9018 struct VLRUExtStatsEntry * vec;
9022 * add a 256-entry fudge factor onto the vector in case state changes
9023 * out from under us.
9025 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
9028 * collect extended statistics for the VLRU subsystem.
9030 * @param[out] stats pointer to stats structure to be populated
9031 * @param[in] nvols number of volumes currently known to exist
9033 * @pre VOL_LOCK held
9035 * @post stats->vec allocated and populated
9037 * @return operation status
9042 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
9044 afs_uint32 cur, idx, len;
9045 struct rx_queue * qp, * nqp;
9047 struct VLRUExtStatsEntry * vec;
9049 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
9050 vec = stats->vec = calloc(len,
9051 sizeof(struct VLRUExtStatsEntry));
9057 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9058 VLRU_Wait_r(&volume_LRU.q[idx]);
9059 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
9062 stats->queue_info[idx].start = cur;
9064 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
9066 /* out of space in vec */
9069 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
9070 vec[cur].volid = vp->hashid;
9074 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9077 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9085 #define ENUMTOSTRING(en) #en
9086 #define ENUMCASE(en) \
9087 case en: return ENUMTOSTRING(en)
9090 vlru_idx_to_string(int idx)
9093 ENUMCASE(VLRU_QUEUE_NEW);
9094 ENUMCASE(VLRU_QUEUE_MID);
9095 ENUMCASE(VLRU_QUEUE_OLD);
9096 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9097 ENUMCASE(VLRU_QUEUE_HELD);
9098 ENUMCASE(VLRU_QUEUE_INVALID);
9100 return "**UNKNOWN**";
9105 VPrintExtendedCacheStats_r(int flags)
9108 afs_uint32 vol_sum = 0;
9115 struct stats looks, gets, reorders, len;
9116 struct stats ch_looks, ch_gets, ch_reorders;
9118 VolumeHashChainHead *head;
9120 struct VLRUExtStats vlru_stats;
9122 /* zero out stats */
9123 memset(&looks, 0, sizeof(struct stats));
9124 memset(&gets, 0, sizeof(struct stats));
9125 memset(&reorders, 0, sizeof(struct stats));
9126 memset(&len, 0, sizeof(struct stats));
9127 memset(&ch_looks, 0, sizeof(struct stats));
9128 memset(&ch_gets, 0, sizeof(struct stats));
9129 memset(&ch_reorders, 0, sizeof(struct stats));
9131 for (i = 0; i < VolumeHashTable.Size; i++) {
9132 head = &VolumeHashTable.Table[i];
9135 VHashBeginExclusive_r(head);
9138 ch_looks.sum = UInt64ToDouble(&head->looks);
9139 ch_gets.sum = UInt64ToDouble(&head->gets);
9140 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9142 /* update global statistics */
9144 looks.sum += ch_looks.sum;
9145 gets.sum += ch_gets.sum;
9146 reorders.sum += ch_reorders.sum;
9147 len.sum += (double)head->len;
9148 vol_sum += head->len;
9151 len.min = (double) head->len;
9152 len.max = (double) head->len;
9153 looks.min = ch_looks.sum;
9154 looks.max = ch_looks.sum;
9155 gets.min = ch_gets.sum;
9156 gets.max = ch_gets.sum;
9157 reorders.min = ch_reorders.sum;
9158 reorders.max = ch_reorders.sum;
9160 if (((double)head->len) < len.min)
9161 len.min = (double) head->len;
9162 if (((double)head->len) > len.max)
9163 len.max = (double) head->len;
9164 if (ch_looks.sum < looks.min)
9165 looks.min = ch_looks.sum;
9166 else if (ch_looks.sum > looks.max)
9167 looks.max = ch_looks.sum;
9168 if (ch_gets.sum < gets.min)
9169 gets.min = ch_gets.sum;
9170 else if (ch_gets.sum > gets.max)
9171 gets.max = ch_gets.sum;
9172 if (ch_reorders.sum < reorders.min)
9173 reorders.min = ch_reorders.sum;
9174 else if (ch_reorders.sum > reorders.max)
9175 reorders.max = ch_reorders.sum;
9179 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9180 /* compute detailed per-chain stats */
9181 struct stats hdr_loads, hdr_gets;
9182 double v_looks, v_loads, v_gets;
9184 /* initialize stats with data from first element in chain */
9185 vp = queue_First(head, Volume);
9186 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9187 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9188 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9189 ch_gets.min = ch_gets.max = v_looks;
9190 hdr_loads.min = hdr_loads.max = v_loads;
9191 hdr_gets.min = hdr_gets.max = v_gets;
9192 hdr_loads.sum = hdr_gets.sum = 0;
9194 vp = queue_Next(vp, Volume);
9196 /* pull in stats from remaining elements in chain */
9197 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9198 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9199 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9200 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9202 hdr_loads.sum += v_loads;
9203 hdr_gets.sum += v_gets;
9205 if (v_looks < ch_gets.min)
9206 ch_gets.min = v_looks;
9207 else if (v_looks > ch_gets.max)
9208 ch_gets.max = v_looks;
9210 if (v_loads < hdr_loads.min)
9211 hdr_loads.min = v_loads;
9212 else if (v_loads > hdr_loads.max)
9213 hdr_loads.max = v_loads;
9215 if (v_gets < hdr_gets.min)
9216 hdr_gets.min = v_gets;
9217 else if (v_gets > hdr_gets.max)
9218 hdr_gets.max = v_gets;
9221 /* compute per-chain averages */
9222 ch_gets.avg = ch_gets.sum / ((double)head->len);
9223 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9224 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9226 /* dump per-chain stats */
9227 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9229 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9230 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9231 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9232 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9233 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9234 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9235 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9236 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9237 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9238 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9239 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9240 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9241 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9242 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9243 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9244 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9245 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9246 } else if (flags & VOL_STATS_PER_CHAIN) {
9247 /* dump simple per-chain stats */
9248 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9250 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9251 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9252 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9256 VHashEndExclusive_r(head);
9261 /* compute global averages */
9262 len.avg = len.sum / ((double)VolumeHashTable.Size);
9263 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9264 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9265 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9267 /* dump global stats */
9268 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9269 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9270 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9271 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9272 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9273 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9274 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9275 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9276 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9277 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9278 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9279 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9280 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9281 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9282 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9283 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9284 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9285 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9286 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9287 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9288 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9290 /* print extended disk related statistics */
9292 struct DiskPartition64 * diskP;
9293 afs_uint32 vol_count[VOLMAXPARTS+1];
9294 byte part_exists[VOLMAXPARTS+1];
9298 memset(vol_count, 0, sizeof(vol_count));
9299 memset(part_exists, 0, sizeof(part_exists));
9303 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9305 vol_count[id] = diskP->vol_list.len;
9306 part_exists[id] = 1;
9310 for (i = 0; i <= VOLMAXPARTS; i++) {
9311 if (part_exists[i]) {
9312 /* XXX while this is currently safe, it is a violation
9313 * of the VGetPartitionById_r interface contract. */
9314 diskP = VGetPartitionById_r(i, 0);
9316 Log("Partition %s has %d online volumes\n",
9317 VPartitionPath(diskP), diskP->vol_list.len);
9324 /* print extended VLRU statistics */
9325 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9326 afs_uint32 idx, cur, lpos;
9331 Log("VLRU State Dump:\n\n");
9333 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9334 Log("\t%s:\n", vlru_idx_to_string(idx));
9337 for (cur = vlru_stats.queue_info[idx].start;
9338 cur < vlru_stats.queue_info[idx].len;
9340 line[lpos++] = vlru_stats.vec[cur].volid;
9342 Log("\t\t%u, %u, %u, %u, %u,\n",
9343 line[0], line[1], line[2], line[3], line[4]);
9352 Log("\t\t%u, %u, %u, %u, %u\n",
9353 line[0], line[1], line[2], line[3], line[4]);
9358 free(vlru_stats.vec);
9365 VPrintExtendedCacheStats(int flags)
9368 VPrintExtendedCacheStats_r(flags);
9371 #endif /* AFS_DEMAND_ATTACH_FS */
9374 VCanScheduleSalvage(void)
9376 return vol_opts.canScheduleSalvage;
9382 return vol_opts.canUseFSSYNC;
9386 VCanUseSALVSYNC(void)
9388 return vol_opts.canUseSALVSYNC;
9392 VCanUnsafeAttach(void)
9394 return vol_opts.unsafe_attach;