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 FreeVolumeHeader(vp);
3476 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3478 error_state = VOL_STATE_ERROR;
3479 /* see if we can recover */
3480 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3485 #endif /* AFS_DEMAND_ATTACH_FS */
3487 #ifdef AFS_DEMAND_ATTACH_FS
3488 if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3489 V_inUse(vp) = programType;
3490 #endif /* AFS_DEMAND_ATTACH_FS */
3491 V_checkoutMode(vp) = mode;
3494 AddVolumeToHashTable(vp, vp->hashid);
3495 #ifdef AFS_DEMAND_ATTACH_FS
3496 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3499 if ((programType != fileServer) ||
3500 (V_inUse(vp) == fileServer)) {
3501 AddVolumeToVByPList_r(vp);
3503 VChangeState_r(vp, VOL_STATE_ATTACHED);
3505 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3514 #ifdef AFS_DEMAND_ATTACH_FS
3515 if (!VIsErrorState(V_attachState(vp))) {
3516 if (programType != fileServer && *ec == VNOVOL) {
3517 /* do not log anything in this case; it is common for
3518 * non-fileserver programs to fail here with VNOVOL, since that
3519 * is what happens when they simply try to use a volume, but that
3520 * volume doesn't exist. */
3522 } else if (VIsErrorState(error_state)) {
3523 Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3524 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3525 V_attachFlags(vp), *ec);
3527 VChangeState_r(vp, error_state);
3529 #endif /* AFS_DEMAND_ATTACH_FS */
3532 VReleaseVolumeHandles_r(vp);
3535 #ifdef AFS_DEMAND_ATTACH_FS
3537 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3538 /* The salvage could not be scheduled with the salvage server
3539 * due to a hard error. Reset the error code to prevent retry loops by
3541 if (*ec == VSALVAGING) {
3550 #else /* !AFS_DEMAND_ATTACH_FS */
3552 #endif /* !AFS_DEMAND_ATTACH_FS */
3556 /* Attach an existing volume.
3557 The volume also normally goes online at this time.
3558 An offline volume must be reattached to make it go online.
3562 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3566 retVal = VAttachVolume_r(ec, volumeId, mode);
3572 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3575 VGetVolumePath(ec, volumeId, &part, &name);
3579 vp = VGetVolume_r(&error, volumeId);
3581 opr_Assert(V_inUse(vp) == 0);
3582 VDetachVolume_r(ec, vp);
3586 return VAttachVolumeByName_r(ec, part, name, mode);
3589 /* Increment a reference count to a volume, sans context swaps. Requires
3590 * possibly reading the volume header in from the disk, since there's
3591 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3593 * N.B. This call can fail if we can't read in the header!! In this case
3594 * we still guarantee we won't context swap, but the ref count won't be
3595 * incremented (otherwise we'd violate the invariant).
3597 /* NOTE: with the demand attach fileserver extensions, the global lock
3598 * is dropped within VHold */
3599 #ifdef AFS_DEMAND_ATTACH_FS
3601 VHold_r(Volume * vp)
3605 VCreateReservation_r(vp);
3606 VWaitExclusiveState_r(vp);
3608 LoadVolumeHeader(&error, vp);
3610 VCancelReservation_r(vp);
3614 VCancelReservation_r(vp);
3617 #else /* AFS_DEMAND_ATTACH_FS */
3619 VHold_r(Volume * vp)
3623 LoadVolumeHeader(&error, vp);
3629 #endif /* AFS_DEMAND_ATTACH_FS */
3631 /**** volume timeout-related stuff ****/
3633 #ifdef AFS_PTHREAD_ENV
3635 static struct timespec *shutdown_timeout;
3636 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3639 VTimedOut(const struct timespec *ts)
3644 if (ts->tv_sec == 0) {
3645 /* short-circuit; this will have always timed out */
3649 code = gettimeofday(&tv, NULL);
3651 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3652 /* assume no timeout; failure mode is we just wait longer than normal
3653 * instead of returning errors when we shouldn't */
3657 if (tv.tv_sec < ts->tv_sec ||
3658 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3667 * Calculate an absolute timeout.
3669 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3670 * NULL, the memory is not touched
3671 * @param[in] timeout How long the timeout should be from now
3673 * @return timeout to use
3674 * @retval NULL no timeout; wait forever
3675 * @retval non-NULL the given value for "ts"
3679 static struct timespec *
3680 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3690 ts->tv_sec = ts->tv_nsec = 0;
3694 code = gettimeofday(&now, NULL);
3696 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3700 ts->tv_sec = now.tv_sec + timeout;
3701 ts->tv_nsec = now.tv_usec * 1000;
3707 * Initialize the shutdown_timeout global.
3710 VShutdownTimeoutInit(void)
3712 struct timespec *ts;
3714 ts = malloc(sizeof(*ts));
3716 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3718 if (!shutdown_timeout) {
3724 * Figure out the timeout that should be used for waiting for offline volumes.
3726 * @param[out] ats Storage space for a local timeout value if needed
3728 * @return The timeout value that should be used
3729 * @retval NULL No timeout; wait forever for offlining volumes
3730 * @retval non-NULL A pointer to the absolute time that should be used as
3731 * the deadline for waiting for offlining volumes.
3733 * @note If we return non-NULL, the pointer we return may or may not be the
3736 static const struct timespec *
3737 VOfflineTimeout(struct timespec *ats)
3739 if (vol_shutting_down) {
3740 opr_Verify(pthread_once(&shutdown_timeout_once,
3741 VShutdownTimeoutInit) == 0);
3742 return shutdown_timeout;
3744 return VCalcTimeout(ats, vol_opts.offline_timeout);
3748 #else /* AFS_PTHREAD_ENV */
3750 /* Waiting a certain amount of time for offlining volumes is not supported
3751 * for LWP due to a lack of primitives. So, we never time out */
3752 # define VTimedOut(x) (0)
3753 # define VOfflineTimeout(x) (NULL)
3755 #endif /* !AFS_PTHREAD_ENV */
3763 retVal = VHold_r(vp);
3770 VIsGoingOffline_r(struct Volume *vp)
3774 if (vp->goingOffline) {
3775 if (vp->specialStatus) {
3776 code = vp->specialStatus;
3777 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3788 * Tell the caller if a volume is waiting to go offline.
3790 * @param[in] vp The volume we want to know about
3792 * @return volume status
3793 * @retval 0 volume is not waiting to go offline, go ahead and use it
3794 * @retval nonzero volume is waiting to offline, and give the returned code
3795 * as an error to anyone accessing the volume
3797 * @pre VOL_LOCK is NOT held
3798 * @pre caller holds a heavyweight reference on vp
3801 VIsGoingOffline(struct Volume *vp)
3806 code = VIsGoingOffline_r(vp);
3813 * Register an RX call with a volume.
3815 * @param[inout] ec Error code; if unset when passed in, may be set if
3816 * the volume starts going offline
3817 * @param[out] client_ec @see GetVolume
3818 * @param[in] vp Volume struct
3819 * @param[in] cbv VCallByVol struct containing the RX call to register
3821 * @pre VOL_LOCK held
3822 * @pre caller holds heavy ref on vp
3827 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3830 #ifdef AFS_DEMAND_ATTACH_FS
3832 /* just in case the volume started going offline after we got the
3833 * reference to it... otherwise, if the volume started going
3834 * offline right at the end of GetVolume(), we might race with the
3835 * RX call scanner, and return success and add our cbv to the
3836 * rx_call_list _after_ the scanner has scanned the list. */
3837 *ec = VIsGoingOffline_r(vp);
3843 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3844 VWaitStateChange_r(vp);
3846 #endif /* AFS_DEMAND_ATTACH_FS */
3848 queue_Prepend(&vp->rx_call_list, cbv);
3853 * Deregister an RX call with a volume.
3855 * @param[in] vp Volume struct
3856 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3858 * @pre VOL_LOCK held
3859 * @pre caller holds heavy ref on vp
3864 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3866 if (cbv && queue_IsOnQueue(cbv)) {
3867 #ifdef AFS_DEMAND_ATTACH_FS
3868 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3869 VWaitStateChange_r(vp);
3871 #endif /* AFS_DEMAND_ATTACH_FS */
3877 /***************************************************/
3878 /* get and put volume routines */
3879 /***************************************************/
3882 * put back a heavyweight reference to a volume object.
3884 * @param[in] vp volume object pointer
3886 * @pre VOL_LOCK held
3888 * @post heavyweight volume reference put back.
3889 * depending on state, volume may have been taken offline,
3890 * detached, salvaged, freed, etc.
3892 * @internal volume package internal use only
3895 VPutVolume_r(Volume * vp)
3897 opr_Verify(--vp->nUsers >= 0);
3898 if (vp->nUsers == 0) {
3900 ReleaseVolumeHeader(vp->header);
3901 #ifdef AFS_DEMAND_ATTACH_FS
3902 if (!VCheckDetach(vp)) {
3906 #else /* AFS_DEMAND_ATTACH_FS */
3908 #endif /* AFS_DEMAND_ATTACH_FS */
3913 VPutVolume(Volume * vp)
3921 * Puts a volume reference obtained with VGetVolumeWithCall.
3923 * @param[in] vp Volume struct
3924 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3926 * @pre VOL_LOCK is NOT held
3929 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3932 VDeregisterCall_r(vp, cbv);
3937 /* Get a pointer to an attached volume. The pointer is returned regardless
3938 of whether or not the volume is in service or on/off line. An error
3939 code, however, is returned with an indication of the volume's status */
3941 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3945 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3951 * Get a volume reference associated with an RX call.
3953 * @param[out] ec @see GetVolume
3954 * @param[out] client_ec @see GetVolume
3955 * @param[in] volumeId @see GetVolume
3956 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3957 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3958 * with an error if the volume is going offline.
3959 * @param[in] cbv Contains an RX call to be associated with this volume
3960 * reference. This call may be interrupted if the volume is
3961 * requested to go offline while we hold a ref on it. Give NULL
3962 * to not associate an RX call with this reference.
3964 * @return @see GetVolume
3966 * @note for LWP builds, ts must be NULL
3968 * @note A reference obtained with this function MUST be put back with
3969 * VPutVolumeWithCall
3972 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3973 const struct timespec *ts, struct VCallByVol *cbv)
3977 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3978 VRegisterCall_r(ec, client_ec, retVal, cbv);
3984 VGetVolume_r(Error * ec, VolumeId volumeId)
3986 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3989 /* try to get a volume we've previously looked up */
3990 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3992 VGetVolumeByVp_r(Error * ec, Volume * vp)
3994 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3998 * private interface for getting a volume handle
4000 * @param[out] ec error code (0 if no error)
4001 * @param[out] client_ec wire error code to be given to clients
4002 * @param[in] volumeId ID of the volume we want
4003 * @param[in] hint optional hint for hash lookups, or NULL
4004 * @param[in] timeout absolute deadline for waiting for the volume to go
4005 * offline, if it is going offline. NULL to wait forever.
4007 * @return a volume handle for the specified volume
4008 * @retval NULL an error occurred, or the volume is in such a state that
4009 * we cannot load a header or return any volume struct
4011 * @note for DAFS, caller must NOT hold a ref count on 'hint'
4013 * @note 'timeout' is only checked if the volume is actually going offline; so
4014 * if you pass timeout->tv_sec = 0, this will exhibit typical
4015 * nonblocking behavior.
4017 * @note for LWP builds, 'timeout' must be NULL
4020 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
4021 const struct timespec *timeout)
4024 /* pull this profiling/debugging code out of regular builds */
4026 #define VGET_CTR_INC(x) x++
4027 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
4028 0, V7 = 0, V8 = 0, V9 = 0;
4029 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
4031 #define VGET_CTR_INC(x)
4033 #ifdef AFS_DEMAND_ATTACH_FS
4034 Volume *avp, * rvp = hint;
4038 * if VInit is zero, the volume package dynamic
4039 * data structures have not been initialized yet,
4040 * and we must immediately return an error
4046 *client_ec = VOFFLINE;
4051 #ifdef AFS_DEMAND_ATTACH_FS
4053 VCreateReservation_r(rvp);
4055 #endif /* AFS_DEMAND_ATTACH_FS */
4063 vp = VLookupVolume_r(ec, volumeId, vp);
4069 #ifdef AFS_DEMAND_ATTACH_FS
4070 if (rvp && (rvp != vp)) {
4071 /* break reservation on old vp */
4072 VCancelReservation_r(rvp);
4075 #endif /* AFS_DEMAND_ATTACH_FS */
4081 /* Until we have reached an initialization level of 2
4082 * we don't know whether this volume exists or not.
4083 * We can't sleep and retry later because before a volume
4084 * is attached, the caller tries to get it first. Just
4085 * return VOFFLINE and the caller can choose whether to
4086 * retry the command or not. */
4096 IncUInt64(&VStats.hdr_gets);
4098 #ifdef AFS_DEMAND_ATTACH_FS
4099 /* block if someone else is performing an exclusive op on this volume */
4102 VCreateReservation_r(rvp);
4104 VWaitExclusiveState_r(vp);
4106 /* short circuit with VNOVOL in the following circumstances:
4109 * - VOL_STATE_SHUTTING_DOWN
4111 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4112 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4119 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4120 * VNOVOL for VOL_STATE_DELETED
4122 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4123 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4124 (V_attachState(vp) == VOL_STATE_DELETED)) {
4125 if (vp->specialStatus) {
4126 *ec = vp->specialStatus;
4127 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4136 /* allowable states:
4143 if (vp->salvage.requested) {
4144 VUpdateSalvagePriority_r(vp);
4147 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4148 if (vp->specialStatus) {
4149 *ec = vp->specialStatus;
4153 avp = VAttachVolumeByVp_r(ec, vp, 0);
4156 /* VAttachVolumeByVp_r can return a pointer
4157 * != the vp passed to it under certain
4158 * conditions; make sure we don't leak
4159 * reservations if that happens */
4161 VCancelReservation_r(rvp);
4163 VCreateReservation_r(rvp);
4174 if (vp->specialStatus) {
4175 *ec = vp->specialStatus;
4180 if (vp->specialStatus) {
4181 *ec = vp->specialStatus;
4194 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4196 /* see CheckVnode() in afsfileprocs.c for an explanation
4197 * of this error code logic */
4198 afs_uint32 now = FT_ApproxTime();
4199 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4202 *client_ec = VRESTARTING;
4210 if (VIsErrorState(V_attachState(vp))) {
4211 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4212 * it, or transition it out of that state */
4221 * this test MUST happen after VAttachVolymeByVp, so we have no
4222 * conflicting vol op. (attach2 would have errored out if we had one;
4223 * specifically attach_check_vop must have detected a conflicting vop)
4225 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4227 #endif /* AFS_DEMAND_ATTACH_FS */
4229 LoadVolumeHeader(ec, vp);
4232 /* Only log the error if it was a totally unexpected error. Simply
4233 * a missing inode is likely to be caused by the volume being deleted */
4234 if (errno != ENXIO || GetLogLevel() != 0)
4235 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4236 afs_printable_VolumeId_lu(vp->hashid));
4237 #ifdef AFS_DEMAND_ATTACH_FS
4238 if (VCanScheduleSalvage()) {
4239 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4244 #else /* AFS_DEMAND_ATTACH_FS */
4247 #endif /* AFS_DEMAND_ATTACH_FS */
4252 if (vp->shuttingDown) {
4259 if (programType == fileServer) {
4261 if (vp->goingOffline) {
4262 if (timeout && VTimedOut(timeout)) {
4263 /* we've timed out; don't wait for the vol */
4266 #ifdef AFS_DEMAND_ATTACH_FS
4267 /* wait for the volume to go offline */
4268 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4269 VTimedWaitStateChange_r(vp, timeout, NULL);
4271 #elif defined(AFS_PTHREAD_ENV)
4272 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4273 #else /* AFS_PTHREAD_ENV */
4274 /* LWP has no timed wait, so the caller better not be
4276 opr_Assert(!timeout);
4277 LWP_WaitProcess(VPutVolume);
4278 #endif /* AFS_PTHREAD_ENV */
4282 if (vp->specialStatus) {
4284 *ec = vp->specialStatus;
4285 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4288 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4299 #ifdef AFS_DEMAND_ATTACH_FS
4300 /* if no error, bump nUsers */
4303 VLRU_UpdateAccess_r(vp);
4306 VCancelReservation_r(rvp);
4309 if (client_ec && !*client_ec) {
4312 #else /* AFS_DEMAND_ATTACH_FS */
4313 /* if no error, bump nUsers */
4320 #endif /* AFS_DEMAND_ATTACH_FS */
4323 opr_Assert(vp || *ec);
4328 /***************************************************/
4329 /* Volume offline/detach routines */
4330 /***************************************************/
4332 /* caller MUST hold a heavyweight ref on vp */
4333 #ifdef AFS_DEMAND_ATTACH_FS
4335 VTakeOffline_r(Volume * vp)
4339 opr_Assert(vp->nUsers > 0);
4340 opr_Assert(programType == fileServer);
4342 VCreateReservation_r(vp);
4343 VWaitExclusiveState_r(vp);
4345 vp->goingOffline = 1;
4346 V_needsSalvaged(vp) = 1;
4348 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4349 VCancelReservation_r(vp);
4351 #else /* AFS_DEMAND_ATTACH_FS */
4353 VTakeOffline_r(Volume * vp)
4355 opr_Assert(vp->nUsers > 0);
4356 opr_Assert(programType == fileServer);
4358 vp->goingOffline = 1;
4359 V_needsSalvaged(vp) = 1;
4361 #endif /* AFS_DEMAND_ATTACH_FS */
4364 VTakeOffline(Volume * vp)
4372 * force a volume offline.
4374 * @param[in] vp volume object pointer
4375 * @param[in] flags flags (see note below)
4377 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4378 * used when VUpdateVolume_r needs to call VForceOffline_r
4379 * (which in turn would normally call VUpdateVolume_r)
4381 * @see VUpdateVolume_r
4383 * @pre VOL_LOCK must be held.
4384 * for DAFS, caller must hold ref.
4386 * @note for DAFS, it _is safe_ to call this function from an
4389 * @post needsSalvaged flag is set.
4390 * for DAFS, salvage is requested.
4391 * no further references to the volume through the volume
4392 * package will be honored.
4393 * all file descriptor and vnode caches are invalidated.
4395 * @warning this is a heavy-handed interface. it results in
4396 * a volume going offline regardless of the current
4397 * reference count state.
4399 * @internal volume package internal use only
4402 VForceOffline_r(Volume * vp, int flags)
4406 #ifdef AFS_DEMAND_ATTACH_FS
4407 VChangeState_r(vp, VOL_STATE_ERROR);
4412 strcpy(V_offlineMessage(vp),
4413 "Forced offline due to internal error: volume needs to be salvaged");
4414 Log("Volume %" AFS_VOLID_FMT " forced offline: it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4417 vp->goingOffline = 0;
4418 V_needsSalvaged(vp) = 1;
4419 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4420 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4423 #ifdef AFS_DEMAND_ATTACH_FS
4424 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4425 #endif /* AFS_DEMAND_ATTACH_FS */
4427 #ifdef AFS_PTHREAD_ENV
4428 opr_cv_broadcast(&vol_put_volume_cond);
4429 #else /* AFS_PTHREAD_ENV */
4430 LWP_NoYieldSignal(VPutVolume);
4431 #endif /* AFS_PTHREAD_ENV */
4433 VReleaseVolumeHandles_r(vp);
4437 * force a volume offline.
4439 * @param[in] vp volume object pointer
4441 * @see VForceOffline_r
4444 VForceOffline(Volume * vp)
4447 VForceOffline_r(vp, 0);
4452 * Iterate over the RX calls associated with a volume, and interrupt them.
4454 * @param[in] vp The volume whose RX calls we want to scan
4456 * @pre VOL_LOCK held
4459 VScanCalls_r(struct Volume *vp)
4461 struct VCallByVol *cbv, *ncbv;
4463 #ifdef AFS_DEMAND_ATTACH_FS
4464 VolState state_save;
4467 if (queue_IsEmpty(&vp->rx_call_list))
4468 return; /* no calls to interrupt */
4469 if (!vol_opts.interrupt_rxcall)
4470 return; /* we have no function with which to interrupt calls */
4471 err = VIsGoingOffline_r(vp);
4473 return; /* we're not going offline anymore */
4475 #ifdef AFS_DEMAND_ATTACH_FS
4476 VWaitExclusiveState_r(vp);
4477 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4479 #endif /* AFS_DEMAND_ATTACH_FS */
4481 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4482 if (GetLogLevel() != 0) {
4483 struct rx_peer *peer;
4485 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4487 Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4488 "from it; kicking client off with error %ld\n",
4489 afs_printable_VolumeId_lu(vp->hashid),
4490 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4491 (unsigned) ntohs(rx_PortOf(peer)),
4494 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4497 #ifdef AFS_DEMAND_ATTACH_FS
4499 VChangeState_r(vp, state_save);
4500 #endif /* AFS_DEMAND_ATTACH_FS */
4503 #ifdef AFS_DEMAND_ATTACH_FS
4505 * Wait for a vp to go offline.
4507 * @param[out] ec 1 if a salvage on the volume has been requested and
4508 * salvok == 0, 0 otherwise
4509 * @param[in] vp The volume to wait for
4510 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4511 * has been requested to salvage. Otherwise we keep waiting
4512 * until the volume has gone offline.
4514 * @pre VOL_LOCK held
4515 * @pre caller holds a lightweight ref on vp
4520 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4522 struct timespec timeout_ts;
4523 const struct timespec *ts;
4526 ts = VOfflineTimeout(&timeout_ts);
4530 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4531 if (!salvok && vp->salvage.requested) {
4535 VTimedWaitStateChange_r(vp, ts, &timedout);
4538 /* we didn't time out, so the volume must be offline, so we're done */
4542 /* If we got here, we timed out waiting for the volume to go offline.
4543 * Kick off the accessing RX calls and wait again */
4547 while (!VIsOfflineState(V_attachState(vp))) {
4548 if (!salvok && vp->salvage.requested) {
4553 VWaitStateChange_r(vp);
4557 #else /* AFS_DEMAND_ATTACH_FS */
4560 * Wait for a volume to go offline.
4562 * @pre VOL_LOCK held
4564 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4567 VWaitForOffline_r(Error *ec, VolumeId volid)
4570 const struct timespec *ts;
4571 #ifdef AFS_PTHREAD_ENV
4572 struct timespec timeout_ts;
4575 ts = VOfflineTimeout(&timeout_ts);
4577 vp = GetVolume(ec, NULL, volid, NULL, ts);
4579 /* error occurred so bad that we can't even get a vp; we have no
4580 * information on the vol so we don't know whether to wait, so just
4584 if (!VIsGoingOffline_r(vp)) {
4585 /* volume is no longer going offline, so we're done */
4590 /* If we got here, we timed out waiting for the volume to go offline.
4591 * Kick off the accessing RX calls and wait again */
4597 vp = VGetVolume_r(ec, volid);
4599 /* In case it was reattached... */
4603 #endif /* !AFS_DEMAND_ATTACH_FS */
4605 /* The opposite of VAttachVolume. The volume header is written to disk, with
4606 the inUse bit turned off. A copy of the header is maintained in memory,
4607 however (which is why this is VOffline, not VDetach).
4610 VOffline_r(Volume * vp, char *message)
4613 #ifndef AFS_DEMAND_ATTACH_FS
4614 VolumeId vid = V_id(vp);
4617 opr_Assert(programType != volumeUtility && programType != volumeServer);
4622 if (V_offlineMessage(vp)[0] == '\0')
4623 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4624 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4626 vp->goingOffline = 1;
4627 #ifdef AFS_DEMAND_ATTACH_FS
4628 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4629 VCreateReservation_r(vp);
4631 VWaitForOfflineByVp_r(&error, vp, 1);
4632 VCancelReservation_r(vp);
4633 #else /* AFS_DEMAND_ATTACH_FS */
4635 VWaitForOffline_r(&error, vid);
4636 #endif /* AFS_DEMAND_ATTACH_FS */
4639 #ifdef AFS_DEMAND_ATTACH_FS
4641 * Take a volume offline in order to perform a volume operation.
4643 * @param[inout] ec address in which to store error code
4644 * @param[in] vp volume object pointer
4645 * @param[in] message volume offline status message
4648 * - VOL_LOCK is held
4649 * - caller MUST hold a heavyweight ref on vp
4652 * - volume is taken offline
4653 * - if possible, volume operation is promoted to running state
4654 * - on failure, *ec is set to nonzero
4656 * @note Although this function does not return any value, it may
4657 * still fail to promote our pending volume operation to
4658 * a running state. Any caller MUST check the value of *ec,
4659 * and MUST NOT blindly assume success.
4661 * @warning if the caller does not hold a lightweight ref on vp,
4662 * then it MUST NOT reference vp after this function
4663 * returns to the caller.
4665 * @internal volume package internal use only
4668 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4671 opr_Assert(vp->pending_vol_op);
4677 if (V_offlineMessage(vp)[0] == '\0')
4678 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4679 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4681 vp->goingOffline = 1;
4682 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4683 VCreateReservation_r(vp);
4686 if (vp->pending_vol_op->com.programType != salvageServer) {
4687 /* do not give corrupted volumes to the volserver */
4692 VWaitForOfflineByVp_r(ec, vp, salvok);
4694 VCancelReservation_r(vp);
4696 #endif /* AFS_DEMAND_ATTACH_FS */
4699 VOffline(Volume * vp, char *message)
4702 VOffline_r(vp, message);
4706 /* This gets used for the most part by utility routines that don't want
4707 * to keep all the volume headers around. Generally, the file server won't
4708 * call this routine, because then the offline message in the volume header
4709 * (or other information) won't be available to clients. For NAMEI, also
4710 * close the file handles. However, the fileserver does call this during
4711 * an attach following a volume operation.
4714 VDetachVolume_r(Error * ec, Volume * vp)
4716 #ifdef FSSYNC_BUILD_CLIENT
4718 struct DiskPartition64 *tpartp;
4719 int notifyServer = 0;
4720 int useDone = FSYNC_VOL_ON;
4722 if (VCanUseFSSYNC()) {
4723 notifyServer = vp->needsPutBack;
4724 if (V_destroyMe(vp) == DESTROY_ME)
4725 useDone = FSYNC_VOL_LEAVE_OFF;
4726 # ifdef AFS_DEMAND_ATTACH_FS
4727 else if (!V_blessed(vp) || !V_inService(vp))
4728 useDone = FSYNC_VOL_LEAVE_OFF;
4731 # ifdef AFS_DEMAND_ATTACH_FS
4732 if (V_needsSalvaged(vp)) {
4734 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4737 tpartp = vp->partition;
4739 #endif /* FSSYNC_BUILD_CLIENT */
4741 *ec = 0; /* always "succeeds" */
4742 DeleteVolumeFromHashTable(vp);
4743 vp->shuttingDown = 1;
4744 #ifdef AFS_DEMAND_ATTACH_FS
4745 DeleteVolumeFromVByPList_r(vp);
4747 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4749 if (programType != fileServer)
4751 #endif /* AFS_DEMAND_ATTACH_FS */
4753 /* Will be detached sometime in the future--this is OK since volume is offline */
4755 /* XXX the following code should really be moved to VCheckDetach() since the volume
4756 * is not technically detached until the refcounts reach zero
4758 #ifdef FSSYNC_BUILD_CLIENT
4759 if (VCanUseFSSYNC() && notifyServer) {
4760 if (notifyServer == VOL_PUTBACK_DELETE) {
4761 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4762 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4763 * to signify a deleted volume. */
4764 useDone = FSYNC_VOL_DONE;
4767 * Note: The server is not notified in the case of a bogus volume
4768 * explicitly to make it possible to create a volume, do a partial
4769 * restore, then abort the operation without ever putting the volume
4770 * online. This is essential in the case of a volume move operation
4771 * between two partitions on the same server. In that case, there
4772 * would be two instances of the same volume, one of them bogus,
4773 * which the file server would attempt to put on line
4775 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4776 /* XXX this code path is only hit by volume utilities, thus
4777 * V_BreakVolumeCallbacks will always be NULL. if we really
4778 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4780 /* Dettaching it so break all callbacks on it */
4781 if (V_BreakVolumeCallbacks) {
4782 Log("volume %u detached; breaking all call backs\n", volume);
4783 (*V_BreakVolumeCallbacks) (volume);
4787 #endif /* FSSYNC_BUILD_CLIENT */
4791 VDetachVolume(Error * ec, Volume * vp)
4794 VDetachVolume_r(ec, vp);
4799 /***************************************************/
4800 /* Volume fd/inode handle closing routines */
4801 /***************************************************/
4803 /* For VDetachVolume, we close all cached file descriptors, but keep
4804 * the Inode handles in case we need to read from a busy volume.
4806 /* for demand attach, caller MUST hold ref count on vp */
4808 VCloseVolumeHandles_r(Volume * vp)
4810 #ifdef AFS_DEMAND_ATTACH_FS
4811 VolState state_save;
4813 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4818 DFlushVolume(vp->hashid);
4820 #ifdef AFS_DEMAND_ATTACH_FS
4824 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4825 VCloseVnodeFiles_r(vp);
4827 #ifdef AFS_DEMAND_ATTACH_FS
4831 /* Too time consuming and unnecessary for the volserver */
4832 if (programType == fileServer) {
4833 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4834 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4835 IH_CONDSYNC(vp->diskDataHandle);
4836 #ifdef AFS_NAMEI_ENV
4837 IH_CONDSYNC(vp->linkHandle);
4838 #endif /* AFS_NAMEI_ENV */
4841 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4842 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4843 IH_REALLYCLOSE(vp->diskDataHandle);
4844 IH_REALLYCLOSE(vp->linkHandle);
4846 #ifdef AFS_DEMAND_ATTACH_FS
4847 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4852 VChangeState_r(vp, state_save);
4856 /* For both VForceOffline and VOffline, we close all relevant handles.
4857 * For VOffline, if we re-attach the volume, the files may possible be
4858 * different than before.
4860 /* for demand attach, caller MUST hold a ref count on vp */
4862 VReleaseVolumeHandles_r(Volume * vp)
4864 #ifdef AFS_DEMAND_ATTACH_FS
4865 VolState state_save;
4867 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4872 DFlushVolume(vp->hashid);
4874 #ifdef AFS_DEMAND_ATTACH_FS
4878 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4880 #ifdef AFS_DEMAND_ATTACH_FS
4884 /* Too time consuming and unnecessary for the volserver */
4885 if (programType == fileServer) {
4886 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4887 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4888 IH_CONDSYNC(vp->diskDataHandle);
4889 #ifdef AFS_NAMEI_ENV
4890 IH_CONDSYNC(vp->linkHandle);
4891 #endif /* AFS_NAMEI_ENV */
4894 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4895 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4896 IH_RELEASE(vp->diskDataHandle);
4897 IH_RELEASE(vp->linkHandle);
4899 #ifdef AFS_DEMAND_ATTACH_FS
4900 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4905 VChangeState_r(vp, state_save);
4910 /***************************************************/
4911 /* Volume write and fsync routines */
4912 /***************************************************/
4915 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4917 #ifdef AFS_DEMAND_ATTACH_FS
4918 VolState state_save;
4920 if (flags & VOL_UPDATE_WAIT) {
4921 VCreateReservation_r(vp);
4922 VWaitExclusiveState_r(vp);
4927 if (programType == fileServer) {
4929 V_uniquifier(vp) = V_nextVnodeUnique(vp);
4932 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4933 if (V_uniquifier(vp) < V_nextVnodeUnique(vp)) {
4934 /* uniquifier rolled over; reset the counters */
4935 V_nextVnodeUnique(vp) = 2; /* 1 is reserved for the root vnode */
4937 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4942 #ifdef AFS_DEMAND_ATTACH_FS
4943 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4947 WriteVolumeHeader_r(ec, vp);
4949 #ifdef AFS_DEMAND_ATTACH_FS
4951 VChangeState_r(vp, state_save);
4952 if (flags & VOL_UPDATE_WAIT) {
4953 VCancelReservation_r(vp);
4958 Log("VUpdateVolume: error updating volume header, volume %" AFS_VOLID_FMT " (%s)\n",
4959 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
4960 /* try to update on-disk header,
4961 * while preventing infinite recursion */
4962 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4963 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4969 VUpdateVolume(Error * ec, Volume * vp)
4972 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4977 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4981 #ifdef AFS_DEMAND_ATTACH_FS
4982 VolState state_save;
4985 if (flags & VOL_SYNC_WAIT) {
4986 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4988 VUpdateVolume_r(ec, vp, 0);
4991 #ifdef AFS_DEMAND_ATTACH_FS
4992 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4995 fdP = IH_OPEN(V_diskDataHandle(vp));
4996 opr_Assert(fdP != NULL);
4997 code = FDH_SYNC(fdP);
4998 opr_Assert(code == 0);
5000 #ifdef AFS_DEMAND_ATTACH_FS
5002 VChangeState_r(vp, state_save);
5008 VSyncVolume(Error * ec, Volume * vp)
5011 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
5016 /***************************************************/
5017 /* Volume dealloaction routines */
5018 /***************************************************/
5020 #ifdef AFS_DEMAND_ATTACH_FS
5022 FreeVolume(Volume * vp)
5024 /* free the heap space, iff it's safe.
5025 * otherwise, pull it out of the hash table, so it
5026 * will get deallocated when all refs to it go away */
5027 if (!VCheckFree(vp)) {
5028 DeleteVolumeFromHashTable(vp);
5029 DeleteVolumeFromVByPList_r(vp);
5031 /* make sure we invalidate the header cache entry */
5032 FreeVolumeHeader(vp);
5035 #endif /* AFS_DEMAND_ATTACH_FS */
5038 ReallyFreeVolume(Volume * vp)
5043 #ifdef AFS_DEMAND_ATTACH_FS
5045 VChangeState_r(vp, VOL_STATE_FREED);
5046 if (vp->pending_vol_op)
5047 free(vp->pending_vol_op);
5048 #endif /* AFS_DEMAND_ATTACH_FS */
5049 for (i = 0; i < nVNODECLASSES; i++)
5050 if (vp->vnodeIndex[i].bitmap)
5051 free(vp->vnodeIndex[i].bitmap);
5052 FreeVolumeHeader(vp);
5053 #ifndef AFS_DEMAND_ATTACH_FS
5054 DeleteVolumeFromHashTable(vp);
5055 #endif /* AFS_DEMAND_ATTACH_FS */
5059 /* check to see if we should shutdown this volume
5060 * returns 1 if volume was freed, 0 otherwise */
5061 #ifdef AFS_DEMAND_ATTACH_FS
5063 VCheckDetach(Volume * vp)
5068 if (vp->nUsers || vp->nWaiters)
5071 if (vp->shuttingDown) {
5073 if ((programType != fileServer) &&
5074 (V_inUse(vp) == programType) &&
5075 ((V_checkoutMode(vp) == V_VOLUPD) ||
5076 (V_checkoutMode(vp) == V_SECRETLY) ||
5077 ((V_checkoutMode(vp) == V_CLONE) &&
5078 (VolumeWriteable(vp))))) {
5080 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5082 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " "
5083 "failed with errno %d\n", afs_printable_VolumeId_lu(vp->hashid), errno);
5086 VReleaseVolumeHandles_r(vp);
5088 ReallyFreeVolume(vp);
5089 if (programType == fileServer) {
5090 opr_cv_broadcast(&vol_put_volume_cond);
5095 #else /* AFS_DEMAND_ATTACH_FS */
5097 VCheckDetach(Volume * vp)
5105 if (vp->shuttingDown) {
5107 if ((programType != fileServer) &&
5108 (V_inUse(vp) == programType) &&
5109 ((V_checkoutMode(vp) == V_VOLUPD) ||
5110 (V_checkoutMode(vp) == V_SECRETLY) ||
5111 ((V_checkoutMode(vp) == V_CLONE) &&
5112 (VolumeWriteable(vp))))) {
5114 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5116 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " failed with errno %d\n",
5117 afs_printable_VolumeId_lu(vp->hashid), errno);
5120 VReleaseVolumeHandles_r(vp);
5121 ReallyFreeVolume(vp);
5122 if (programType == fileServer) {
5123 #if defined(AFS_PTHREAD_ENV)
5124 opr_cv_broadcast(&vol_put_volume_cond);
5125 #else /* AFS_PTHREAD_ENV */
5126 LWP_NoYieldSignal(VPutVolume);
5127 #endif /* AFS_PTHREAD_ENV */
5132 #endif /* AFS_DEMAND_ATTACH_FS */
5134 /* check to see if we should offline this volume
5135 * return 1 if volume went offline, 0 otherwise */
5136 #ifdef AFS_DEMAND_ATTACH_FS
5138 VCheckOffline(Volume * vp)
5142 if (vp->goingOffline && !vp->nUsers) {
5144 opr_Assert(programType == fileServer);
5145 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5146 (V_attachState(vp) != VOL_STATE_FREED) &&
5147 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5148 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5149 (V_attachState(vp) != VOL_STATE_DELETED));
5153 * VOL_STATE_GOING_OFFLINE
5154 * VOL_STATE_SHUTTING_DOWN
5155 * VIsErrorState(V_attachState(vp))
5156 * VIsExclusiveState(V_attachState(vp))
5159 VCreateReservation_r(vp);
5160 VChangeState_r(vp, VOL_STATE_OFFLINING);
5163 /* must clear the goingOffline flag before we drop the glock */
5164 vp->goingOffline = 0;
5169 /* perform async operations */
5170 VUpdateVolume_r(&error, vp, 0);
5171 VCloseVolumeHandles_r(vp);
5173 if (GetLogLevel() != 0) {
5174 if (V_offlineMessage(vp)[0]) {
5175 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5176 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5177 V_offlineMessage(vp));
5179 Log("VOffline: Volume %lu (%s) is now offline\n",
5180 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5184 /* invalidate the volume header cache entry */
5185 FreeVolumeHeader(vp);
5187 /* if nothing changed state to error or salvaging,
5188 * drop state to unattached */
5189 if (!VIsErrorState(V_attachState(vp))) {
5190 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5192 VCancelReservation_r(vp);
5193 /* no usage of vp is safe beyond this point */
5197 #else /* AFS_DEMAND_ATTACH_FS */
5199 VCheckOffline(Volume * vp)
5203 if (vp->goingOffline && !vp->nUsers) {
5205 opr_Assert(programType == fileServer);
5208 vp->goingOffline = 0;
5210 VUpdateVolume_r(&error, vp, 0);
5211 VCloseVolumeHandles_r(vp);
5212 if (GetLogLevel() != 0) {
5213 if (V_offlineMessage(vp)[0]) {
5214 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5215 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5216 V_offlineMessage(vp));
5218 Log("VOffline: Volume %lu (%s) is now offline\n",
5219 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5222 FreeVolumeHeader(vp);
5223 #ifdef AFS_PTHREAD_ENV
5224 opr_cv_broadcast(&vol_put_volume_cond);
5225 #else /* AFS_PTHREAD_ENV */
5226 LWP_NoYieldSignal(VPutVolume);
5227 #endif /* AFS_PTHREAD_ENV */
5231 #endif /* AFS_DEMAND_ATTACH_FS */
5233 /***************************************************/
5234 /* demand attach fs ref counting routines */
5235 /***************************************************/
5237 #ifdef AFS_DEMAND_ATTACH_FS
5238 /* the following two functions handle reference counting for
5239 * asynchronous operations on volume structs.
5241 * their purpose is to prevent a VDetachVolume or VShutdown
5242 * from free()ing the Volume struct during an async i/o op */
5244 /* register with the async volume op ref counter */
5245 /* VCreateReservation_r moved into inline code header because it
5246 * is now needed in vnode.c -- tkeiser 11/20/2007
5250 * decrement volume-package internal refcount.
5252 * @param vp volume object pointer
5254 * @internal volume package internal use only
5257 * @arg VOL_LOCK is held
5258 * @arg lightweight refcount held
5260 * @post volume waiters refcount is decremented; volume may
5261 * have been deallocated/shutdown/offlined/salvaged/
5262 * whatever during the process
5264 * @warning once you have tossed your last reference (you can acquire
5265 * lightweight refs recursively) it is NOT SAFE to reference
5266 * a volume object pointer ever again
5268 * @see VCreateReservation_r
5270 * @note DEMAND_ATTACH_FS only
5273 VCancelReservation_r(Volume * vp)
5275 opr_Verify(--vp->nWaiters >= 0);
5276 if (vp->nWaiters == 0) {
5278 if (!VCheckDetach(vp)) {
5285 /* check to see if we should free this volume now
5286 * return 1 if volume was freed, 0 otherwise */
5288 VCheckFree(Volume * vp)
5291 if ((vp->nUsers == 0) &&
5292 (vp->nWaiters == 0) &&
5293 !(V_attachFlags(vp) & (VOL_IN_HASH |
5297 ReallyFreeVolume(vp);
5302 #endif /* AFS_DEMAND_ATTACH_FS */
5305 /***************************************************/
5306 /* online volume operations routines */
5307 /***************************************************/
5309 #ifdef AFS_DEMAND_ATTACH_FS
5311 * register a volume operation on a given volume.
5313 * @param[in] vp volume object
5314 * @param[in] vopinfo volume operation info object
5316 * @pre VOL_LOCK is held
5318 * @post volume operation info object attached to volume object.
5319 * volume operation statistics updated.
5321 * @note by "attached" we mean a copy of the passed in object is made
5323 * @internal volume package internal use only
5326 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5328 FSSYNC_VolOp_info * info;
5330 /* attach a vol op info node to the volume struct */
5331 info = malloc(sizeof(FSSYNC_VolOp_info));
5332 opr_Assert(info != NULL);
5333 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5334 vp->pending_vol_op = info;
5337 vp->stats.last_vol_op = FT_ApproxTime();
5338 vp->stats.vol_ops++;
5339 IncUInt64(&VStats.vol_ops);
5345 * deregister the volume operation attached to this volume.
5347 * @param[in] vp volume object pointer
5349 * @pre VOL_LOCK is held
5351 * @post the volume operation info object is detached from the volume object
5353 * @internal volume package internal use only
5356 VDeregisterVolOp_r(Volume * vp)
5358 if (vp->pending_vol_op) {
5359 free(vp->pending_vol_op);
5360 vp->pending_vol_op = NULL;
5364 #endif /* AFS_DEMAND_ATTACH_FS */
5367 * determine whether it is safe to leave a volume online during
5368 * the volume operation described by the vopinfo object.
5370 * @param[in] vp volume object
5371 * @param[in] vopinfo volume operation info object
5373 * @return whether it is safe to leave volume online
5374 * @retval 0 it is NOT SAFE to leave the volume online
5375 * @retval 1 it is safe to leave the volume online during the operation
5378 * @arg VOL_LOCK is held
5379 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5380 * this condition is met)
5382 * @internal volume package internal use only
5385 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5387 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5388 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5389 (vopinfo->com.reason == V_READONLY ||
5390 (!VolumeWriteable(vp) &&
5391 (vopinfo->com.reason == V_CLONE ||
5392 vopinfo->com.reason == V_DUMP)))));
5396 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5399 * @param[in] vp volume object
5400 * @param[in] vopinfo volume operation info object
5402 * @return whether it is safe to leave volume online
5403 * @retval 0 it is NOT SAFE to leave the volume online
5404 * @retval 1 it is safe to leave the volume online during the operation
5405 * @retval -1 unsure; volume header is required in order to know whether or
5406 * not is is safe to leave the volume online
5408 * @pre VOL_LOCK is held
5410 * @internal volume package internal use only
5413 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5415 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5416 * assume that we don't know VolumeWriteable; return -1 if the answer
5417 * depends on VolumeWriteable */
5419 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5422 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5423 vopinfo->com.reason == V_READONLY) {
5427 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5428 (vopinfo->com.reason == V_CLONE ||
5429 vopinfo->com.reason == V_DUMP)) {
5431 /* must know VolumeWriteable */
5438 * determine whether VBUSY should be set during this volume operation.
5440 * @param[in] vp volume object
5441 * @param[in] vopinfo volume operation info object
5443 * @return whether VBUSY should be set
5444 * @retval 0 VBUSY does NOT need to be set
5445 * @retval 1 VBUSY SHOULD be set
5447 * @pre VOL_LOCK is held
5449 * @internal volume package internal use only
5452 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5454 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5455 vopinfo->com.reason == FSYNC_SALVAGE) ||
5456 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5457 (vopinfo->com.reason == V_CLONE ||
5458 vopinfo->com.reason == V_DUMP)));
5462 /***************************************************/
5463 /* online salvager routines */
5464 /***************************************************/
5465 #if defined(AFS_DEMAND_ATTACH_FS)
5468 * offline a volume to let it be salvaged.
5470 * @param[in] vp Volume to offline
5472 * @return whether we offlined the volume successfully
5473 * @retval 0 volume was not offlined
5474 * @retval 1 volume is now offline
5476 * @note This is similar to VCheckOffline, but slightly different. We do not
5477 * deal with vp->goingOffline, and we try to avoid touching the volume
5478 * header except just to set needsSalvaged
5480 * @pre VOL_LOCK held
5481 * @pre vp->nUsers == 0
5482 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5485 VOfflineForSalvage_r(struct Volume *vp)
5489 VCreateReservation_r(vp);
5490 VWaitExclusiveState_r(vp);
5492 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5493 /* Someone's using the volume, or someone got to scheduling the salvage
5494 * before us. I don't think either of these should be possible, as we
5495 * should gain no new heavyweight references while we're trying to
5496 * salvage, but just to be sure... */
5497 VCancelReservation_r(vp);
5501 VChangeState_r(vp, VOL_STATE_OFFLINING);
5505 V_needsSalvaged(vp) = 1;
5506 /* ignore error; updating needsSalvaged is just best effort */
5507 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5509 VCloseVolumeHandles_r(vp);
5511 FreeVolumeHeader(vp);
5513 /* volume has been effectively offlined; we can mark it in the SALVAGING
5514 * state now, which lets FSSYNC give it away */
5515 VChangeState_r(vp, VOL_STATE_SALVAGING);
5517 VCancelReservation_r(vp);
5523 * check whether a salvage needs to be performed on this volume.
5525 * @param[in] vp pointer to volume object
5527 * @return status code
5528 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5529 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5530 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5531 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5532 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5534 * @pre VOL_LOCK is held
5536 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5537 * then a salvage will be requested
5539 * @note this is one of the event handlers called by VCancelReservation_r
5541 * @note the caller must check if the volume needs to be freed after calling
5542 * this; the volume may not have any references or be on any lists after
5543 * we return, and we do not free it
5545 * @see VCancelReservation_r
5547 * @internal volume package internal use only.
5550 VCheckSalvage(Volume * vp)
5552 int ret = VCHECK_SALVAGE_OK;
5554 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5555 if (!vp->salvage.requested) {
5556 return VCHECK_SALVAGE_OK;
5559 return VCHECK_SALVAGE_ASYNC;
5562 /* prevent recursion; some of the code below creates and removes
5563 * lightweight refs, which can call VCheckSalvage */
5564 if (vp->salvage.scheduling) {
5565 return VCHECK_SALVAGE_ASYNC;
5567 vp->salvage.scheduling = 1;
5569 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5570 if (!VOfflineForSalvage_r(vp)) {
5571 vp->salvage.scheduling = 0;
5572 return VCHECK_SALVAGE_FAIL;
5576 if (vp->salvage.requested) {
5577 ret = VScheduleSalvage_r(vp);
5579 vp->salvage.scheduling = 0;
5580 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5585 * request volume salvage.
5587 * @param[out] ec computed client error code
5588 * @param[in] vp volume object pointer
5589 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5590 * @param[in] flags see flags note below
5593 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5594 * not been fully attached
5596 * @pre VOL_LOCK is held.
5598 * @post volume state is changed.
5599 * for fileserver, salvage will be requested once refcount reaches zero.
5601 * @return operation status code
5602 * @retval 0 volume salvage will occur
5603 * @retval 1 volume salvage could not be scheduled
5607 * @note in the fileserver, this call does not synchronously schedule a volume
5608 * salvage. rather, it sets volume state so that when volume refcounts
5609 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5610 * nUsers and nWaiters must be zero.
5612 * @internal volume package internal use only.
5615 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5619 * for DAFS volume utilities that are not supposed to schedule salvages,
5620 * just transition to error state instead
5622 if (!VCanScheduleSalvage()) {
5623 VChangeState_r(vp, VOL_STATE_ERROR);
5628 if (programType != fileServer && !VCanUseFSSYNC()) {
5629 VChangeState_r(vp, VOL_STATE_ERROR);
5634 if (!vp->salvage.requested) {
5635 vp->salvage.requested = 1;
5636 vp->salvage.reason = reason;
5637 vp->stats.last_salvage = FT_ApproxTime();
5639 /* Note that it is not possible for us to reach this point if a
5640 * salvage is already running on this volume (even if the fileserver
5641 * was restarted during the salvage). If a salvage were running, the
5642 * salvager would have write-locked the volume header file, so when
5643 * we tried to lock the volume header, the lock would have failed,
5644 * and we would have failed during attachment prior to calling
5645 * VRequestSalvage. So we know that we can schedule salvages without
5646 * fear of a salvage already running for this volume. */
5648 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5650 /* if we don't need to offline the volume, we can go directly
5651 * to SALVAGING. SALVAGING says the volume is offline and is
5652 * either salvaging or ready to be handed to the salvager.
5653 * SALVAGE_REQ says that we want to salvage the volume, but we
5654 * are waiting for it to go offline first. */
5655 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5656 VChangeState_r(vp, VOL_STATE_SALVAGING);
5658 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5659 if (vp->nUsers == 0) {
5660 /* normally VOfflineForSalvage_r would be called from
5661 * PutVolume et al when nUsers reaches 0, but if
5662 * it's already 0, just do it ourselves, since PutVolume
5663 * isn't going to get called */
5664 VOfflineForSalvage_r(vp);
5667 /* If we are non-fileserver, we're telling the fileserver to
5668 * salvage the vol, so we don't need to give it back separately. */
5669 vp->needsPutBack = 0;
5673 Log("VRequestSalvage: volume %" AFS_VOLID_FMT " online salvaged too many times; forced offline.\n", afs_printable_VolumeId_lu(vp->hashid));
5675 /* make sure neither VScheduleSalvage_r nor
5676 * VUpdateSalvagePriority_r try to schedule another salvage */
5677 vp->salvage.requested = vp->salvage.scheduled = 0;
5679 VChangeState_r(vp, VOL_STATE_ERROR);
5683 if ((flags & VOL_SALVAGE_NO_OFFLINE)) {
5684 /* Here, we free the header for the volume, but make sure to only
5685 * do this if VOL_SALVAGE_NO_OFFLINE is specified. The reason for
5686 * this requires a bit of explanation.
5688 * Normally, the volume header will be freed when the volume goes
5689 * goes offline. However, if VOL_SALVAGE_NO_OFFLINE has been
5690 * specified, the volume was in the process of being attached when
5691 * we discovered that it needed salvaging. Thus, the volume will
5692 * never go offline, since it never went fully online in the first
5693 * place. Specifically, we do not call VOfflineForSalvage_r above,
5694 * and we never get rid of the volume via VPutVolume_r; the volume
5695 * has not been initialized enough for those to work.
5697 * So instead, explicitly free the volume header here. If we do not
5698 * do this, we are wasting a header that some other volume could be
5699 * using, since the header remains attached to the volume. Also if
5700 * we do not free the header here, we end up with a volume where
5701 * nUsers == 0, but the volume has a header that is not on the
5702 * header LRU. Some code expects that all nUsers == 0 volumes have
5703 * their header on the header LRU (or have no header).
5705 * Also note that we must not free the volume header here if
5706 * VOL_SALVAGE_NO_OFFLINE is not set. Since, if
5707 * VOL_SALVAGE_NO_OFFLINE is not set, someone else may have a
5708 * reference to this volume, and they assume they can use the
5709 * volume's header. If we free the volume out from under them, they
5710 * can easily segfault.
5712 FreeVolumeHeader(vp);
5719 * update salvageserver scheduling priority for a volume.
5721 * @param[in] vp pointer to volume object
5723 * @return operation status
5725 * @retval 1 request denied, or SALVSYNC communications failure
5727 * @pre VOL_LOCK is held.
5729 * @post in-core salvage priority counter is incremented. if at least
5730 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5731 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5732 * to update its priority queue. if no salvage is scheduled,
5733 * this function is a no-op.
5735 * @note DAFS fileserver only
5737 * @note this should be called whenever a VGetVolume fails due to a
5738 * pending salvage request
5740 * @todo should set exclusive state and drop glock around salvsync call
5742 * @internal volume package internal use only.
5745 VUpdateSalvagePriority_r(Volume * vp)
5749 #ifdef SALVSYNC_BUILD_CLIENT
5754 now = FT_ApproxTime();
5756 /* update the salvageserver priority queue occasionally so that
5757 * frequently requested volumes get moved to the head of the queue
5759 if ((vp->salvage.scheduled) &&
5760 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5761 code = SALVSYNC_SalvageVolume(vp->hashid,
5762 VPartitionPath(vp->partition),
5767 vp->stats.last_salvage_req = now;
5768 if (code != SYNC_OK) {
5772 #endif /* SALVSYNC_BUILD_CLIENT */
5777 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5779 /* A couple of little helper functions. These return true if we tried to
5780 * use this mechanism to schedule a salvage, false if we haven't tried.
5781 * If we did try a salvage then the results are contained in code.
5785 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5786 #ifdef SALVSYNC_BUILD_CLIENT
5787 if (VCanUseSALVSYNC()) {
5788 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over SALVSYNC\n",
5789 afs_printable_VolumeId_lu(vp->hashid), partName);
5791 /* can't use V_id() since there's no guarantee
5792 * we have the disk data header at this point */
5793 *code = SALVSYNC_SalvageVolume(vp->hashid,
5806 try_FSSYNC(Volume *vp, char *partName, int *code) {
5807 #ifdef FSSYNC_BUILD_CLIENT
5808 if (VCanUseFSSYNC()) {
5809 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over FSSYNC\n",
5810 afs_printable_VolumeId_lu(vp->hashid), partName);
5813 * If we aren't the fileserver, tell the fileserver the volume
5814 * needs to be salvaged. We could directly tell the
5815 * salvageserver, but the fileserver keeps track of some stats
5816 * related to salvages, and handles some other salvage-related
5817 * complications for us.
5819 *code = FSYNC_VolOp(vp->hashid, partName,
5820 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5823 #endif /* FSSYNC_BUILD_CLIENT */
5828 * schedule a salvage with the salvage server or fileserver.
5830 * @param[in] vp pointer to volume object
5832 * @return operation status
5833 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5834 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5835 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5836 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5837 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5840 * @arg VOL_LOCK is held.
5841 * @arg nUsers and nWaiters should be zero.
5843 * @post salvageserver or fileserver is sent a salvage request
5845 * @note If we are the fileserver, the request will be sent to the salvage
5846 * server over SALVSYNC. If we are not the fileserver, the request will be
5847 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5849 * @note the caller must check if the volume needs to be freed after calling
5850 * this; the volume may not have any references or be on any lists after
5851 * we return, and we do not free it
5855 * @internal volume package internal use only.
5858 VScheduleSalvage_r(Volume * vp)
5860 int ret = VCHECK_SALVAGE_SCHEDULED;
5862 VolState state_save;
5863 VThreadOptions_t * thread_opts;
5866 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5868 if (vp->nWaiters || vp->nUsers) {
5869 return VCHECK_SALVAGE_ASYNC;
5872 /* prevent endless salvage,attach,salvage,attach,... loops */
5873 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5874 return VCHECK_SALVAGE_FAIL;
5878 * don't perform salvsync ops on certain threads
5880 thread_opts = pthread_getspecific(VThread_key);
5881 if (thread_opts == NULL) {
5882 thread_opts = &VThread_defaults;
5884 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5885 return VCHECK_SALVAGE_ASYNC;
5888 if (vp->salvage.scheduled) {
5889 return VCHECK_SALVAGE_SCHEDULED;
5892 VCreateReservation_r(vp);
5893 VWaitExclusiveState_r(vp);
5896 * XXX the scheduling process should really be done asynchronously
5897 * to avoid fssync deadlocks
5899 if (vp->salvage.scheduled) {
5900 ret = VCHECK_SALVAGE_SCHEDULED;
5902 /* if we haven't previously scheduled a salvage, do so now
5904 * set the volume to an exclusive state and drop the lock
5905 * around the SALVSYNC call
5907 strlcpy(partName, vp->partition->name, sizeof(partName));
5908 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5911 opr_Verify(try_SALVSYNC(vp, partName, &code)
5912 || try_FSSYNC(vp, partName, &code));
5915 VChangeState_r(vp, state_save);
5917 if (code == SYNC_OK) {
5918 ret = VCHECK_SALVAGE_SCHEDULED;
5919 vp->salvage.scheduled = 1;
5920 vp->stats.last_salvage_req = FT_ApproxTime();
5921 if (VCanUseSALVSYNC()) {
5922 /* don't record these stats for non-fileservers; let the
5923 * fileserver take care of these */
5924 vp->stats.salvages++;
5925 IncUInt64(&VStats.salvages);
5929 case SYNC_BAD_COMMAND:
5930 case SYNC_COM_ERROR:
5931 ret = VCHECK_SALVAGE_FAIL;
5934 ret = VCHECK_SALVAGE_DENIED;
5935 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5936 "denied\n", afs_printable_VolumeId_lu(vp->hashid));
5939 ret = VCHECK_SALVAGE_FAIL;
5940 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5941 "failed\n", afs_printable_VolumeId_lu(vp->hashid));
5944 ret = VCHECK_SALVAGE_FAIL;
5945 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5946 "received unknown protocol error %d\n",
5947 afs_printable_VolumeId_lu(vp->hashid), code);
5951 if (VCanUseFSSYNC()) {
5952 VChangeState_r(vp, VOL_STATE_ERROR);
5957 /* NB: this is cancelling the reservation we obtained above, but we do
5958 * not call VCancelReservation_r, since that may trigger the vp dtor,
5959 * possibly free'ing the vp. We need to keep the vp around after
5960 * this, as the caller may reference vp without any refs. Instead, it
5961 * is the duty of the caller to inspect 'vp' after we return to see if
5962 * needs to be freed. */
5963 opr_Verify(--vp->nWaiters >= 0);
5966 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5968 #ifdef SALVSYNC_BUILD_CLIENT
5971 * connect to the salvageserver SYNC service.
5973 * @return operation status
5977 * @post connection to salvageserver SYNC service established
5979 * @see VConnectSALV_r
5980 * @see VDisconnectSALV
5981 * @see VReconnectSALV
5988 retVal = VConnectSALV_r();
5994 * connect to the salvageserver SYNC service.
5996 * @return operation status
6000 * @pre VOL_LOCK is held.
6002 * @post connection to salvageserver SYNC service established
6005 * @see VDisconnectSALV_r
6006 * @see VReconnectSALV_r
6007 * @see SALVSYNC_clientInit
6009 * @internal volume package internal use only.
6012 VConnectSALV_r(void)
6014 return SALVSYNC_clientInit();
6018 * disconnect from the salvageserver SYNC service.
6020 * @return operation status
6023 * @pre client should have a live connection to the salvageserver
6025 * @post connection to salvageserver SYNC service destroyed
6027 * @see VDisconnectSALV_r
6029 * @see VReconnectSALV
6032 VDisconnectSALV(void)
6035 VDisconnectSALV_r();
6041 * disconnect from the salvageserver SYNC service.
6043 * @return operation status
6047 * @arg VOL_LOCK is held.
6048 * @arg client should have a live connection to the salvageserver.
6050 * @post connection to salvageserver SYNC service destroyed
6052 * @see VDisconnectSALV
6053 * @see VConnectSALV_r
6054 * @see VReconnectSALV_r
6055 * @see SALVSYNC_clientFinis
6057 * @internal volume package internal use only.
6060 VDisconnectSALV_r(void)
6062 return SALVSYNC_clientFinis();
6066 * disconnect and then re-connect to the salvageserver SYNC service.
6068 * @return operation status
6072 * @pre client should have a live connection to the salvageserver
6074 * @post old connection is dropped, and a new one is established
6077 * @see VDisconnectSALV
6078 * @see VReconnectSALV_r
6081 VReconnectSALV(void)
6085 retVal = VReconnectSALV_r();
6091 * disconnect and then re-connect to the salvageserver SYNC service.
6093 * @return operation status
6098 * @arg VOL_LOCK is held.
6099 * @arg client should have a live connection to the salvageserver.
6101 * @post old connection is dropped, and a new one is established
6103 * @see VConnectSALV_r
6104 * @see VDisconnectSALV
6105 * @see VReconnectSALV
6106 * @see SALVSYNC_clientReconnect
6108 * @internal volume package internal use only.
6111 VReconnectSALV_r(void)
6113 return SALVSYNC_clientReconnect();
6115 #endif /* SALVSYNC_BUILD_CLIENT */
6116 #endif /* AFS_DEMAND_ATTACH_FS */
6119 /***************************************************/
6120 /* FSSYNC routines */
6121 /***************************************************/
6123 /* This must be called by any volume utility which needs to run while the
6124 file server is also running. This is separated from VInitVolumePackage2 so
6125 that a utility can fork--and each of the children can independently
6126 initialize communication with the file server */
6127 #ifdef FSSYNC_BUILD_CLIENT
6129 * connect to the fileserver SYNC service.
6131 * @return operation status
6136 * @arg VInit must equal 2.
6137 * @arg Program Type must not be fileserver or salvager.
6139 * @post connection to fileserver SYNC service established
6142 * @see VDisconnectFS
6143 * @see VChildProcReconnectFS
6150 retVal = VConnectFS_r();
6156 * connect to the fileserver SYNC service.
6158 * @return operation status
6163 * @arg VInit must equal 2.
6164 * @arg Program Type must not be fileserver or salvager.
6165 * @arg VOL_LOCK is held.
6167 * @post connection to fileserver SYNC service established
6170 * @see VDisconnectFS_r
6171 * @see VChildProcReconnectFS_r
6173 * @internal volume package internal use only.
6179 opr_Assert((VInit == 2) &&
6180 (programType != fileServer) &&
6181 (programType != salvager));
6182 rc = FSYNC_clientInit();
6190 * disconnect from the fileserver SYNC service.
6193 * @arg client should have a live connection to the fileserver.
6194 * @arg VOL_LOCK is held.
6195 * @arg Program Type must not be fileserver or salvager.
6197 * @post connection to fileserver SYNC service destroyed
6199 * @see VDisconnectFS
6201 * @see VChildProcReconnectFS_r
6203 * @internal volume package internal use only.
6206 VDisconnectFS_r(void)
6208 opr_Assert((programType != fileServer) &&
6209 (programType != salvager));
6210 FSYNC_clientFinis();
6215 * disconnect from the fileserver SYNC service.
6218 * @arg client should have a live connection to the fileserver.
6219 * @arg Program Type must not be fileserver or salvager.
6221 * @post connection to fileserver SYNC service destroyed
6223 * @see VDisconnectFS_r
6225 * @see VChildProcReconnectFS
6236 * connect to the fileserver SYNC service from a child process following a fork.
6238 * @return operation status
6243 * @arg VOL_LOCK is held.
6244 * @arg current FSYNC handle is shared with a parent process
6246 * @post current FSYNC handle is discarded and a new connection to the
6247 * fileserver SYNC service is established
6249 * @see VChildProcReconnectFS
6251 * @see VDisconnectFS_r
6253 * @internal volume package internal use only.
6256 VChildProcReconnectFS_r(void)
6258 return FSYNC_clientChildProcReconnect();
6262 * connect to the fileserver SYNC service from a child process following a fork.
6264 * @return operation status
6268 * @pre current FSYNC handle is shared with a parent process
6270 * @post current FSYNC handle is discarded and a new connection to the
6271 * fileserver SYNC service is established
6273 * @see VChildProcReconnectFS_r
6275 * @see VDisconnectFS
6278 VChildProcReconnectFS(void)
6282 ret = VChildProcReconnectFS_r();
6286 #endif /* FSSYNC_BUILD_CLIENT */
6289 /***************************************************/
6290 /* volume bitmap routines */
6291 /***************************************************/
6294 * Grow the bitmap by the defined increment
6297 VGrowBitmap(struct vnodeIndex *index)
6301 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6302 osi_Assert(bp != NULL);
6304 bp += index->bitmapSize;
6305 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6306 index->bitmapOffset = index->bitmapSize;
6307 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6313 * allocate a vnode bitmap number for the vnode
6315 * @param[out] ec error code
6316 * @param[in] vp volume object pointer
6317 * @param[in] index vnode index number for the vnode
6318 * @param[in] flags flag values described in note
6320 * @note for DAFS, flags parameter controls locking behavior.
6321 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6322 * will create a reservation and block on any other exclusive
6323 * operations. Otherwise, this function assumes the caller
6324 * already has exclusive access to vp, and we just change the
6327 * @pre VOL_LOCK held
6329 * @return bit number allocated
6335 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6336 struct vnodeIndex *index, int flags)
6340 #ifdef AFS_DEMAND_ATTACH_FS
6341 VolState state_save;
6342 #endif /* AFS_DEMAND_ATTACH_FS */
6346 /* This test is probably redundant */
6347 if (!VolumeWriteable(vp)) {
6348 *ec = (bit32) VREADONLY;
6352 #ifdef AFS_DEMAND_ATTACH_FS
6353 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6354 VCreateReservation_r(vp);
6355 VWaitExclusiveState_r(vp);
6357 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6358 #endif /* AFS_DEMAND_ATTACH_FS */
6361 if ((programType == fileServer) && !index->bitmap) {
6363 #ifndef AFS_DEMAND_ATTACH_FS
6364 /* demand attach fs uses the volume state to avoid races.
6365 * specialStatus field is not used at all */
6367 if (vp->specialStatus == VBUSY) {
6368 if (vp->goingOffline) { /* vos dump waiting for the volume to
6369 * go offline. We probably come here
6370 * from AddNewReadableResidency */
6373 while (vp->specialStatus == VBUSY) {
6374 #ifdef AFS_PTHREAD_ENV
6378 #else /* !AFS_PTHREAD_ENV */
6380 #endif /* !AFS_PTHREAD_ENV */
6384 #endif /* !AFS_DEMAND_ATTACH_FS */
6386 if (!index->bitmap) {
6387 #ifndef AFS_DEMAND_ATTACH_FS
6388 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6389 #endif /* AFS_DEMAND_ATTACH_FS */
6390 for (i = 0; i < nVNODECLASSES; i++) {
6391 VGetBitmap_r(ec, vp, i);
6393 #ifdef AFS_DEMAND_ATTACH_FS
6394 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6395 #else /* AFS_DEMAND_ATTACH_FS */
6396 DeleteVolumeFromHashTable(vp);
6397 vp->shuttingDown = 1; /* Let who has it free it. */
6398 vp->specialStatus = 0;
6399 #endif /* AFS_DEMAND_ATTACH_FS */
6403 #ifndef AFS_DEMAND_ATTACH_FS
6405 vp->specialStatus = 0; /* Allow others to have access. */
6406 #endif /* AFS_DEMAND_ATTACH_FS */
6409 #endif /* BITMAP_LATER */
6411 #ifdef AFS_DEMAND_ATTACH_FS
6413 #endif /* AFS_DEMAND_ATTACH_FS */
6414 bp = index->bitmap + index->bitmapOffset;
6415 ep = index->bitmap + index->bitmapSize;
6417 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6419 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6422 o = opr_ffs(~*bp) - 1;
6424 ret = ((bp - index->bitmap) * 8 + o);
6425 #ifdef AFS_DEMAND_ATTACH_FS
6427 #endif /* AFS_DEMAND_ATTACH_FS */
6430 bp += sizeof(bit32) /* i.e. 4 */ ;
6432 /* No bit map entry--must grow bitmap */
6434 bp = index->bitmap + index->bitmapOffset;
6436 ret = index->bitmapOffset * 8;
6437 #ifdef AFS_DEMAND_ATTACH_FS
6439 #endif /* AFS_DEMAND_ATTACH_FS */
6442 #ifdef AFS_DEMAND_ATTACH_FS
6443 VChangeState_r(vp, state_save);
6444 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6445 VCancelReservation_r(vp);
6447 #endif /* AFS_DEMAND_ATTACH_FS */
6452 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6456 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6462 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6463 unsigned bitNumber, int flags)
6465 unsigned int offset;
6469 #ifdef AFS_DEMAND_ATTACH_FS
6470 if (flags & VOL_FREE_BITMAP_WAIT) {
6471 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6472 * state, so ensure we're not in an exclusive volume state when we update
6474 VCreateReservation_r(vp);
6475 VWaitExclusiveState_r(vp);
6482 #endif /* BITMAP_LATER */
6484 offset = bitNumber >> 3;
6485 if (offset >= index->bitmapSize) {
6489 if (offset < index->bitmapOffset)
6490 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6491 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6494 #ifdef AFS_DEMAND_ATTACH_FS
6495 if (flags & VOL_FREE_BITMAP_WAIT) {
6496 VCancelReservation_r(vp);
6499 return; /* make the compiler happy for non-DAFS */
6503 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6507 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6511 /* this function will drop the glock internally.
6512 * for old pthread fileservers, this is safe thanks to vbusy.
6514 * for demand attach fs, caller must have already called
6515 * VCreateReservation_r and VWaitExclusiveState_r */
6517 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6519 StreamHandle_t *file;
6520 afs_sfsize_t nVnodes, size;
6521 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6522 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6523 struct VnodeDiskObject *vnode;
6524 unsigned int unique = 0;
6528 #endif /* BITMAP_LATER */
6529 #ifdef AFS_DEMAND_ATTACH_FS
6530 VolState state_save;
6531 #endif /* AFS_DEMAND_ATTACH_FS */
6535 #ifdef AFS_DEMAND_ATTACH_FS
6536 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6537 #endif /* AFS_DEMAND_ATTACH_FS */
6540 fdP = IH_OPEN(vip->handle);
6541 opr_Assert(fdP != NULL);
6542 file = FDH_FDOPEN(fdP, "r");
6543 opr_Assert(file != NULL);
6544 vnode = malloc(vcp->diskSize);
6545 opr_Assert(vnode != NULL);
6546 size = OS_SIZE(fdP->fd_fd);
6547 opr_Assert(size != -1);
6548 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6550 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6551 * a few files can be created in this volume,
6552 * the whole thing is rounded up to nearest 4
6553 * bytes, because the bit map allocator likes
6556 BitMap = (byte *) calloc(1, vip->bitmapSize);
6557 opr_Assert(BitMap != NULL);
6558 #else /* BITMAP_LATER */
6559 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6560 opr_Assert(vip->bitmap != NULL);
6561 vip->bitmapOffset = 0;
6562 #endif /* BITMAP_LATER */
6563 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6565 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6566 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6568 if (vnode->type != vNull) {
6569 if (vnode->vnodeMagic != vcp->magic) {
6570 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6575 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6576 #else /* BITMAP_LATER */
6577 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6578 #endif /* BITMAP_LATER */
6579 if (unique <= vnode->uniquifier)
6580 unique = vnode->uniquifier + 1;
6582 #ifndef AFS_PTHREAD_ENV
6583 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6586 #endif /* !AFS_PTHREAD_ENV */
6589 if (vp->nextVnodeUnique < unique) {
6590 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6593 /* Paranoia, partly justified--I think fclose after fdopen
6594 * doesn't seem to close fd. In any event, the documentation
6595 * doesn't specify, so it's safer to close it twice.
6603 /* There may have been a racing condition with some other thread, both
6604 * creating the bitmaps for this volume. If the other thread was faster
6605 * the pointer to bitmap should already be filled and we can free ours.
6607 if (vip->bitmap == NULL) {
6608 vip->bitmap = BitMap;
6609 vip->bitmapOffset = 0;
6612 #endif /* BITMAP_LATER */
6613 #ifdef AFS_DEMAND_ATTACH_FS
6614 VChangeState_r(vp, state_save);
6615 #endif /* AFS_DEMAND_ATTACH_FS */
6619 /***************************************************/
6620 /* Volume Path and Volume Number utility routines */
6621 /***************************************************/
6624 * find the first occurrence of a volume header file and return the path.
6626 * @param[out] ec outbound error code
6627 * @param[in] volumeId volume id to find
6628 * @param[out] partitionp pointer to disk partition path string
6629 * @param[out] namep pointer to volume header file name string
6631 * @post path to first occurrence of volume header is returned in partitionp
6632 * and namep, or ec is set accordingly.
6634 * @warning this function is NOT re-entrant -- partitionp and namep point to
6635 * static data segments
6637 * @note if a volume utility inadvertently leaves behind a stale volume header
6638 * on a vice partition, it is possible for callers to get the wrong one,
6639 * depending on the order of the disk partition linked list.
6643 VGetVolumePath(Error * ec, VolumeId volumeId, char **partitionp, char **namep)
6645 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6646 char path[VMAXPATHLEN];
6648 struct DiskPartition64 *dp;
6651 name[0] = OS_DIRSEPC;
6652 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6653 afs_printable_VolumeId_lu(volumeId));
6654 for (dp = DiskPartitionList; dp; dp = dp->next) {
6655 struct afs_stat_st status;
6656 strcpy(path, VPartitionPath(dp));
6658 if (afs_stat(path, &status) == 0) {
6659 strcpy(partition, dp->name);
6666 *partitionp = *namep = NULL;
6668 *partitionp = partition;
6674 * extract a volume number from a volume header filename string.
6676 * @param[in] name volume header filename string
6678 * @return volume number
6680 * @note the string must be of the form VFORMAT. the only permissible
6681 * deviation is a leading OS_DIRSEPC character.
6686 VolumeNumber(char *name)
6688 if (*name == OS_DIRSEPC)
6690 return strtoul(name + 1, NULL, 10);
6694 * compute the volume header filename.
6696 * @param[in] volumeId
6698 * @return volume header filename
6700 * @post volume header filename string is constructed
6702 * @warning this function is NOT re-entrant -- the returned string is
6703 * stored in a static char array. see VolumeExternalName_r
6704 * for a re-entrant equivalent.
6706 * @see VolumeExternalName_r
6708 * @deprecated due to the above re-entrancy warning, this interface should
6709 * be considered deprecated. Please use VolumeExternalName_r
6713 VolumeExternalName(VolumeId volumeId)
6715 static char name[VMAXPATHLEN];
6716 snprintf(name, sizeof name, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6721 * compute the volume header filename.
6723 * @param[in] volumeId
6724 * @param[inout] name array in which to store filename
6725 * @param[in] len length of name array
6727 * @return result code from afs_snprintf
6729 * @see VolumeExternalName
6732 * @note re-entrant equivalent of VolumeExternalName
6735 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6737 return snprintf(name, len, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6741 /***************************************************/
6742 /* Volume Usage Statistics routines */
6743 /***************************************************/
6745 #define OneDay (86400) /* 24 hours' worth of seconds */
6748 Midnight(time_t t) {
6749 struct tm local, *l;
6752 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6753 l = localtime_r(&t, &local);
6759 /* the following is strictly speaking problematic on the
6760 switching day to daylight saving time, after the switch,
6761 as tm_isdst does not match. Similarly, on the looong day when
6762 switching back the OneDay check will not do what naively expected!
6763 The effects are minor, though, and more a matter of interpreting
6765 #ifndef AFS_PTHREAD_ENV
6768 local.tm_hour = local.tm_min=local.tm_sec = 0;
6769 midnight = mktime(&local);
6770 if (midnight != (time_t) -1) return(midnight);
6772 return( (t/OneDay)*OneDay );
6776 /*------------------------------------------------------------------------
6777 * [export] VAdjustVolumeStatistics
6780 * If we've passed midnight, we need to update all the day use
6781 * statistics as well as zeroing the detailed volume statistics
6782 * (if we are implementing them).
6785 * vp : Pointer to the volume structure describing the lucky
6786 * volume being considered for update.
6792 * Nothing interesting.
6796 *------------------------------------------------------------------------*/
6799 VAdjustVolumeStatistics_r(Volume * vp)
6801 unsigned int now = FT_ApproxTime();
6803 if (now - V_dayUseDate(vp) > OneDay) {
6806 ndays = (now - V_dayUseDate(vp)) / OneDay;
6807 for (i = 6; i > ndays - 1; i--)
6808 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6809 for (i = 0; i < ndays - 1 && i < 7; i++)
6810 V_weekUse(vp)[i] = 0;
6812 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6814 V_dayUseDate(vp) = Midnight(now);
6817 * All we need to do is bzero the entire VOL_STATS_BYTES of
6818 * the detailed volume statistics area.
6820 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6823 /*It's been more than a day of collection */
6825 * Always return happily.
6828 } /*VAdjustVolumeStatistics */
6831 VAdjustVolumeStatistics(Volume * vp)
6835 retVal = VAdjustVolumeStatistics_r(vp);
6841 VBumpVolumeUsage_r(Volume * vp)
6843 unsigned int now = FT_ApproxTime();
6844 V_accessDate(vp) = now;
6845 if (now - V_dayUseDate(vp) > OneDay)
6846 VAdjustVolumeStatistics_r(vp);
6848 * Save the volume header image to disk after a threshold of bumps to dayUse,
6849 * at most every usage_rate_limit seconds.
6852 vp->usage_bumps_outstanding++;
6853 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6854 && vp->usage_bumps_next_write <= now) {
6856 vp->usage_bumps_outstanding = 0;
6857 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6858 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6863 VBumpVolumeUsage(Volume * vp)
6866 VBumpVolumeUsage_r(vp);
6871 VSetDiskUsage_r(void)
6873 #ifndef AFS_DEMAND_ATTACH_FS
6874 static int FifteenMinuteCounter = 0;
6878 /* NOTE: Don't attempt to access the partitions list until the
6879 * initialization level indicates that all volumes are attached,
6880 * which implies that all partitions are initialized. */
6881 #ifdef AFS_PTHREAD_ENV
6882 VOL_CV_WAIT(&vol_vinit_cond);
6883 #else /* AFS_PTHREAD_ENV */
6885 #endif /* AFS_PTHREAD_ENV */
6888 VResetDiskUsage_r();
6890 #ifndef AFS_DEMAND_ATTACH_FS
6891 if (++FifteenMinuteCounter == 3) {
6892 FifteenMinuteCounter = 0;
6895 #endif /* !AFS_DEMAND_ATTACH_FS */
6907 /***************************************************/
6908 /* Volume Update List routines */
6909 /***************************************************/
6911 /* The number of minutes that a volume hasn't been updated before the
6912 * "Dont salvage" flag in the volume header will be turned on */
6913 #define SALVAGE_INTERVAL (10*60)
6918 * volume update list functionality has been moved into the VLRU
6919 * the DONT_SALVAGE flag is now set during VLRU demotion
6922 #ifndef AFS_DEMAND_ATTACH_FS
6923 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6924 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6925 static int updateSize = 0; /* number of entries possible */
6926 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6927 #endif /* !AFS_DEMAND_ATTACH_FS */
6930 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6933 vp->updateTime = FT_ApproxTime();
6934 if (V_dontSalvage(vp) == 0)
6936 V_dontSalvage(vp) = 0;
6937 VSyncVolume_r(ec, vp, 0);
6938 #ifdef AFS_DEMAND_ATTACH_FS
6939 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6940 #else /* !AFS_DEMAND_ATTACH_FS */
6943 if (UpdateList == NULL) {
6944 updateSize = UPDATE_LIST_SIZE;
6945 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6947 if (nUpdatedVolumes == updateSize) {
6949 if (updateSize > 524288) {
6950 Log("warning: there is likely a bug in the volume update scanner\n");
6953 UpdateList = realloc(UpdateList,
6954 sizeof(VolumeId) * updateSize);
6957 opr_Assert(UpdateList != NULL);
6958 UpdateList[nUpdatedVolumes++] = V_id(vp);
6959 #endif /* !AFS_DEMAND_ATTACH_FS */
6962 #ifndef AFS_DEMAND_ATTACH_FS
6964 VScanUpdateList(void)
6969 afs_uint32 now = FT_ApproxTime();
6970 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6971 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6973 UpdateList[i - gap] = UpdateList[i];
6975 /* XXX this routine needlessly messes up the Volume LRU by
6976 * breaking the LRU temporal-locality assumptions.....
6977 * we should use a special volume header allocator here */
6978 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6981 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6982 V_dontSalvage(vp) = DONT_SALVAGE;
6983 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6991 #ifndef AFS_PTHREAD_ENV
6993 #endif /* !AFS_PTHREAD_ENV */
6995 nUpdatedVolumes -= gap;
6997 #endif /* !AFS_DEMAND_ATTACH_FS */
7000 /***************************************************/
7001 /* Volume LRU routines */
7002 /***************************************************/
7007 * with demand attach fs, we attempt to soft detach(1)
7008 * volumes which have not been accessed in a long time
7009 * in order to speed up fileserver shutdown
7011 * (1) by soft detach we mean a process very similar
7012 * to VOffline, except the final state of the
7013 * Volume will be VOL_STATE_PREATTACHED, instead
7014 * of the usual VOL_STATE_UNATTACHED
7016 #ifdef AFS_DEMAND_ATTACH_FS
7018 /* implementation is reminiscent of a generational GC
7020 * queue 0 is newly attached volumes. this queue is
7021 * sorted by attach timestamp
7023 * queue 1 is volumes that have been around a bit
7024 * longer than queue 0. this queue is sorted by
7027 * queue 2 is volumes tha have been around the longest.
7028 * this queue is unsorted
7030 * queue 3 is volumes that have been marked as
7031 * candidates for soft detachment. this queue is
7034 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
7035 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
7038 * definition of a VLRU queue.
7041 volatile struct rx_queue q;
7048 * main VLRU data structure.
7051 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
7054 /** time interval (in seconds) between promotion passes for
7055 * each young generation queue. */
7056 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
7058 /** time interval (in seconds) between soft detach candidate
7059 * scans for each generation queue.
7061 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
7062 * we perform a soft detach pass. */
7063 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
7065 /* scheduler state */
7066 int next_idx; /**< next queue to receive attention */
7067 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
7068 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
7070 int scanner_state; /**< state of scanner thread */
7071 pthread_cond_t cv; /**< state transition CV */
7074 /** global VLRU state */
7075 static struct VLRU volume_LRU;
7078 * defined states for VLRU scanner thread.
7081 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7082 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7083 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7084 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7085 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7086 } vlru_thread_state_t;
7088 /* vlru disk data header stuff */
7089 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7090 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7092 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7093 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7096 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7097 * soft detachment. */
7098 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7100 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7101 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7103 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7104 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7106 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7107 static afs_uint32 VLRU_enabled = 1;
7109 /* queue synchronization routines */
7110 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7111 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7112 static void VLRU_Wait_r(struct VLRU_q * q);
7115 * set VLRU subsystem tunable parameters.
7117 * @param[in] option tunable option to modify
7118 * @param[in] val new value for tunable parameter
7120 * @pre @c VInitVolumePackage2 has not yet been called.
7122 * @post tunable parameter is modified
7126 * @note valid option parameters are:
7127 * @arg @c VLRU_SET_THRESH
7128 * set the period of inactivity after which
7129 * volumes are eligible for soft detachment
7130 * @arg @c VLRU_SET_INTERVAL
7131 * set the time interval between calls
7132 * to the volume LRU "garbage collector"
7133 * @arg @c VLRU_SET_MAX
7134 * set the max number of volumes to deallocate
7138 VLRU_SetOptions(int option, afs_uint32 val)
7140 if (option == VLRU_SET_THRESH) {
7141 VLRU_offline_thresh = val;
7142 } else if (option == VLRU_SET_INTERVAL) {
7143 VLRU_offline_interval = val;
7144 } else if (option == VLRU_SET_MAX) {
7145 VLRU_offline_max = val;
7146 } else if (option == VLRU_SET_ENABLED) {
7149 VLRU_ComputeConstants();
7153 * compute VLRU internal timing parameters.
7155 * @post VLRU scanner thread internal timing parameters are computed
7157 * @note computes internal timing parameters based upon user-modifiable
7158 * tunable parameters.
7162 * @internal volume package internal use only.
7165 VLRU_ComputeConstants(void)
7167 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7169 /* compute the candidate scan interval */
7170 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7172 /* compute the promotion intervals */
7173 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7174 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7177 /* compute the gen 0 scan interval */
7178 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7180 /* compute the gen 0 scan interval */
7181 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7186 * initialize VLRU subsystem.
7188 * @pre this function has not yet been called
7190 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7194 * @internal volume package internal use only.
7200 pthread_attr_t attrs;
7203 if (!VLRU_enabled) {
7204 Log("VLRU: disabled\n");
7208 /* initialize each of the VLRU queues */
7209 for (i = 0; i < VLRU_QUEUES; i++) {
7210 queue_Init(&volume_LRU.q[i]);
7211 volume_LRU.q[i].len = 0;
7212 volume_LRU.q[i].busy = 0;
7213 opr_cv_init(&volume_LRU.q[i].cv);
7216 /* setup the timing constants */
7217 VLRU_ComputeConstants();
7219 /* XXX put inside log level check? */
7220 Log("VLRU: starting scanner with the following configuration parameters:\n");
7221 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7222 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7223 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7224 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7225 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7226 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7228 /* start up the VLRU scanner */
7229 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7230 if (programType == fileServer) {
7231 opr_cv_init(&volume_LRU.cv);
7232 opr_Verify(pthread_attr_init(&attrs) == 0);
7233 opr_Verify(pthread_attr_setdetachstate(&attrs,
7234 PTHREAD_CREATE_DETACHED) == 0);
7235 opr_Verify(pthread_create(&tid, &attrs,
7236 &VLRU_ScannerThread, NULL) == 0);
7241 * initialize the VLRU-related fields of a newly allocated volume object.
7243 * @param[in] vp pointer to volume object
7246 * @arg @c VOL_LOCK is held.
7247 * @arg volume object is not on a VLRU queue.
7249 * @post VLRU fields are initialized to indicate that volume object is not
7250 * currently registered with the VLRU subsystem
7254 * @internal volume package interal use only.
7257 VLRU_Init_Node_r(Volume * vp)
7262 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7263 vp->vlru.idx = VLRU_QUEUE_INVALID;
7267 * add a volume object to a VLRU queue.
7269 * @param[in] vp pointer to volume object
7272 * @arg @c VOL_LOCK is held.
7273 * @arg caller MUST hold a lightweight ref on @p vp.
7274 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7276 * @post the volume object is added to the appropriate VLRU queue
7278 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7279 * then the volume is added to that queue. Otherwise, the value
7280 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7281 * volume is added to the NEW generation queue.
7283 * @note @c VOL_LOCK may be dropped internally
7285 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7286 * during the add operation, and is restored to the previous
7287 * state prior to return.
7291 * @internal volume package internal use only.
7294 VLRU_Add_r(Volume * vp)
7297 VolState state_save;
7302 if (queue_IsOnQueue(&vp->vlru))
7305 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7308 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7309 idx = VLRU_QUEUE_NEW;
7312 VLRU_Wait_r(&volume_LRU.q[idx]);
7314 /* repeat check since VLRU_Wait_r may have dropped
7316 if (queue_IsNotOnQueue(&vp->vlru)) {
7318 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7319 volume_LRU.q[idx].len++;
7320 V_attachFlags(vp) |= VOL_ON_VLRU;
7321 vp->stats.last_promote = FT_ApproxTime();
7324 VChangeState_r(vp, state_save);
7328 * delete a volume object from a VLRU queue.
7330 * @param[in] vp pointer to volume object
7333 * @arg @c VOL_LOCK is held.
7334 * @arg caller MUST hold a lightweight ref on @p vp.
7335 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7337 * @post volume object is removed from the VLRU queue
7339 * @note @c VOL_LOCK may be dropped internally
7343 * @todo We should probably set volume state to something exlcusive
7344 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7346 * @internal volume package internal use only.
7349 VLRU_Delete_r(Volume * vp)
7356 if (queue_IsNotOnQueue(&vp->vlru))
7362 if (idx == VLRU_QUEUE_INVALID)
7364 VLRU_Wait_r(&volume_LRU.q[idx]);
7365 } while (idx != vp->vlru.idx);
7367 /* now remove from the VLRU and update
7368 * the appropriate counter */
7369 queue_Remove(&vp->vlru);
7370 volume_LRU.q[idx].len--;
7371 vp->vlru.idx = VLRU_QUEUE_INVALID;
7372 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7376 * tell the VLRU subsystem that a volume was just accessed.
7378 * @param[in] vp pointer to volume object
7381 * @arg @c VOL_LOCK is held
7382 * @arg caller MUST hold a lightweight ref on @p vp
7383 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7385 * @post volume VLRU access statistics are updated. If the volume was on
7386 * the VLRU soft detach candidate queue, it is moved to the NEW
7389 * @note @c VOL_LOCK may be dropped internally
7393 * @internal volume package internal use only.
7396 VLRU_UpdateAccess_r(Volume * vp)
7398 Volume * rvp = NULL;
7403 if (queue_IsNotOnQueue(&vp->vlru))
7406 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7408 /* update the access timestamp */
7409 vp->stats.last_get = FT_ApproxTime();
7412 * if the volume is on the soft detach candidate
7413 * list, we need to safely move it back to a
7414 * regular generation. this has to be done
7415 * carefully so we don't race against the scanner
7419 /* if this volume is on the soft detach candidate queue,
7420 * then grab exclusive access to the necessary queues */
7421 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7423 VCreateReservation_r(rvp);
7425 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7426 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7427 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7428 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7431 /* make sure multiple threads don't race to update */
7432 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7433 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7437 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7438 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7439 VCancelReservation_r(rvp);
7444 * switch a volume between two VLRU queues.
7446 * @param[in] vp pointer to volume object
7447 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7448 * @param[in] append controls whether the volume will be appended or
7449 * prepended to the queue. A nonzero value means it will
7450 * be appended; zero means it will be prepended.
7452 * @pre The new (and old, if applicable) queue(s) must either be owned
7453 * exclusively by the calling thread for asynchronous manipulation,
7454 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7455 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7456 * for further details of the queue asynchronous processing mechanism.
7458 * @post If the volume object was already on a VLRU queue, it is
7459 * removed from the queue. Depending on the value of the append
7460 * parameter, the volume object is either appended or prepended
7461 * to the VLRU queue referenced by the new_idx parameter.
7465 * @see VLRU_BeginExclusive_r
7466 * @see VLRU_EndExclusive_r
7469 * @internal volume package internal use only.
7472 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7474 if (queue_IsNotOnQueue(&vp->vlru))
7477 queue_Remove(&vp->vlru);
7478 volume_LRU.q[vp->vlru.idx].len--;
7480 /* put the volume back on the correct generational queue */
7482 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7484 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7487 volume_LRU.q[new_idx].len++;
7488 vp->vlru.idx = new_idx;
7492 * VLRU background thread.
7494 * The VLRU Scanner Thread is responsible for periodically scanning through
7495 * each VLRU queue looking for volumes which should be moved to another
7496 * queue, or soft detached.
7498 * @param[in] args unused thread arguments parameter
7500 * @return unused thread return value
7501 * @retval NULL always
7503 * @internal volume package internal use only.
7506 VLRU_ScannerThread(void * args)
7508 afs_uint32 now, min_delay, delay;
7509 int i, min_idx, min_op, overdue, state;
7511 /* set t=0 for promotion cycle to be
7512 * fileserver startup */
7513 now = FT_ApproxTime();
7514 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7515 volume_LRU.last_promotion[i] = now;
7518 /* don't start the scanner until VLRU_offline_thresh
7519 * plus a small delay for VInitVolumePackage2 to finish
7522 sleep(VLRU_offline_thresh + 60);
7524 /* set t=0 for scan cycle to be now */
7525 now = FT_ApproxTime();
7526 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7527 volume_LRU.last_scan[i] = now;
7531 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7532 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7535 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7536 /* check to see if we've been asked to pause */
7537 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7538 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7539 opr_cv_broadcast(&volume_LRU.cv);
7541 VOL_CV_WAIT(&volume_LRU.cv);
7542 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7545 /* scheduling can happen outside the glock */
7548 /* figure out what is next on the schedule */
7550 /* figure out a potential schedule for the new generation first */
7552 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7555 if (min_delay > volume_LRU.scan_interval[0]) {
7556 /* unsigned overflow -- we're overdue to run this scan */
7561 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7563 i = VLRU_QUEUE_CANDIDATE;
7564 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7565 if (delay < min_delay) {
7569 if (delay > volume_LRU.scan_interval[i]) {
7570 /* unsigned overflow -- we're overdue to run this scan */
7577 /* if we're still not overdue for something, figure out schedules for promotions */
7578 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7579 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7580 if (delay < min_delay) {
7585 if (delay > volume_LRU.promotion_interval[i]) {
7586 /* unsigned overflow -- we're overdue to run this promotion */
7595 /* sleep as needed */
7600 /* do whatever is next */
7603 VLRU_Promote_r(min_idx);
7604 VLRU_Demote_r(min_idx+1);
7606 VLRU_Scan_r(min_idx);
7608 now = FT_ApproxTime();
7611 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7613 /* signal that scanner is down */
7614 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7615 opr_cv_broadcast(&volume_LRU.cv);
7621 * promote volumes from one VLRU generation to the next.
7623 * This routine scans a VLRU generation looking for volumes which are
7624 * eligible to be promoted to the next generation. All volumes which
7625 * meet the eligibility requirement are promoted.
7627 * Promotion eligibility is based upon meeting both of the following
7630 * @arg The volume has been accessed since the last promotion:
7631 * @c (vp->stats.last_get >= vp->stats.last_promote)
7632 * @arg The last promotion occurred at least
7633 * @c volume_LRU.promotion_interval[idx] seconds ago
7635 * As a performance optimization, promotions are "globbed". In other
7636 * words, we promote arbitrarily large contiguous sublists of elements
7639 * @param[in] idx VLRU queue index to scan
7643 * @internal VLRU internal use only.
7646 VLRU_Promote_r(int idx)
7648 int len, chaining, promote;
7649 afs_uint32 now, thresh;
7650 struct rx_queue *qp, *nqp;
7651 Volume * vp, *start = NULL, *end = NULL;
7653 /* get exclusive access to two chains, and drop the glock */
7654 VLRU_Wait_r(&volume_LRU.q[idx]);
7655 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7656 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7657 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7660 thresh = volume_LRU.promotion_interval[idx];
7661 now = FT_ApproxTime();
7664 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7665 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7666 promote = (((vp->stats.last_promote + thresh) <= now) &&
7667 (vp->stats.last_get >= vp->stats.last_promote));
7675 /* promote and prepend chain */
7676 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7690 /* promote and prepend */
7691 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7695 volume_LRU.q[idx].len -= len;
7696 volume_LRU.q[idx+1].len += len;
7699 /* release exclusive access to the two chains */
7701 volume_LRU.last_promotion[idx] = now;
7702 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7703 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7706 /* run the demotions */
7708 VLRU_Demote_r(int idx)
7711 int len, chaining, demote;
7712 afs_uint32 now, thresh;
7713 struct rx_queue *qp, *nqp;
7714 Volume * vp, *start = NULL, *end = NULL;
7715 Volume ** salv_flag_vec = NULL;
7716 int salv_vec_offset = 0;
7718 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7720 /* get exclusive access to two chains, and drop the glock */
7721 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7722 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7723 VLRU_Wait_r(&volume_LRU.q[idx]);
7724 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7727 /* no big deal if this allocation fails */
7728 if (volume_LRU.q[idx].len) {
7729 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7732 now = FT_ApproxTime();
7733 thresh = volume_LRU.promotion_interval[idx-1];
7736 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7737 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7738 demote = (((vp->stats.last_promote + thresh) <= now) &&
7739 (vp->stats.last_get < (now - thresh)));
7741 /* we now do volume update list DONT_SALVAGE flag setting during
7742 * demotion passes */
7743 if (salv_flag_vec &&
7744 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7746 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7747 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7748 salv_flag_vec[salv_vec_offset++] = vp;
7749 VCreateReservation_r(vp);
7758 /* demote and append chain */
7759 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7773 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7777 volume_LRU.q[idx].len -= len;
7778 volume_LRU.q[idx-1].len += len;
7781 /* release exclusive access to the two chains */
7783 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7784 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7786 /* now go back and set the DONT_SALVAGE flags as appropriate */
7787 if (salv_flag_vec) {
7789 for (i = 0; i < salv_vec_offset; i++) {
7790 vp = salv_flag_vec[i];
7791 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7792 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7793 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7796 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7797 V_dontSalvage(vp) = DONT_SALVAGE;
7798 VUpdateVolume_r(&ec, vp, 0);
7802 VCancelReservation_r(vp);
7804 free(salv_flag_vec);
7808 /* run a pass of the VLRU GC scanner */
7810 VLRU_Scan_r(int idx)
7812 afs_uint32 now, thresh;
7813 struct rx_queue *qp, *nqp;
7817 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7819 /* gain exclusive access to the idx VLRU */
7820 VLRU_Wait_r(&volume_LRU.q[idx]);
7821 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7823 if (idx != VLRU_QUEUE_CANDIDATE) {
7824 /* gain exclusive access to the candidate VLRU */
7825 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7826 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7829 now = FT_ApproxTime();
7830 thresh = now - VLRU_offline_thresh;
7832 /* perform candidate selection and soft detaching */
7833 if (idx == VLRU_QUEUE_CANDIDATE) {
7834 /* soft detach some volumes from the candidate pool */
7838 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7839 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7840 if (i >= VLRU_offline_max) {
7843 /* check timestamp to see if it's a candidate for soft detaching */
7844 if (vp->stats.last_get <= thresh) {
7846 if (VCheckSoftDetach(vp, thresh))
7852 /* scan for volumes to become soft detach candidates */
7853 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7854 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7856 /* check timestamp to see if it's a candidate for soft detaching */
7857 if (vp->stats.last_get <= thresh) {
7858 VCheckSoftDetachCandidate(vp, thresh);
7861 if (!(i&0x7f)) { /* lock coarsening optimization */
7869 /* relinquish exclusive access to the VLRU chains */
7873 volume_LRU.last_scan[idx] = now;
7874 if (idx != VLRU_QUEUE_CANDIDATE) {
7875 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7877 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7880 /* check whether volume is safe to soft detach
7881 * caller MUST NOT hold a ref count on vp */
7883 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7887 if (vp->nUsers || vp->nWaiters)
7890 if (vp->stats.last_get <= thresh) {
7891 ret = VSoftDetachVolume_r(vp, thresh);
7897 /* check whether volume should be made a
7898 * soft detach candidate */
7900 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7903 if (vp->nUsers || vp->nWaiters)
7908 opr_Assert(idx == VLRU_QUEUE_NEW);
7910 if (vp->stats.last_get <= thresh) {
7911 /* move to candidate pool */
7912 queue_Remove(&vp->vlru);
7913 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7914 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7915 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7916 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7924 /* begin exclusive access on VLRU */
7926 VLRU_BeginExclusive_r(struct VLRU_q * q)
7928 opr_Assert(q->busy == 0);
7932 /* end exclusive access on VLRU */
7934 VLRU_EndExclusive_r(struct VLRU_q * q)
7936 opr_Assert(q->busy);
7938 opr_cv_broadcast(&q->cv);
7941 /* wait for another thread to end exclusive access on VLRU */
7943 VLRU_Wait_r(struct VLRU_q * q)
7946 VOL_CV_WAIT(&q->cv);
7951 * volume soft detach
7953 * caller MUST NOT hold a ref count on vp */
7955 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7960 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7962 ts_save = vp->stats.last_get;
7963 if (ts_save > thresh)
7966 if (vp->nUsers || vp->nWaiters)
7969 if (VIsExclusiveState(V_attachState(vp))) {
7973 switch (V_attachState(vp)) {
7974 case VOL_STATE_UNATTACHED:
7975 case VOL_STATE_PREATTACHED:
7976 case VOL_STATE_ERROR:
7977 case VOL_STATE_GOING_OFFLINE:
7978 case VOL_STATE_SHUTTING_DOWN:
7979 case VOL_STATE_SALVAGING:
7980 case VOL_STATE_DELETED:
7981 volume_LRU.q[vp->vlru.idx].len--;
7983 /* create and cancel a reservation to
7984 * give the volume an opportunity to
7986 VCreateReservation_r(vp);
7987 queue_Remove(&vp->vlru);
7988 vp->vlru.idx = VLRU_QUEUE_INVALID;
7989 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7990 VCancelReservation_r(vp);
7996 /* hold the volume and take it offline.
7997 * no need for reservations, as VHold_r
7998 * takes care of that internally. */
7999 if (VHold_r(vp) == 0) {
8000 /* vhold drops the glock, so now we should
8001 * check to make sure we aren't racing against
8002 * other threads. if we are racing, offlining vp
8003 * would be wasteful, and block the scanner for a while
8007 (vp->shuttingDown) ||
8008 (vp->goingOffline) ||
8009 (vp->stats.last_get != ts_save)) {
8010 /* looks like we're racing someone else. bail */
8014 /* pull it off the VLRU */
8015 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
8016 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
8017 queue_Remove(&vp->vlru);
8018 vp->vlru.idx = VLRU_QUEUE_INVALID;
8019 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
8021 /* take if offline */
8022 VOffline_r(vp, "volume has been soft detached");
8024 /* invalidate the volume header cache */
8025 FreeVolumeHeader(vp);
8028 IncUInt64(&VStats.soft_detaches);
8029 vp->stats.soft_detaches++;
8031 /* put in pre-attached state so demand
8032 * attacher can work on it */
8033 VChangeState_r(vp, VOL_STATE_PREATTACHED);
8039 #endif /* AFS_DEMAND_ATTACH_FS */
8042 /***************************************************/
8043 /* Volume Header Cache routines */
8044 /***************************************************/
8047 * volume header cache.
8049 struct volume_hdr_LRU_t volume_hdr_LRU;
8052 * initialize the volume header cache.
8054 * @param[in] howMany number of header cache entries to preallocate
8056 * @pre VOL_LOCK held. Function has never been called before.
8058 * @post howMany cache entries are allocated, initialized, and added
8059 * to the LRU list. Header cache statistics are initialized.
8061 * @note only applicable to fileServer program type. Should only be
8062 * called once during volume package initialization.
8064 * @internal volume package internal use only.
8067 VInitVolumeHeaderCache(afs_uint32 howMany)
8069 struct volHeader *hp;
8070 if (programType != fileServer)
8072 queue_Init(&volume_hdr_LRU);
8073 volume_hdr_LRU.stats.free = 0;
8074 volume_hdr_LRU.stats.used = howMany;
8075 volume_hdr_LRU.stats.attached = 0;
8076 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8077 opr_Assert(hp != NULL);
8080 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8081 * to ensure they have the right values
8083 ReleaseVolumeHeader(hp++);
8086 /* get a volume header off of the volume header LRU.
8088 * @return volume header
8089 * @retval NULL no usable volume header is available on the LRU
8091 * @pre VOL_LOCK held
8093 * @post for DAFS, if the returned header is associated with a volume, that
8094 * volume is NOT in an exclusive state
8096 * @internal volume package internal use only.
8098 #ifdef AFS_DEMAND_ATTACH_FS
8099 static struct volHeader*
8100 GetVolHeaderFromLRU(void)
8102 struct volHeader *hd = NULL, *qh, *nqh;
8103 /* Usually, a volume in an exclusive state will not have its header on
8104 * the LRU. However, it is possible for this to occur when a salvage
8105 * request is received over FSSYNC, and possibly in other corner cases.
8106 * So just skip over headers whose volumes are in an exclusive state. We
8107 * could VWaitExclusiveState_r instead, but not waiting is faster and
8109 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8110 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8118 #else /* AFS_DEMAND_ATTACH_FS */
8119 static struct volHeader*
8120 GetVolHeaderFromLRU(void)
8122 struct volHeader *hd = NULL;
8123 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8124 hd = queue_First(&volume_hdr_LRU, volHeader);
8129 #endif /* !AFS_DEMAND_ATTACH_FS */
8132 * get a volume header and attach it to the volume object.
8134 * @param[in] vp pointer to volume object
8136 * @return cache entry status
8137 * @retval 0 volume header was newly attached; cache data is invalid
8138 * @retval 1 volume header was previously attached; cache data is valid
8140 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8142 * @post volume header attached to volume object. if necessary, header cache
8143 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8145 * @note VOL_LOCK may be dropped
8147 * @warning this interface does not load header data from disk. it merely
8148 * attaches a header object to the volume object, and may sync the old
8149 * header cache data out to disk in the process.
8151 * @internal volume package internal use only.
8154 GetVolumeHeader(Volume * vp)
8157 struct volHeader *hd;
8159 static int everLogged = 0;
8161 #ifdef AFS_DEMAND_ATTACH_FS
8162 VolState vp_save = 0, back_save = 0;
8164 /* XXX debug 9/19/05 we've apparently got
8165 * a ref counting bug somewhere that's
8166 * breaking the nUsers == 0 => header on LRU
8168 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8169 Log("nUsers == 0, but header not on LRU\n");
8174 old = (vp->header != NULL); /* old == volume already has a header */
8176 if (programType != fileServer) {
8177 /* for volume utilities, we allocate volHeaders as needed */
8179 hd = calloc(1, sizeof(*vp->header));
8180 opr_Assert(hd != NULL);
8183 #ifdef AFS_DEMAND_ATTACH_FS
8184 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8188 /* for the fileserver, we keep a volume header cache */
8190 /* the header we previously dropped in the lru is
8191 * still available. pull it off the lru and return */
8194 opr_Assert(hd->back == vp);
8195 #ifdef AFS_DEMAND_ATTACH_FS
8196 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8199 hd = GetVolHeaderFromLRU();
8201 /* LRU is empty, so allocate a new volHeader
8202 * this is probably indicative of a leak, so let the user know */
8203 hd = calloc(1, sizeof(struct volHeader));
8204 opr_Assert(hd != NULL);
8206 Log("****Allocated more volume headers, probably leak****\n");
8209 volume_hdr_LRU.stats.free++;
8212 /* this header used to belong to someone else.
8213 * we'll need to check if the header needs to
8214 * be sync'd out to disk */
8216 #ifdef AFS_DEMAND_ATTACH_FS
8217 /* GetVolHeaderFromLRU had better not give us back a header
8218 * with a volume in exclusive state... */
8219 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8222 if (hd->diskstuff.inUse) {
8223 /* volume was in use, so we'll need to sync
8224 * its header to disk */
8226 #ifdef AFS_DEMAND_ATTACH_FS
8227 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8228 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8229 VCreateReservation_r(hd->back);
8233 WriteVolumeHeader_r(&error, hd->back);
8234 /* Ignore errors; catch them later */
8236 #ifdef AFS_DEMAND_ATTACH_FS
8241 hd->back->header = NULL;
8242 #ifdef AFS_DEMAND_ATTACH_FS
8243 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8245 if (hd->diskstuff.inUse) {
8246 VChangeState_r(hd->back, back_save);
8247 VCancelReservation_r(hd->back);
8248 VChangeState_r(vp, vp_save);
8252 volume_hdr_LRU.stats.attached++;
8256 #ifdef AFS_DEMAND_ATTACH_FS
8257 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8260 volume_hdr_LRU.stats.free--;
8261 volume_hdr_LRU.stats.used++;
8263 IncUInt64(&VStats.hdr_gets);
8264 #ifdef AFS_DEMAND_ATTACH_FS
8265 IncUInt64(&vp->stats.hdr_gets);
8266 vp->stats.last_hdr_get = FT_ApproxTime();
8273 * make sure volume header is attached and contains valid cache data.
8275 * @param[out] ec outbound error code
8276 * @param[in] vp pointer to volume object
8278 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8280 * @post header cache entry attached, and loaded with valid data, or
8281 * *ec is nonzero, and the header is released back into the LRU.
8283 * @internal volume package internal use only.
8286 LoadVolumeHeader(Error * ec, Volume * vp)
8288 #ifdef AFS_DEMAND_ATTACH_FS
8289 VolState state_save;
8293 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8294 IncUInt64(&VStats.hdr_loads);
8295 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8298 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8299 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8301 IncUInt64(&vp->stats.hdr_loads);
8302 now = FT_ApproxTime();
8306 V_attachFlags(vp) |= VOL_HDR_LOADED;
8307 vp->stats.last_hdr_load = now;
8309 VChangeState_r(vp, state_save);
8311 #else /* AFS_DEMAND_ATTACH_FS */
8313 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8314 IncUInt64(&VStats.hdr_loads);
8316 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8317 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8320 #endif /* AFS_DEMAND_ATTACH_FS */
8322 /* maintain (nUsers==0) => header in LRU invariant */
8323 FreeVolumeHeader(vp);
8328 * release a header cache entry back into the LRU list.
8330 * @param[in] hd pointer to volume header cache object
8332 * @pre VOL_LOCK held.
8334 * @post header cache object appended onto end of LRU list.
8336 * @note only applicable to fileServer program type.
8338 * @note used to place a header cache entry back into the
8339 * LRU pool without invalidating it as a cache entry.
8341 * @internal volume package internal use only.
8344 ReleaseVolumeHeader(struct volHeader *hd)
8346 if (programType != fileServer)
8348 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8350 queue_Append(&volume_hdr_LRU, hd);
8351 #ifdef AFS_DEMAND_ATTACH_FS
8353 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8356 volume_hdr_LRU.stats.free++;
8357 volume_hdr_LRU.stats.used--;
8361 * free/invalidate a volume header cache entry.
8363 * @param[in] vp pointer to volume object
8365 * @pre VOL_LOCK is held.
8367 * @post For fileserver, header cache entry is returned to LRU, and it is
8368 * invalidated as a cache entry. For volume utilities, the header
8369 * cache entry is freed.
8371 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8372 * whenever it is necessary to invalidate the header cache entry.
8374 * @see ReleaseVolumeHeader
8376 * @internal volume package internal use only.
8379 FreeVolumeHeader(Volume * vp)
8381 struct volHeader *hd = vp->header;
8384 if (programType == fileServer) {
8385 ReleaseVolumeHeader(hd);
8390 #ifdef AFS_DEMAND_ATTACH_FS
8391 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8393 volume_hdr_LRU.stats.attached--;
8398 /***************************************************/
8399 /* Volume Hash Table routines */
8400 /***************************************************/
8403 * set size of volume object hash table.
8405 * @param[in] logsize log(2) of desired hash table size
8407 * @return operation status
8409 * @retval -1 failure
8411 * @pre MUST be called prior to VInitVolumePackage2
8413 * @post Volume Hash Table will have 2^logsize buckets
8416 VSetVolHashSize(int logsize)
8418 /* 64 to 268435456 hash buckets seems like a reasonable range */
8419 if ((logsize < 6 ) || (logsize > 28)) {
8424 VolumeHashTable.Size = opr_jhash_size(logsize);
8425 VolumeHashTable.Mask = opr_jhash_mask(logsize);
8427 /* we can't yet support runtime modification of this
8428 * parameter. we'll need a configuration rwlock to
8429 * make runtime modification feasible.... */
8436 * initialize dynamic data structures for volume hash table.
8438 * @post hash table is allocated, and fields are initialized.
8440 * @internal volume package internal use only.
8443 VInitVolumeHash(void)
8447 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8448 sizeof(VolumeHashChainHead));
8449 opr_Assert(VolumeHashTable.Table != NULL);
8451 for (i=0; i < VolumeHashTable.Size; i++) {
8452 queue_Init(&VolumeHashTable.Table[i]);
8453 #ifdef AFS_DEMAND_ATTACH_FS
8454 opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8455 #endif /* AFS_DEMAND_ATTACH_FS */
8460 * add a volume object to the hash table.
8462 * @param[in] vp pointer to volume object
8463 * @param[in] hashid hash of volume id
8465 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8468 * @post volume is added to hash chain.
8470 * @internal volume package internal use only.
8472 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8473 * asynchronous hash chain reordering to finish.
8476 AddVolumeToHashTable(Volume * vp, VolumeId hashid)
8478 VolumeHashChainHead * head;
8480 if (queue_IsOnQueue(vp))
8483 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8485 #ifdef AFS_DEMAND_ATTACH_FS
8486 /* wait for the hash chain to become available */
8489 V_attachFlags(vp) |= VOL_IN_HASH;
8490 vp->chainCacheCheck = ++head->cacheCheck;
8491 #endif /* AFS_DEMAND_ATTACH_FS */
8494 vp->hashid = hashid;
8495 queue_Append(head, vp);
8499 * delete a volume object from the hash table.
8501 * @param[in] vp pointer to volume object
8503 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8506 * @post volume is removed from hash chain.
8508 * @internal volume package internal use only.
8510 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8511 * asynchronous hash chain reordering to finish.
8514 DeleteVolumeFromHashTable(Volume * vp)
8516 VolumeHashChainHead * head;
8518 if (!queue_IsOnQueue(vp))
8521 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8523 #ifdef AFS_DEMAND_ATTACH_FS
8524 /* wait for the hash chain to become available */
8527 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8529 #endif /* AFS_DEMAND_ATTACH_FS */
8533 /* do NOT reset hashid to zero, as the online
8534 * salvager package may need to know the volume id
8535 * after the volume is removed from the hash */
8539 * lookup a volume object in the hash table given a volume id.
8541 * @param[out] ec error code return
8542 * @param[in] volumeId volume id
8543 * @param[in] hint volume object which we believe could be the correct
8546 * @return volume object pointer
8547 * @retval NULL no such volume id is registered with the hash table.
8549 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8552 * @post volume object with the given id is returned. volume object and
8553 * hash chain access statistics are updated. hash chain may have
8556 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8557 * asynchronous hash chain reordering operation to finish, or
8558 * in order for us to perform an asynchronous chain reordering.
8560 * @note Hash chain reorderings occur when the access count for the
8561 * volume object being looked up exceeds the sum of the previous
8562 * node's (the node ahead of it in the hash chain linked list)
8563 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8565 * @note For DAFS, the hint parameter allows us to short-circuit if the
8566 * cacheCheck fields match between the hash chain head and the
8567 * hint volume object.
8570 VLookupVolume_r(Error * ec, VolumeId volumeId, Volume * hint)
8574 #ifdef AFS_DEMAND_ATTACH_FS
8577 VolumeHashChainHead * head;
8580 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8582 #ifdef AFS_DEMAND_ATTACH_FS
8583 /* wait for the hash chain to become available */
8586 /* check to see if we can short circuit without walking the hash chain */
8587 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8588 IncUInt64(&hint->stats.hash_short_circuits);
8591 #endif /* AFS_DEMAND_ATTACH_FS */
8593 /* someday we need to either do per-chain locks, RWlocks,
8594 * or both for volhash access.
8595 * (and move to a data structure with better cache locality) */
8597 /* search the chain for this volume id */
8598 for(queue_Scan(head, vp, np, Volume)) {
8600 if (vp->hashid == volumeId) {
8605 if (queue_IsEnd(head, vp)) {
8609 #ifdef AFS_DEMAND_ATTACH_FS
8610 /* update hash chain statistics */
8613 FillInt64(lks, 0, looks);
8614 AddUInt64(head->looks, lks, &head->looks);
8615 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8616 IncUInt64(&head->gets);
8621 IncUInt64(&vp->stats.hash_lookups);
8623 /* for demand attach fileserver, we permit occasional hash chain reordering
8624 * so that frequently looked up volumes move towards the head of the chain */
8625 pp = queue_Prev(vp, Volume);
8626 if (!queue_IsEnd(head, pp)) {
8627 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8628 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8629 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8630 VReorderHash_r(head, pp, vp);
8634 /* update the short-circuit cache check */
8635 vp->chainCacheCheck = head->cacheCheck;
8637 #endif /* AFS_DEMAND_ATTACH_FS */
8642 #ifdef AFS_DEMAND_ATTACH_FS
8643 /* perform volume hash chain reordering.
8645 * advance a subchain beginning at vp ahead of
8646 * the adjacent subchain ending at pp */
8648 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8650 Volume *tp, *np, *lp;
8651 afs_uint64 move_thresh;
8653 /* this should never be called if the chain is already busy, so
8654 * no need to wait for other exclusive chain ops to finish */
8656 /* this is a rather heavy set of operations,
8657 * so let's set the chain busy flag and drop
8659 VHashBeginExclusive_r(head);
8662 /* scan forward in the chain from vp looking for the last element
8663 * in the chain we want to advance */
8664 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8665 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8666 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8667 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8671 lp = queue_Prev(tp, Volume);
8673 /* scan backwards from pp to determine where to splice and
8674 * insert the subchain we're advancing */
8675 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8676 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8680 tp = queue_Next(tp, Volume);
8682 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8683 queue_MoveChainBefore(tp,vp,lp);
8686 IncUInt64(&VStats.hash_reorders);
8688 IncUInt64(&head->reorders);
8690 /* wake up any threads waiting for the hash chain */
8691 VHashEndExclusive_r(head);
8695 /* demand-attach fs volume hash
8696 * asynchronous exclusive operations */
8699 * begin an asynchronous exclusive operation on a volume hash chain.
8701 * @param[in] head pointer to volume hash chain head object
8703 * @pre VOL_LOCK held. hash chain is quiescent.
8705 * @post hash chain marked busy.
8707 * @note this interface is used in conjunction with VHashEndExclusive_r and
8708 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8709 * volume hash chain. Its main use case is hash chain reordering, which
8710 * has the potential to be a highly latent operation.
8712 * @see VHashEndExclusive_r
8717 * @internal volume package internal use only.
8720 VHashBeginExclusive_r(VolumeHashChainHead * head)
8722 opr_Assert(head->busy == 0);
8727 * relinquish exclusive ownership of a volume hash chain.
8729 * @param[in] head pointer to volume hash chain head object
8731 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8733 * @post hash chain is marked quiescent. threads awaiting use of
8734 * chain are awakened.
8736 * @see VHashBeginExclusive_r
8741 * @internal volume package internal use only.
8744 VHashEndExclusive_r(VolumeHashChainHead * head)
8746 opr_Assert(head->busy);
8748 opr_cv_broadcast(&head->chain_busy_cv);
8752 * wait for all asynchronous operations on a hash chain to complete.
8754 * @param[in] head pointer to volume hash chain head object
8756 * @pre VOL_LOCK held.
8758 * @post hash chain object is quiescent.
8760 * @see VHashBeginExclusive_r
8761 * @see VHashEndExclusive_r
8765 * @note This interface should be called before any attempt to
8766 * traverse the hash chain. It is permissible for a thread
8767 * to gain exclusive access to the chain, and then perform
8768 * latent operations on the chain asynchronously wrt the
8771 * @warning if waiting is necessary, VOL_LOCK is dropped
8773 * @internal volume package internal use only.
8776 VHashWait_r(VolumeHashChainHead * head)
8778 while (head->busy) {
8779 VOL_CV_WAIT(&head->chain_busy_cv);
8782 #endif /* AFS_DEMAND_ATTACH_FS */
8785 /***************************************************/
8786 /* Volume by Partition List routines */
8787 /***************************************************/
8790 * demand attach fileserver adds a
8791 * linked list of volumes to each
8792 * partition object, thus allowing
8793 * for quick enumeration of all
8794 * volumes on a partition
8797 #ifdef AFS_DEMAND_ATTACH_FS
8799 * add a volume to its disk partition VByPList.
8801 * @param[in] vp pointer to volume object
8803 * @pre either the disk partition VByPList is owned exclusively
8804 * by the calling thread, or the list is quiescent and
8807 * @post volume is added to disk partition VByPList
8811 * @warning it is the caller's responsibility to ensure list
8814 * @see VVByPListWait_r
8815 * @see VVByPListBeginExclusive_r
8816 * @see VVByPListEndExclusive_r
8818 * @internal volume package internal use only.
8821 AddVolumeToVByPList_r(Volume * vp)
8823 if (queue_IsNotOnQueue(&vp->vol_list)) {
8824 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8825 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8826 vp->partition->vol_list.len++;
8831 * delete a volume from its disk partition VByPList.
8833 * @param[in] vp pointer to volume object
8835 * @pre either the disk partition VByPList is owned exclusively
8836 * by the calling thread, or the list is quiescent and
8839 * @post volume is removed from the disk partition VByPList
8843 * @warning it is the caller's responsibility to ensure list
8846 * @see VVByPListWait_r
8847 * @see VVByPListBeginExclusive_r
8848 * @see VVByPListEndExclusive_r
8850 * @internal volume package internal use only.
8853 DeleteVolumeFromVByPList_r(Volume * vp)
8855 if (queue_IsOnQueue(&vp->vol_list)) {
8856 queue_Remove(&vp->vol_list);
8857 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8858 vp->partition->vol_list.len--;
8863 * begin an asynchronous exclusive operation on a VByPList.
8865 * @param[in] dp pointer to disk partition object
8867 * @pre VOL_LOCK held. VByPList is quiescent.
8869 * @post VByPList marked busy.
8871 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8872 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8875 * @see VVByPListEndExclusive_r
8876 * @see VVByPListWait_r
8880 * @internal volume package internal use only.
8882 /* take exclusive control over the list */
8884 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8886 opr_Assert(dp->vol_list.busy == 0);
8887 dp->vol_list.busy = 1;
8891 * relinquish exclusive ownership of a VByPList.
8893 * @param[in] dp pointer to disk partition object
8895 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8897 * @post VByPList is marked quiescent. threads awaiting use of
8898 * the list are awakened.
8900 * @see VVByPListBeginExclusive_r
8901 * @see VVByPListWait_r
8905 * @internal volume package internal use only.
8908 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8910 opr_Assert(dp->vol_list.busy);
8911 dp->vol_list.busy = 0;
8912 opr_cv_broadcast(&dp->vol_list.cv);
8916 * wait for all asynchronous operations on a VByPList to complete.
8918 * @param[in] dp pointer to disk partition object
8920 * @pre VOL_LOCK is held.
8922 * @post disk partition's VByP list is quiescent
8926 * @note This interface should be called before any attempt to
8927 * traverse the VByPList. It is permissible for a thread
8928 * to gain exclusive access to the list, and then perform
8929 * latent operations on the list asynchronously wrt the
8932 * @warning if waiting is necessary, VOL_LOCK is dropped
8934 * @see VVByPListEndExclusive_r
8935 * @see VVByPListBeginExclusive_r
8937 * @internal volume package internal use only.
8940 VVByPListWait_r(struct DiskPartition64 * dp)
8942 while (dp->vol_list.busy) {
8943 VOL_CV_WAIT(&dp->vol_list.cv);
8946 #endif /* AFS_DEMAND_ATTACH_FS */
8948 /***************************************************/
8949 /* Volume Cache Statistics routines */
8950 /***************************************************/
8953 VPrintCacheStats_r(void)
8955 struct VnodeClassInfo *vcp;
8956 vcp = &VnodeClassInfo[vLarge];
8957 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);
8958 vcp = &VnodeClassInfo[vSmall];
8959 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);
8960 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8961 "%"AFS_INT64_FMT" replacements\n",
8962 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8966 VPrintCacheStats(void)
8969 VPrintCacheStats_r();
8973 #ifdef AFS_DEMAND_ATTACH_FS
8975 UInt64ToDouble(afs_uint64 * x)
8977 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8979 SplitInt64(*x, h, l);
8980 return (((double)h) * c32) + ((double) l);
8984 DoubleToPrintable(double x, char * buf, int len)
8986 static double billion = 1000000000.0;
8989 y[0] = (afs_uint32) (x / (billion * billion));
8990 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8991 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8994 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8996 snprintf(buf, len, "%d%09d", y[1], y[2]);
8998 snprintf(buf, len, "%d", y[2]);
9004 struct VLRUExtStatsEntry {
9008 struct VLRUExtStats {
9014 } queue_info[VLRU_QUEUE_INVALID];
9015 struct VLRUExtStatsEntry * vec;
9019 * add a 256-entry fudge factor onto the vector in case state changes
9020 * out from under us.
9022 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
9025 * collect extended statistics for the VLRU subsystem.
9027 * @param[out] stats pointer to stats structure to be populated
9028 * @param[in] nvols number of volumes currently known to exist
9030 * @pre VOL_LOCK held
9032 * @post stats->vec allocated and populated
9034 * @return operation status
9039 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
9041 afs_uint32 cur, idx, len;
9042 struct rx_queue * qp, * nqp;
9044 struct VLRUExtStatsEntry * vec;
9046 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
9047 vec = stats->vec = calloc(len,
9048 sizeof(struct VLRUExtStatsEntry));
9054 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9055 VLRU_Wait_r(&volume_LRU.q[idx]);
9056 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
9059 stats->queue_info[idx].start = cur;
9061 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
9063 /* out of space in vec */
9066 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
9067 vec[cur].volid = vp->hashid;
9071 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9074 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9082 #define ENUMTOSTRING(en) #en
9083 #define ENUMCASE(en) \
9084 case en: return ENUMTOSTRING(en)
9087 vlru_idx_to_string(int idx)
9090 ENUMCASE(VLRU_QUEUE_NEW);
9091 ENUMCASE(VLRU_QUEUE_MID);
9092 ENUMCASE(VLRU_QUEUE_OLD);
9093 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9094 ENUMCASE(VLRU_QUEUE_HELD);
9095 ENUMCASE(VLRU_QUEUE_INVALID);
9097 return "**UNKNOWN**";
9102 VPrintExtendedCacheStats_r(int flags)
9105 afs_uint32 vol_sum = 0;
9112 struct stats looks, gets, reorders, len;
9113 struct stats ch_looks, ch_gets, ch_reorders;
9115 VolumeHashChainHead *head;
9117 struct VLRUExtStats vlru_stats;
9119 /* zero out stats */
9120 memset(&looks, 0, sizeof(struct stats));
9121 memset(&gets, 0, sizeof(struct stats));
9122 memset(&reorders, 0, sizeof(struct stats));
9123 memset(&len, 0, sizeof(struct stats));
9124 memset(&ch_looks, 0, sizeof(struct stats));
9125 memset(&ch_gets, 0, sizeof(struct stats));
9126 memset(&ch_reorders, 0, sizeof(struct stats));
9128 for (i = 0; i < VolumeHashTable.Size; i++) {
9129 head = &VolumeHashTable.Table[i];
9132 VHashBeginExclusive_r(head);
9135 ch_looks.sum = UInt64ToDouble(&head->looks);
9136 ch_gets.sum = UInt64ToDouble(&head->gets);
9137 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9139 /* update global statistics */
9141 looks.sum += ch_looks.sum;
9142 gets.sum += ch_gets.sum;
9143 reorders.sum += ch_reorders.sum;
9144 len.sum += (double)head->len;
9145 vol_sum += head->len;
9148 len.min = (double) head->len;
9149 len.max = (double) head->len;
9150 looks.min = ch_looks.sum;
9151 looks.max = ch_looks.sum;
9152 gets.min = ch_gets.sum;
9153 gets.max = ch_gets.sum;
9154 reorders.min = ch_reorders.sum;
9155 reorders.max = ch_reorders.sum;
9157 if (((double)head->len) < len.min)
9158 len.min = (double) head->len;
9159 if (((double)head->len) > len.max)
9160 len.max = (double) head->len;
9161 if (ch_looks.sum < looks.min)
9162 looks.min = ch_looks.sum;
9163 else if (ch_looks.sum > looks.max)
9164 looks.max = ch_looks.sum;
9165 if (ch_gets.sum < gets.min)
9166 gets.min = ch_gets.sum;
9167 else if (ch_gets.sum > gets.max)
9168 gets.max = ch_gets.sum;
9169 if (ch_reorders.sum < reorders.min)
9170 reorders.min = ch_reorders.sum;
9171 else if (ch_reorders.sum > reorders.max)
9172 reorders.max = ch_reorders.sum;
9176 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9177 /* compute detailed per-chain stats */
9178 struct stats hdr_loads, hdr_gets;
9179 double v_looks, v_loads, v_gets;
9181 /* initialize stats with data from first element in chain */
9182 vp = queue_First(head, Volume);
9183 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9184 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9185 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9186 ch_gets.min = ch_gets.max = v_looks;
9187 hdr_loads.min = hdr_loads.max = v_loads;
9188 hdr_gets.min = hdr_gets.max = v_gets;
9189 hdr_loads.sum = hdr_gets.sum = 0;
9191 vp = queue_Next(vp, Volume);
9193 /* pull in stats from remaining elements in chain */
9194 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9195 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9196 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9197 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9199 hdr_loads.sum += v_loads;
9200 hdr_gets.sum += v_gets;
9202 if (v_looks < ch_gets.min)
9203 ch_gets.min = v_looks;
9204 else if (v_looks > ch_gets.max)
9205 ch_gets.max = v_looks;
9207 if (v_loads < hdr_loads.min)
9208 hdr_loads.min = v_loads;
9209 else if (v_loads > hdr_loads.max)
9210 hdr_loads.max = v_loads;
9212 if (v_gets < hdr_gets.min)
9213 hdr_gets.min = v_gets;
9214 else if (v_gets > hdr_gets.max)
9215 hdr_gets.max = v_gets;
9218 /* compute per-chain averages */
9219 ch_gets.avg = ch_gets.sum / ((double)head->len);
9220 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9221 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9223 /* dump per-chain stats */
9224 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9226 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9227 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9228 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9229 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9230 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9231 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9232 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9233 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9234 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9235 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9236 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9237 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9238 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9239 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9240 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9241 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9242 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9243 } else if (flags & VOL_STATS_PER_CHAIN) {
9244 /* dump simple per-chain stats */
9245 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9247 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9248 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9249 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9253 VHashEndExclusive_r(head);
9258 /* compute global averages */
9259 len.avg = len.sum / ((double)VolumeHashTable.Size);
9260 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9261 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9262 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9264 /* dump global stats */
9265 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9266 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9267 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9268 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9269 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9270 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9271 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9272 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9273 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9274 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9275 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9276 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9277 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9278 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9279 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9280 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9281 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9282 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9283 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9284 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9285 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9287 /* print extended disk related statistics */
9289 struct DiskPartition64 * diskP;
9290 afs_uint32 vol_count[VOLMAXPARTS+1];
9291 byte part_exists[VOLMAXPARTS+1];
9295 memset(vol_count, 0, sizeof(vol_count));
9296 memset(part_exists, 0, sizeof(part_exists));
9300 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9302 vol_count[id] = diskP->vol_list.len;
9303 part_exists[id] = 1;
9307 for (i = 0; i <= VOLMAXPARTS; i++) {
9308 if (part_exists[i]) {
9309 /* XXX while this is currently safe, it is a violation
9310 * of the VGetPartitionById_r interface contract. */
9311 diskP = VGetPartitionById_r(i, 0);
9313 Log("Partition %s has %d online volumes\n",
9314 VPartitionPath(diskP), diskP->vol_list.len);
9321 /* print extended VLRU statistics */
9322 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9323 afs_uint32 idx, cur, lpos;
9328 Log("VLRU State Dump:\n\n");
9330 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9331 Log("\t%s:\n", vlru_idx_to_string(idx));
9334 for (cur = vlru_stats.queue_info[idx].start;
9335 cur < vlru_stats.queue_info[idx].len;
9337 line[lpos++] = vlru_stats.vec[cur].volid;
9339 Log("\t\t%u, %u, %u, %u, %u,\n",
9340 line[0], line[1], line[2], line[3], line[4]);
9349 Log("\t\t%u, %u, %u, %u, %u\n",
9350 line[0], line[1], line[2], line[3], line[4]);
9355 free(vlru_stats.vec);
9362 VPrintExtendedCacheStats(int flags)
9365 VPrintExtendedCacheStats_r(flags);
9368 #endif /* AFS_DEMAND_ATTACH_FS */
9371 VCanScheduleSalvage(void)
9373 return vol_opts.canScheduleSalvage;
9379 return vol_opts.canUseFSSYNC;
9383 VCanUseSALVSYNC(void)
9385 return vol_opts.canUseSALVSYNC;
9389 VCanUnsafeAttach(void)
9391 return vol_opts.unsafe_attach;