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)
48 #ifdef AFS_VFSINCL_ENV
51 #include <sys/fs/ufs_fs.h>
53 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
54 #include <ufs/ufs/dinode.h>
55 #include <ufs/ffs/fs.h>
60 #else /* AFS_VFSINCL_ENV */
61 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
64 #endif /* AFS_VFSINCL_ENV */
65 #endif /* AFS_SGI_ENV */
66 #endif /* !AFS_NT40_ENV */
74 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
76 #include <sys/mnttab.h>
77 #include <sys/mntent.h>
83 #if defined(AFS_SGI_ENV)
86 #ifndef AFS_LINUX20_ENV
87 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
90 #endif /* AFS_SGI_ENV */
92 #endif /* AFS_HPUX_ENV */
96 #include <afs/errors.h>
99 #include <afs/afssyscalls.h>
101 #include <afs/afsutil.h>
102 #include "daemon_com.h"
104 #include "salvsync.h"
107 #include "partition.h"
108 #include "volume_inline.h"
113 #ifdef AFS_PTHREAD_ENV
114 pthread_mutex_t vol_glock_mutex;
115 pthread_mutex_t vol_trans_mutex;
116 pthread_cond_t vol_put_volume_cond;
117 pthread_cond_t vol_sleep_cond;
118 pthread_cond_t vol_init_attach_cond;
119 pthread_cond_t vol_vinit_cond;
120 int vol_attach_threads = 1;
121 #endif /* AFS_PTHREAD_ENV */
123 #ifdef AFS_DEMAND_ATTACH_FS
124 pthread_mutex_t vol_salvsync_mutex;
127 * Set this to 1 to disallow SALVSYNC communication in all threads; used
128 * during shutdown, since the salvageserver may have gone away.
130 static volatile sig_atomic_t vol_disallow_salvsync = 0;
131 #endif /* AFS_DEMAND_ATTACH_FS */
134 * has VShutdown_r been called / is VShutdown_r running?
136 static int vol_shutting_down = 0;
138 /* Forward declarations */
139 static Volume *attach2(Error * ec, VolumeId volumeId, char *path,
140 struct DiskPartition64 *partp, Volume * vp,
141 int isbusy, int mode, int *acheckedOut);
142 static void ReallyFreeVolume(Volume * vp);
143 #ifdef AFS_DEMAND_ATTACH_FS
144 static void FreeVolume(Volume * vp);
145 #else /* !AFS_DEMAND_ATTACH_FS */
146 #define FreeVolume(vp) ReallyFreeVolume(vp)
147 static void VScanUpdateList(void);
148 #endif /* !AFS_DEMAND_ATTACH_FS */
149 static void VInitVolumeHeaderCache(afs_uint32 howMany);
150 static int GetVolumeHeader(Volume * vp);
151 static void ReleaseVolumeHeader(struct volHeader *hd);
152 static void FreeVolumeHeader(Volume * vp);
153 static void AddVolumeToHashTable(Volume * vp, VolumeId hashid);
154 static void DeleteVolumeFromHashTable(Volume * vp);
155 static int VHold_r(Volume * vp);
156 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
157 static void VReleaseVolumeHandles_r(Volume * vp);
158 static void VCloseVolumeHandles_r(Volume * vp);
159 static void LoadVolumeHeader(Error * ec, Volume * vp);
160 static int VCheckOffline(Volume * vp);
161 static int VCheckDetach(Volume * vp);
162 static Volume * GetVolume(Error * ec, Error * client_ec, VolumeId volumeId,
163 Volume * hint, const struct timespec *ts);
165 ProgramType programType; /* The type of program using the package */
166 static VolumePackageOptions vol_opts;
168 /* extended volume package statistics */
171 #ifdef VOL_LOCK_DEBUG
172 pthread_t vol_glock_holder = 0;
176 /* this parameter needs to be tunable at runtime.
177 * 128 was really inadequate for largish servers -- at 16384 volumes this
178 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
179 * talk about bad spatial locality...
181 * an AVL or splay tree might work a lot better, but we'll just increase
182 * the default hash table size for now
184 #define DEFAULT_VOLUME_HASH_BITS 10
185 #define DEFAULT_VOLUME_HASH_SIZE opr_jhash_size(DEFAULT_VOLUME_HASH_BITS)
186 #define DEFAULT_VOLUME_HASH_MASK opr_jhash_mask(DEFAULT_VOLUME_HASH_BITS)
187 #define VOLUME_HASH(volumeId) \
188 (opr_jhash_int(volumeId, 0) & VolumeHashTable.Mask)
191 * turn volume hash chains into partially ordered lists.
192 * when the threshold is exceeded between two adjacent elements,
193 * perform a chain rebalancing operation.
195 * keep the threshold high in order to keep cache line invalidates
196 * low "enough" on SMPs
198 #define VOLUME_HASH_REORDER_THRESHOLD 200
201 * when possible, don't just reorder single elements, but reorder
202 * entire chains of elements at once. a chain of elements that
203 * exceed the element previous to the pivot by at least CHAIN_THRESH
204 * accesses are moved in front of the chain whose elements have at
205 * least CHAIN_THRESH less accesses than the pivot element
207 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
210 * The per volume uniquifier is bumped by 200 and and written to disk
211 * every 200 file creates.
213 #define VOLUME_UPDATE_UNIQUIFIER_BUMP 200
215 #include "rx/rx_queue.h"
218 VolumeHashTable_t VolumeHashTable = {
219 DEFAULT_VOLUME_HASH_SIZE,
220 DEFAULT_VOLUME_HASH_MASK,
225 static void VInitVolumeHash(void);
228 #ifdef AFS_PTHREAD_ENV
230 * disk partition queue element
232 typedef struct diskpartition_queue_t {
233 struct rx_queue queue; /**< queue header */
234 struct DiskPartition64 *diskP; /**< disk partition table entry */
235 } diskpartition_queue_t;
237 #ifndef AFS_DEMAND_ATTACH_FS
239 typedef struct vinitvolumepackage_thread_t {
240 struct rx_queue queue;
241 pthread_cond_t thread_done_cv;
242 int n_threads_complete;
243 } vinitvolumepackage_thread_t;
244 static void * VInitVolumePackageThread(void * args);
246 #else /* !AFS_DEMAND_ATTTACH_FS */
247 #define VINIT_BATCH_MAX_SIZE 512
250 * disk partition work queue
252 struct partition_queue {
253 struct rx_queue head; /**< diskpartition_queue_t queue */
254 pthread_mutex_t mutex;
259 * volumes parameters for preattach
261 struct volume_init_batch {
262 struct rx_queue queue; /**< queue header */
263 int thread; /**< posting worker thread */
264 int last; /**< indicates thread is done */
265 int size; /**< number of volume ids in batch */
266 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
270 * volume parameters work queue
272 struct volume_init_queue {
273 struct rx_queue head; /**< volume_init_batch queue */
274 pthread_mutex_t mutex;
279 * volume init worker thread parameters
281 struct vinitvolumepackage_thread_param {
282 int nthreads; /**< total number of worker threads */
283 int thread; /**< thread number for this worker thread */
284 struct partition_queue *pq; /**< queue partitions to scan */
285 struct volume_init_queue *vq; /**< queue of volume to preattach */
288 static void *VInitVolumePackageThread(void *args);
289 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
290 static VolumeId VInitNextVolumeId(DIR *dirp);
291 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
293 #endif /* !AFS_DEMAND_ATTACH_FS */
294 #endif /* AFS_PTHREAD_ENV */
296 #ifndef AFS_DEMAND_ATTACH_FS
297 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
298 int * nAttached, int * nUnattached);
299 #endif /* AFS_DEMAND_ATTACH_FS */
302 #ifdef AFS_DEMAND_ATTACH_FS
303 /* demand attach fileserver extensions */
306 * in the future we will support serialization of VLRU state into the fs_state
309 * these structures are the beginning of that effort
311 struct VLRU_DiskHeader {
312 struct versionStamp stamp; /* magic and structure version number */
313 afs_uint32 mtime; /* time of dump to disk */
314 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
317 struct VLRU_DiskEntry {
318 VolumeId vid; /* volume ID */
319 afs_uint32 idx; /* generation */
320 afs_uint32 last_get; /* timestamp of last get */
323 struct VLRU_StartupQueue {
324 struct VLRU_DiskEntry * entry;
329 typedef struct vshutdown_thread_t {
331 pthread_mutex_t lock;
333 pthread_cond_t master_cv;
335 int n_threads_complete;
337 int schedule_version;
340 byte n_parts_done_pass;
341 byte part_thread_target[VOLMAXPARTS+1];
342 byte part_done_pass[VOLMAXPARTS+1];
343 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
344 int stats[4][VOLMAXPARTS+1];
345 } vshutdown_thread_t;
346 static void * VShutdownThread(void * args);
349 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
350 static int VCheckFree(Volume * vp);
353 static void AddVolumeToVByPList_r(Volume * vp);
354 static void DeleteVolumeFromVByPList_r(Volume * vp);
355 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
356 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
357 static void VVByPListWait_r(struct DiskPartition64 * dp);
359 /* online salvager */
361 VCHECK_SALVAGE_OK = 0, /**< no pending salvage */
362 VCHECK_SALVAGE_SCHEDULED = 1, /**< salvage has been scheduled */
363 VCHECK_SALVAGE_ASYNC = 2, /**< salvage being scheduled */
364 VCHECK_SALVAGE_DENIED = 3, /**< salvage not scheduled; denied */
365 VCHECK_SALVAGE_FAIL = 4 /**< salvage not scheduled; failed */
367 static int VCheckSalvage(Volume * vp);
368 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
369 static int VScheduleSalvage_r(Volume * vp);
372 /* Volume hash table */
373 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
374 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
375 static void VHashEndExclusive_r(VolumeHashChainHead * head);
376 static void VHashWait_r(VolumeHashChainHead * head);
379 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
380 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
381 struct rx_queue ** idx);
382 static void ShutdownController(vshutdown_thread_t * params);
383 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
386 static void VLRU_ComputeConstants(void);
387 static void VInitVLRU(void);
388 static void VLRU_Init_Node_r(Volume * vp);
389 static void VLRU_Add_r(Volume * vp);
390 static void VLRU_Delete_r(Volume * vp);
391 static void VLRU_UpdateAccess_r(Volume * vp);
392 static void * VLRU_ScannerThread(void * args);
393 static void VLRU_Scan_r(int idx);
394 static void VLRU_Promote_r(int idx);
395 static void VLRU_Demote_r(int idx);
396 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
399 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
400 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
401 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
404 pthread_key_t VThread_key;
405 VThreadOptions_t VThread_defaults = {
406 0 /**< allow salvsync */
408 #endif /* AFS_DEMAND_ATTACH_FS */
411 struct Lock vol_listLock; /* Lock obtained when listing volumes:
412 * prevents a volume from being missed
413 * if the volume is attached during a
417 /* Common message used when the volume goes off line */
418 char *VSalvageMessage =
419 "Files in this volume are currently unavailable; call operations";
421 int VInit; /* 0 - uninitialized,
422 * 1 - initialized but not all volumes have been attached,
423 * 2 - initialized and all volumes have been attached,
424 * 3 - initialized, all volumes have been attached, and
425 * VConnectFS() has completed. */
427 static int vinit_attach_abort = 0;
429 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
430 * used to stamp volume headers and in-core
431 * vnodes. When the volume goes on-line the
432 * vnode will be invalidated
433 * access only with VOL_LOCK held */
438 /***************************************************/
439 /* Startup routines */
440 /***************************************************/
442 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
443 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
444 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
448 * assign default values to a VolumePackageOptions struct.
450 * Always call this on a VolumePackageOptions struct first, then set any
451 * specific options you want, then call VInitVolumePackage2.
453 * @param[in] pt caller's program type
454 * @param[out] opts volume package options
457 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
459 memset(opts, 0, sizeof(*opts));
461 opts->nLargeVnodes = opts->nSmallVnodes = 5;
463 opts->offline_timeout = -1;
464 opts->offline_shutdown_timeout = -1;
465 opts->usage_threshold = 128;
466 opts->usage_rate_limit = 5;
469 opts->unsafe_attach = 1;
474 opts->canScheduleSalvage = 1;
475 opts->canUseSALVSYNC = 1;
479 opts->canUseFSSYNC = 1;
483 opts->nLargeVnodes = 0;
484 opts->nSmallVnodes = 0;
486 opts->canScheduleSalvage = 1;
487 opts->canUseFSSYNC = 1;
497 * Set VInit to a certain value, and signal waiters.
499 * @param[in] value the value to set VInit to
504 VSetVInit_r(int value)
507 opr_cv_broadcast(&vol_vinit_cond);
511 VLogOfflineTimeout(const char *type, afs_int32 timeout)
517 Log("VInitVolumePackage: Interrupting clients accessing %s "
518 "immediately\n", type);
520 Log("VInitVolumePackage: Interrupting clients accessing %s "
521 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
526 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
528 int errors = 0; /* Number of errors while finding vice partitions. */
533 #ifndef AFS_PTHREAD_ENV
534 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
535 Log("VInitVolumePackage: offline_timeout and/or "
536 "offline_shutdown_timeout was specified, but the volume package "
537 "does not support these for LWP builds\n");
541 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
542 VLogOfflineTimeout("volumes going offline during shutdown",
543 opts->offline_shutdown_timeout);
545 memset(&VStats, 0, sizeof(VStats));
546 VStats.hdr_cache_size = 200;
548 VInitPartitionPackage();
550 #ifdef AFS_DEMAND_ATTACH_FS
551 if (programType == fileServer) {
554 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
556 opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
559 opr_mutex_init(&vol_glock_mutex);
560 opr_mutex_init(&vol_trans_mutex);
561 opr_cv_init(&vol_put_volume_cond);
562 opr_cv_init(&vol_sleep_cond);
563 opr_cv_init(&vol_init_attach_cond);
564 opr_cv_init(&vol_vinit_cond);
565 #ifndef AFS_PTHREAD_ENV
567 #endif /* AFS_PTHREAD_ENV */
568 Lock_Init(&vol_listLock);
570 srandom(time(0)); /* For VGetVolumeInfo */
572 #ifdef AFS_DEMAND_ATTACH_FS
573 opr_mutex_init(&vol_salvsync_mutex);
574 #endif /* AFS_DEMAND_ATTACH_FS */
576 /* Ok, we have done enough initialization that fileserver can
577 * start accepting calls, even though the volumes may not be
578 * available just yet.
582 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
583 if (programType == salvageServer) {
586 #endif /* AFS_DEMAND_ATTACH_FS */
587 #ifdef FSSYNC_BUILD_SERVER
588 if (programType == fileServer) {
592 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
593 if (VCanUseSALVSYNC()) {
594 /* establish a connection to the salvager at this point */
595 opr_Verify(VConnectSALV() != 0);
597 #endif /* AFS_DEMAND_ATTACH_FS */
599 if (opts->volcache > VStats.hdr_cache_size)
600 VStats.hdr_cache_size = opts->volcache;
601 VInitVolumeHeaderCache(VStats.hdr_cache_size);
603 VInitVnodes(vLarge, opts->nLargeVnodes);
604 VInitVnodes(vSmall, opts->nSmallVnodes);
607 errors = VAttachPartitions();
611 if (programType != fileServer) {
612 errors = VInitAttachVolumes(programType);
618 #ifdef FSSYNC_BUILD_CLIENT
619 if (VCanUseFSSYNC()) {
621 #ifdef AFS_DEMAND_ATTACH_FS
622 if (programType == salvageServer) {
623 Log("Unable to connect to file server; aborted\n");
626 #endif /* AFS_DEMAND_ATTACH_FS */
627 Log("Unable to connect to file server; will retry at need\n");
630 #endif /* FSSYNC_BUILD_CLIENT */
635 #if !defined(AFS_PTHREAD_ENV)
637 * Attach volumes in vice partitions
639 * @param[in] pt calling program type
642 * @note This is the original, non-threaded version of attach parititions.
644 * @post VInit state is 2
647 VInitAttachVolumes(ProgramType pt)
649 opr_Assert(VInit==1);
650 if (pt == fileServer) {
651 struct DiskPartition64 *diskP;
652 /* Attach all the volumes in this partition */
653 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
654 int nAttached = 0, nUnattached = 0;
655 opr_Verify(VAttachVolumesByPartition(diskP,
656 &nAttached, &nUnattached)
661 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
662 LWP_NoYieldSignal(VInitAttachVolumes);
666 #endif /* !AFS_PTHREAD_ENV */
668 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
670 * Attach volumes in vice partitions
672 * @param[in] pt calling program type
675 * @note Threaded version of attach parititions.
677 * @post VInit state is 2
680 VInitAttachVolumes(ProgramType pt)
682 opr_Assert(VInit==1);
683 if (pt == fileServer) {
684 struct DiskPartition64 *diskP;
685 struct vinitvolumepackage_thread_t params;
686 struct diskpartition_queue_t * dpq;
687 int i, threads, parts;
689 pthread_attr_t attrs;
691 opr_cv_init(¶ms.thread_done_cv);
693 params.n_threads_complete = 0;
695 /* create partition work queue */
696 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
697 dpq = malloc(sizeof(struct diskpartition_queue_t));
698 opr_Assert(dpq != NULL);
700 queue_Append(¶ms,dpq);
703 threads = min(parts, vol_attach_threads);
706 /* spawn off a bunch of initialization threads */
707 opr_Verify(pthread_attr_init(&attrs) == 0);
708 opr_Verify(pthread_attr_setdetachstate(&attrs,
709 PTHREAD_CREATE_DETACHED)
712 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
713 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
717 for (i=0; i < threads; i++) {
720 opr_Verify(pthread_create(&tid, &attrs,
721 &VInitVolumePackageThread,
723 AFS_SIGSET_RESTORE();
726 while(params.n_threads_complete < threads) {
727 VOL_CV_WAIT(¶ms.thread_done_cv);
731 opr_Verify(pthread_attr_destroy(&attrs) == 0);
733 /* if we're only going to run one init thread, don't bother creating
735 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
736 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
739 VInitVolumePackageThread(¶ms);
742 opr_cv_destroy(¶ms.thread_done_cv);
745 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
746 opr_cv_broadcast(&vol_init_attach_cond);
752 VInitVolumePackageThread(void * args) {
754 struct DiskPartition64 *diskP;
755 struct vinitvolumepackage_thread_t * params;
756 struct diskpartition_queue_t * dpq;
758 params = (vinitvolumepackage_thread_t *) args;
762 /* Attach all the volumes in this partition */
763 while (queue_IsNotEmpty(params)) {
764 int nAttached = 0, nUnattached = 0;
766 if (vinit_attach_abort) {
767 Log("Aborting initialization\n");
771 dpq = queue_First(params,diskpartition_queue_t);
777 opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
784 params->n_threads_complete++;
785 opr_cv_signal(¶ms->thread_done_cv);
789 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
791 #if defined(AFS_DEMAND_ATTACH_FS)
793 * Attach volumes in vice partitions
795 * @param[in] pt calling program type
798 * @note Threaded version of attach partitions.
800 * @post VInit state is 2
803 VInitAttachVolumes(ProgramType pt)
805 opr_Assert(VInit==1);
806 if (pt == fileServer) {
808 struct DiskPartition64 *diskP;
809 struct partition_queue pq;
810 struct volume_init_queue vq;
812 int i, threads, parts;
814 pthread_attr_t attrs;
816 /* create partition work queue */
819 opr_mutex_init(&pq.mutex);
820 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
821 struct diskpartition_queue_t *dp;
822 dp = malloc(sizeof(struct diskpartition_queue_t));
823 opr_Assert(dp != NULL);
825 queue_Append(&pq, dp);
828 /* number of worker threads; at least one, not to exceed the number of partitions */
829 threads = min(parts, vol_attach_threads);
831 /* create volume work queue */
834 opr_mutex_init(&vq.mutex);
836 opr_Verify(pthread_attr_init(&attrs) == 0);
837 opr_Verify(pthread_attr_setdetachstate(&attrs,
838 PTHREAD_CREATE_DETACHED) == 0);
840 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
841 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
844 /* create threads to scan disk partitions. */
845 for (i=0; i < threads; i++) {
846 struct vinitvolumepackage_thread_param *params;
849 params = malloc(sizeof(struct vinitvolumepackage_thread_param));
853 params->nthreads = threads;
854 params->thread = i+1;
857 opr_Verify(pthread_create(&tid, &attrs,
858 &VInitVolumePackageThread,
859 (void*)params) == 0);
860 AFS_SIGSET_RESTORE();
863 VInitPreAttachVolumes(threads, &vq);
865 opr_Verify(pthread_attr_destroy(&attrs) == 0);
866 opr_cv_destroy(&pq.cv);
867 opr_mutex_destroy(&pq.mutex);
868 opr_cv_destroy(&vq.cv);
869 opr_mutex_destroy(&vq.mutex);
873 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
874 opr_cv_broadcast(&vol_init_attach_cond);
881 * Volume package initialization worker thread. Scan partitions for volume
882 * header files. Gather batches of volume ids and dispatch them to
883 * the main thread to be preattached. The volume preattachement is done
884 * in the main thread to avoid global volume lock contention.
887 VInitVolumePackageThread(void *args)
889 struct vinitvolumepackage_thread_param *params;
890 struct DiskPartition64 *partition;
891 struct partition_queue *pq;
892 struct volume_init_queue *vq;
893 struct volume_init_batch *vb;
896 params = (struct vinitvolumepackage_thread_param *)args;
902 vb = malloc(sizeof(struct volume_init_batch));
904 vb->thread = params->thread;
908 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
909 while((partition = VInitNextPartition(pq))) {
913 Log("Partition %s: pre-attaching volumes\n", partition->name);
914 dirp = opendir(VPartitionPath(partition));
916 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
919 while ((vid = VInitNextVolumeId(dirp))) {
920 Volume *vp = calloc(1, sizeof(Volume));
922 vp->device = partition->device;
923 vp->partition = partition;
925 queue_Init(&vp->vnode_list);
926 queue_Init(&vp->rx_call_list);
927 opr_cv_init(&V_attachCV(vp));
929 vb->batch[vb->size++] = vp;
930 if (vb->size == VINIT_BATCH_MAX_SIZE) {
931 opr_mutex_enter(&vq->mutex);
932 queue_Append(vq, vb);
933 opr_cv_broadcast(&vq->cv);
934 opr_mutex_exit(&vq->mutex);
936 vb = malloc(sizeof(struct volume_init_batch));
938 vb->thread = params->thread;
947 opr_mutex_enter(&vq->mutex);
948 queue_Append(vq, vb);
949 opr_cv_broadcast(&vq->cv);
950 opr_mutex_exit(&vq->mutex);
952 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
958 * Read next element from the pre-populated partition list.
960 static struct DiskPartition64*
961 VInitNextPartition(struct partition_queue *pq)
963 struct DiskPartition64 *partition;
964 struct diskpartition_queue_t *dp; /* queue element */
966 if (vinit_attach_abort) {
967 Log("Aborting volume preattach thread.\n");
971 /* get next partition to scan */
972 opr_mutex_enter(&pq->mutex);
973 if (queue_IsEmpty(pq)) {
974 opr_mutex_exit(&pq->mutex);
977 dp = queue_First(pq, diskpartition_queue_t);
979 opr_mutex_exit(&pq->mutex);
982 opr_Assert(dp->diskP);
984 partition = dp->diskP;
990 * Find next volume id on the partition.
993 VInitNextVolumeId(DIR *dirp)
999 while((d = readdir(dirp))) {
1000 if (vinit_attach_abort) {
1001 Log("Aborting volume preattach thread.\n");
1004 ext = strrchr(d->d_name, '.');
1005 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1006 vid = VolumeNumber(d->d_name);
1010 Log("Warning: bogus volume header file: %s\n", d->d_name);
1017 * Preattach volumes in batches to avoid lock contention.
1020 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1022 struct volume_init_batch *vb;
1026 /* dequeue next volume */
1027 opr_mutex_enter(&vq->mutex);
1028 if (queue_IsEmpty(vq)) {
1029 opr_cv_wait(&vq->cv, &vq->mutex);
1031 vb = queue_First(vq, volume_init_batch);
1033 opr_mutex_exit(&vq->mutex);
1037 for (i = 0; i<vb->size; i++) {
1043 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1045 Log("Error looking up volume, code=%d\n", ec);
1048 Log("Warning: Duplicate volume id %" AFS_VOLID_FMT " detected.\n", afs_printable_VolumeId_lu(vp->hashid));
1051 /* put pre-attached volume onto the hash table
1052 * and bring it up to the pre-attached state */
1053 AddVolumeToHashTable(vp, vp->hashid);
1054 AddVolumeToVByPList_r(vp);
1055 VLRU_Init_Node_r(vp);
1056 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1069 #endif /* AFS_DEMAND_ATTACH_FS */
1071 #if !defined(AFS_DEMAND_ATTACH_FS)
1073 * attach all volumes on a given disk partition
1076 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1082 Log("Partition %s: attaching volumes\n", diskP->name);
1083 dirp = opendir(VPartitionPath(diskP));
1085 Log("opendir on Partition %s failed!\n", diskP->name);
1089 while ((dp = readdir(dirp))) {
1091 p = strrchr(dp->d_name, '.');
1093 if (vinit_attach_abort) {
1094 Log("Partition %s: abort attach volumes\n", diskP->name);
1098 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1101 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1103 (*(vp ? nAttached : nUnattached))++;
1104 if (error == VOFFLINE)
1105 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1106 else if (GetLogLevel() >= 5) {
1107 Log("Partition %s: attached volume %d (%s)\n",
1108 diskP->name, VolumeNumber(dp->d_name),
1117 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1122 #endif /* !AFS_DEMAND_ATTACH_FS */
1124 /***************************************************/
1125 /* Shutdown routines */
1126 /***************************************************/
1130 * highly multithreaded volume package shutdown
1132 * with the demand attach fileserver extensions,
1133 * VShutdown has been modified to be multithreaded.
1134 * In order to achieve optimal use of many threads,
1135 * the shutdown code involves one control thread and
1136 * n shutdown worker threads. The control thread
1137 * periodically examines the number of volumes available
1138 * for shutdown on each partition, and produces a worker
1139 * thread allocation schedule. The idea is to eliminate
1140 * redundant scheduling computation on the workers by
1141 * having a single master scheduler.
1143 * The scheduler's objectives are:
1145 * each partition with volumes remaining gets allocated
1146 * at least 1 thread (assuming sufficient threads)
1148 * threads are allocated proportional to the number of
1149 * volumes remaining to be offlined. This ensures that
1150 * the OS I/O scheduler has many requests to elevator
1151 * seek on partitions that will (presumably) take the
1152 * longest amount of time (from now) to finish shutdown
1153 * (3) keep threads busy
1154 * when there are extra threads, they are assigned to
1155 * partitions using a simple round-robin algorithm
1157 * In the future, we may wish to add the ability to adapt
1158 * to the relative performance patterns of each disk
1163 * multi-step shutdown process
1165 * demand attach shutdown is a four-step process. Each
1166 * shutdown "pass" shuts down increasingly more difficult
1167 * volumes. The main purpose is to achieve better cache
1168 * utilization during shutdown.
1171 * shutdown volumes in the unattached, pre-attached
1174 * shutdown attached volumes with cached volume headers
1176 * shutdown all volumes in non-exclusive states
1178 * shutdown all remaining volumes
1181 #ifdef AFS_DEMAND_ATTACH_FS
1187 struct DiskPartition64 * diskP;
1188 struct diskpartition_queue_t * dpq;
1189 vshutdown_thread_t params;
1191 pthread_attr_t attrs;
1193 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1196 Log("VShutdown: aborting attach volumes\n");
1197 vinit_attach_abort = 1;
1198 VOL_CV_WAIT(&vol_init_attach_cond);
1201 for (params.n_parts=0, diskP = DiskPartitionList;
1202 diskP; diskP = diskP->next, params.n_parts++);
1204 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1205 params.n_parts, params.n_parts > 1 ? "s" : "");
1207 vol_shutting_down = 1;
1209 if (vol_attach_threads > 1) {
1210 /* prepare for parallel shutdown */
1211 params.n_threads = vol_attach_threads;
1212 opr_mutex_init(¶ms.lock);
1213 opr_cv_init(¶ms.cv);
1214 opr_cv_init(¶ms.master_cv);
1215 opr_Verify(pthread_attr_init(&attrs) == 0);
1216 opr_Verify(pthread_attr_setdetachstate(&attrs,
1217 PTHREAD_CREATE_DETACHED) == 0);
1218 queue_Init(¶ms);
1220 /* setup the basic partition information structures for
1221 * parallel shutdown */
1222 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1224 struct rx_queue * qp, * nqp;
1228 VVByPListWait_r(diskP);
1229 VVByPListBeginExclusive_r(diskP);
1232 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1233 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1237 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1238 VPartitionPath(diskP), count);
1241 /* build up the pass 0 shutdown work queue */
1242 dpq = malloc(sizeof(struct diskpartition_queue_t));
1243 opr_Assert(dpq != NULL);
1245 queue_Prepend(¶ms, dpq);
1247 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1250 Log("VShutdown: beginning parallel fileserver shutdown\n");
1251 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1252 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1254 /* do pass 0 shutdown */
1255 opr_mutex_enter(¶ms.lock);
1256 for (i=0; i < params.n_threads; i++) {
1257 opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1261 /* wait for all the pass 0 shutdowns to complete */
1262 while (params.n_threads_complete < params.n_threads) {
1263 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1265 params.n_threads_complete = 0;
1267 opr_cv_broadcast(¶ms.cv);
1268 opr_mutex_exit(¶ms.lock);
1270 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1271 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1273 /* run the parallel shutdown scheduler. it will drop the glock internally */
1274 ShutdownController(¶ms);
1276 /* wait for all the workers to finish pass 3 and terminate */
1277 while (params.pass < 4) {
1278 VOL_CV_WAIT(¶ms.cv);
1281 opr_Verify(pthread_attr_destroy(&attrs) == 0);
1282 opr_cv_destroy(¶ms.cv);
1283 opr_cv_destroy(¶ms.master_cv);
1284 opr_mutex_destroy(¶ms.lock);
1286 /* drop the VByPList exclusive reservations */
1287 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1288 VVByPListEndExclusive_r(diskP);
1289 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1290 VPartitionPath(diskP),
1291 params.stats[0][diskP->index],
1292 params.stats[1][diskP->index],
1293 params.stats[2][diskP->index],
1294 params.stats[3][diskP->index]);
1297 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1299 /* if we're only going to run one shutdown thread, don't bother creating
1301 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1303 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1304 VShutdownByPartition_r(diskP);
1308 Log("VShutdown: complete.\n");
1311 #else /* AFS_DEMAND_ATTACH_FS */
1321 Log("VShutdown: aborting attach volumes\n");
1322 vinit_attach_abort = 1;
1323 #ifdef AFS_PTHREAD_ENV
1324 VOL_CV_WAIT(&vol_init_attach_cond);
1326 LWP_WaitProcess(VInitAttachVolumes);
1327 #endif /* AFS_PTHREAD_ENV */
1330 Log("VShutdown: shutting down on-line volumes...\n");
1331 vol_shutting_down = 1;
1332 for (i = 0; i < VolumeHashTable.Size; i++) {
1333 /* try to hold first volume in the hash table */
1334 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1337 if (GetLogLevel() >= 5)
1338 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1339 afs_printable_VolumeId_lu(vp->hashid));
1341 /* next, take the volume offline (drops reference count) */
1342 VOffline_r(vp, "File server was shut down");
1346 Log("VShutdown: complete.\n");
1348 #endif /* AFS_DEMAND_ATTACH_FS */
1354 opr_Assert(VInit>0);
1361 * stop new activity (e.g. SALVSYNC) from occurring
1363 * Use this to make the volume package less busy; for example, during
1364 * shutdown. This doesn't actually shutdown/detach anything in the
1365 * volume package, but prevents certain processes from ocurring. For
1366 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1367 * could also use this to prevent new volume attachment, or prevent
1368 * other programs from checking out volumes, etc.
1373 #ifdef AFS_DEMAND_ATTACH_FS
1374 /* make sure we don't try to contact the salvageserver, since it may
1375 * not be around anymore */
1376 vol_disallow_salvsync = 1;
1380 #ifdef AFS_DEMAND_ATTACH_FS
1383 * shutdown control thread
1386 ShutdownController(vshutdown_thread_t * params)
1389 struct DiskPartition64 * diskP;
1391 vshutdown_thread_t shadow;
1393 ShutdownCreateSchedule(params);
1395 while ((params->pass < 4) &&
1396 (params->n_threads_complete < params->n_threads)) {
1397 /* recompute schedule once per second */
1399 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1403 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1404 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1405 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1406 shadow.n_threads_complete, shadow.n_parts_done_pass);
1407 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1409 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1411 diskP->vol_list.len,
1412 shadow.part_thread_target[id],
1413 shadow.part_done_pass[id],
1414 shadow.part_pass_head[id]);
1420 ShutdownCreateSchedule(params);
1424 /* create the shutdown thread work schedule.
1425 * this scheduler tries to implement fairness
1426 * by allocating at least 1 thread to each
1427 * partition with volumes to be shutdown,
1428 * and then it attempts to allocate remaining
1429 * threads based upon the amount of work left
1432 ShutdownCreateSchedule(vshutdown_thread_t * params)
1434 struct DiskPartition64 * diskP;
1435 int sum, thr_workload, thr_left;
1436 int part_residue[VOLMAXPARTS+1];
1439 /* compute the total number of outstanding volumes */
1441 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1442 sum += diskP->vol_list.len;
1445 params->schedule_version++;
1446 params->vol_remaining = sum;
1451 /* compute average per-thread workload */
1452 thr_workload = sum / params->n_threads;
1453 if (sum % params->n_threads)
1456 thr_left = params->n_threads;
1457 memset(&part_residue, 0, sizeof(part_residue));
1459 /* for fairness, give every partition with volumes remaining
1460 * at least one thread */
1461 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1463 if (diskP->vol_list.len) {
1464 params->part_thread_target[id] = 1;
1467 params->part_thread_target[id] = 0;
1471 if (thr_left && thr_workload) {
1472 /* compute length-weighted workloads */
1475 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1477 delta = (diskP->vol_list.len / thr_workload) -
1478 params->part_thread_target[id];
1482 if (delta < thr_left) {
1483 params->part_thread_target[id] += delta;
1486 params->part_thread_target[id] += thr_left;
1494 /* try to assign any leftover threads to partitions that
1495 * had volume lengths closer to needing thread_target+1 */
1496 int max_residue, max_id = 0;
1498 /* compute the residues */
1499 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1501 part_residue[id] = diskP->vol_list.len -
1502 (params->part_thread_target[id] * thr_workload);
1505 /* now try to allocate remaining threads to partitions with the
1506 * highest residues */
1509 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1511 if (part_residue[id] > max_residue) {
1512 max_residue = part_residue[id];
1521 params->part_thread_target[max_id]++;
1523 part_residue[max_id] = 0;
1528 /* punt and give any remaining threads equally to each partition */
1530 if (thr_left >= params->n_parts) {
1531 alloc = thr_left / params->n_parts;
1532 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1534 params->part_thread_target[id] += alloc;
1539 /* finish off the last of the threads */
1540 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1542 params->part_thread_target[id]++;
1548 /* worker thread for parallel shutdown */
1550 VShutdownThread(void * args)
1552 vshutdown_thread_t * params;
1553 int found, pass, schedule_version_save, count;
1554 struct DiskPartition64 *diskP;
1555 struct diskpartition_queue_t * dpq;
1558 params = (vshutdown_thread_t *) args;
1560 /* acquire the shutdown pass 0 lock */
1561 opr_mutex_enter(¶ms->lock);
1563 /* if there's still pass 0 work to be done,
1564 * get a work entry, and do a pass 0 shutdown */
1565 if (queue_IsNotEmpty(params)) {
1566 dpq = queue_First(params, diskpartition_queue_t);
1568 opr_mutex_exit(¶ms->lock);
1574 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1576 params->stats[0][diskP->index] = count;
1577 opr_mutex_enter(¶ms->lock);
1580 params->n_threads_complete++;
1581 if (params->n_threads_complete == params->n_threads) {
1582 /* notify control thread that all workers have completed pass 0 */
1583 opr_cv_signal(¶ms->master_cv);
1585 while (params->pass == 0) {
1586 opr_cv_wait(¶ms->cv, ¶ms->lock);
1590 opr_mutex_exit(¶ms->lock);
1593 pass = params->pass;
1594 opr_Assert(pass > 0);
1596 /* now escalate through the more complicated shutdowns */
1598 schedule_version_save = params->schedule_version;
1600 /* find a disk partition to work on */
1601 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1603 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1604 params->part_thread_target[id]--;
1611 /* hmm. for some reason the controller thread couldn't find anything for
1612 * us to do. let's see if there's anything we can do */
1613 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1615 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1618 } else if (!params->part_done_pass[id]) {
1619 params->part_done_pass[id] = 1;
1620 params->n_parts_done_pass++;
1622 Log("VShutdown: done shutting down volumes on partition %s.\n",
1623 VPartitionPath(diskP));
1629 /* do work on this partition until either the controller
1630 * creates a new schedule, or we run out of things to do
1631 * on this partition */
1634 while (!params->part_done_pass[id] &&
1635 (schedule_version_save == params->schedule_version)) {
1636 /* ShutdownVolumeWalk_r will drop the glock internally */
1637 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1638 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));
1651 params->stats[pass][id] += count;
1653 /* ok, everyone is done this pass, proceed */
1656 params->n_threads_complete++;
1657 while (params->pass == pass) {
1658 if (params->n_threads_complete == params->n_threads) {
1659 /* we are the last thread to complete, so we will
1660 * reinitialize worker pool state for the next pass */
1661 params->n_threads_complete = 0;
1662 params->n_parts_done_pass = 0;
1664 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1666 params->part_done_pass[id] = 0;
1667 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1670 /* compute a new thread schedule before releasing all the workers */
1671 ShutdownCreateSchedule(params);
1673 /* wake up all the workers */
1674 opr_cv_broadcast(¶ms->cv);
1677 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1678 pass, params->n_threads, params->n_parts);
1681 VOL_CV_WAIT(¶ms->cv);
1684 pass = params->pass;
1698 /* shut down all volumes on a given disk partition
1700 * note that this function will not allow mp-fast
1701 * shutdown of a partition */
1703 VShutdownByPartition_r(struct DiskPartition64 * dp)
1709 /* wait for other exclusive ops to finish */
1710 VVByPListWait_r(dp);
1712 /* begin exclusive access */
1713 VVByPListBeginExclusive_r(dp);
1715 /* pick the low-hanging fruit first,
1716 * then do the complicated ones last
1717 * (has the advantage of keeping
1718 * in-use volumes up until the bitter end) */
1719 for (pass = 0, total=0; pass < 4; pass++) {
1720 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1721 total += pass_stats[pass];
1724 /* end exclusive access */
1725 VVByPListEndExclusive_r(dp);
1727 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1728 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1733 /* internal shutdown functionality
1735 * for multi-pass shutdown:
1736 * 0 to only "shutdown" {pre,un}attached and error state volumes
1737 * 1 to also shutdown attached volumes w/ volume header loaded
1738 * 2 to also shutdown attached volumes w/o volume header loaded
1739 * 3 to also shutdown exclusive state volumes
1741 * caller MUST hold exclusive access on the hash chain
1742 * because we drop vol_glock_mutex internally
1744 * this function is reentrant for passes 1--3
1745 * (e.g. multiple threads can cooperate to
1746 * shutdown a partition mp-fast)
1748 * pass 0 is not scaleable because the volume state data is
1749 * synchronized by vol_glock mutex, and the locking overhead
1750 * is too high to drop the lock long enough to do linked list
1754 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1756 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1758 const char *pass_strs[4] = {"{un/pre}attached vols", "vols w/ vol header loaded", "vols w/o vol header loaded", "vols with exclusive state"};
1760 while (ShutdownVolumeWalk_r(dp, pass, &q)) {
1763 Log("VShutdownByPartition: ... shut down %d volumes on %s in pass %d (%s)\n", i, VPartitionPath(dp), pass, pass_strs[pass]);
1770 /* conditionally shutdown one volume on partition dp
1771 * returns 1 if a volume was shutdown in this pass,
1774 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1775 struct rx_queue ** idx)
1777 struct rx_queue *qp, *nqp;
1782 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1783 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1787 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1788 (V_attachState(vp) != VOL_STATE_ERROR) &&
1789 (V_attachState(vp) != VOL_STATE_DELETED) &&
1790 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1795 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1796 (vp->header == NULL)) {
1801 if (VIsExclusiveState(V_attachState(vp))) {
1807 DeleteVolumeFromVByPList_r(vp);
1808 VShutdownVolume_r(vp);
1818 * shutdown a specific volume
1820 /* caller MUST NOT hold a heavyweight ref on vp */
1822 VShutdownVolume_r(Volume * vp)
1826 VCreateReservation_r(vp);
1828 if (GetLogLevel() >= 5) {
1829 Log("VShutdownVolume_r: vid=%" AFS_VOLID_FMT ", device=%d, state=%u\n",
1830 afs_printable_VolumeId_lu(vp->hashid), vp->partition->device,
1831 (unsigned int) V_attachState(vp));
1834 /* wait for other blocking ops to finish */
1835 VWaitExclusiveState_r(vp);
1837 opr_Assert(VIsValidState(V_attachState(vp)));
1839 switch(V_attachState(vp)) {
1840 case VOL_STATE_SALVAGING:
1841 /* Leave salvaging volumes alone. Any in-progress salvages will
1842 * continue working after viced shuts down. This is intentional.
1845 case VOL_STATE_PREATTACHED:
1846 case VOL_STATE_ERROR:
1847 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1848 case VOL_STATE_UNATTACHED:
1849 case VOL_STATE_DELETED:
1851 case VOL_STATE_GOING_OFFLINE:
1852 case VOL_STATE_SHUTTING_DOWN:
1853 case VOL_STATE_ATTACHED:
1856 if (GetLogLevel() >= 5)
1857 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1858 afs_printable_VolumeId_lu(vp->hashid));
1860 /* take the volume offline (drops reference count) */
1861 VOffline_r(vp, "File server was shut down");
1868 VCancelReservation_r(vp);
1872 #endif /* AFS_DEMAND_ATTACH_FS */
1875 /***************************************************/
1876 /* Header I/O routines */
1877 /***************************************************/
1880 HeaderName(bit32 magic)
1883 case VOLUMEINFOMAGIC:
1884 return "volume info";
1885 case SMALLINDEXMAGIC:
1886 return "small index";
1887 case LARGEINDEXMAGIC:
1888 return "large index";
1889 case LINKTABLEMAGIC:
1890 return "link table";
1895 /* open a descriptor for the inode (h),
1896 * read in an on-disk structure into buffer (to) of size (size),
1897 * verify versionstamp in structure has magic (magic) and
1898 * optionally verify version (version) if (version) is nonzero
1901 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1904 struct versionStamp *vsn;
1906 afs_sfsize_t nbytes;
1911 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1919 Log("ReadHeader: Failed to open %s header file "
1920 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1921 PrintInode(stmp, h->ih_ino), errno);
1926 vsn = (struct versionStamp *)to;
1927 nbytes = FDH_PREAD(fdP, to, size, 0);
1929 Log("ReadHeader: Failed to read %s header file "
1930 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1931 PrintInode(stmp, h->ih_ino), errno);
1933 FDH_REALLYCLOSE(fdP);
1936 if (nbytes != size) {
1937 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1938 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%d, read=%d\n",
1939 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1940 PrintInode(stmp, h->ih_ino), size, (int)nbytes);
1942 FDH_REALLYCLOSE(fdP);
1945 if (vsn->magic != magic) {
1946 Log("ReadHeader: Incorrect magic for %s header file "
1947 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=0x%x, read=0x%x\n",
1948 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1949 PrintInode(stmp, h->ih_ino), magic, vsn->magic);
1951 FDH_REALLYCLOSE(fdP);
1957 /* Check is conditional, in case caller wants to inspect version himself */
1958 if (version && vsn->version != version) {
1959 Log("ReadHeader: Incorrect version for %s header file "
1960 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%x, read=%x\n",
1961 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid), PrintInode(stmp, h->ih_ino),
1962 version, vsn->version);
1968 WriteVolumeHeader_r(Error * ec, Volume * vp)
1970 IHandle_t *h = V_diskDataHandle(vp);
1980 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1981 != sizeof(V_disk(vp))) {
1983 FDH_REALLYCLOSE(fdP);
1989 /* VolumeHeaderToDisk
1990 * Allows for storing 64 bit inode numbers in on-disk volume header
1993 /* convert in-memory representation of a volume header to the
1994 * on-disk representation of a volume header */
1996 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1999 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2000 dh->stamp = h->stamp;
2002 dh->parent = h->parent;
2004 #ifdef AFS_64BIT_IOPS_ENV
2005 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2006 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2007 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2008 dh->smallVnodeIndex_hi =
2009 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2010 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2011 dh->largeVnodeIndex_hi =
2012 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2013 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2014 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2016 dh->volumeInfo_lo = h->volumeInfo;
2017 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2018 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2019 dh->linkTable_lo = h->linkTable;
2023 /* DiskToVolumeHeader
2024 * Converts an on-disk representation of a volume header to
2025 * the in-memory representation of a volume header.
2027 * Makes the assumption that AFS has *always*
2028 * zero'd the volume header file so that high parts of inode
2029 * numbers are 0 in older (SGI EFS) volume header files.
2032 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2034 memset(h, 0, sizeof(VolumeHeader_t));
2035 h->stamp = dh->stamp;
2037 h->parent = dh->parent;
2039 #ifdef AFS_64BIT_IOPS_ENV
2041 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2043 h->smallVnodeIndex =
2044 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2045 smallVnodeIndex_hi << 32);
2047 h->largeVnodeIndex =
2048 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2049 largeVnodeIndex_hi << 32);
2051 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2053 h->volumeInfo = dh->volumeInfo_lo;
2054 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2055 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2056 h->linkTable = dh->linkTable_lo;
2061 /***************************************************/
2062 /* Volume Attachment routines */
2063 /***************************************************/
2065 #ifdef AFS_DEMAND_ATTACH_FS
2067 * pre-attach a volume given its path.
2069 * @param[out] ec outbound error code
2070 * @param[in] partition partition path string
2071 * @param[in] name volume id string
2073 * @return volume object pointer
2075 * @note A pre-attached volume will only have its partition
2076 * and hashid fields initialized. At first call to
2077 * VGetVolume, the volume will be fully attached.
2081 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2085 vp = VPreAttachVolumeByName_r(ec, partition, name);
2091 * pre-attach a volume given its path.
2093 * @param[out] ec outbound error code
2094 * @param[in] partition path to vice partition
2095 * @param[in] name volume id string
2097 * @return volume object pointer
2099 * @pre VOL_LOCK held
2101 * @internal volume package internal use only.
2104 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2106 return VPreAttachVolumeById_r(ec,
2108 VolumeNumber(name));
2112 * pre-attach a volume given its path and numeric volume id.
2114 * @param[out] ec error code return
2115 * @param[in] partition path to vice partition
2116 * @param[in] volumeId numeric volume id
2118 * @return volume object pointer
2120 * @pre VOL_LOCK held
2122 * @internal volume package internal use only.
2125 VPreAttachVolumeById_r(Error * ec,
2130 struct DiskPartition64 *partp;
2134 opr_Assert(programType == fileServer);
2136 if (!(partp = VGetPartition_r(partition, 0))) {
2138 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2142 /* ensure that any vp we pass to VPreAttachVolumeByVp_r
2143 * is NOT in exclusive state.
2146 vp = VLookupVolume_r(ec, volumeId, NULL);
2152 if (vp && VIsExclusiveState(V_attachState(vp))) {
2153 VCreateReservation_r(vp);
2154 VWaitExclusiveState_r(vp);
2155 VCancelReservation_r(vp);
2157 goto retry; /* look up volume again */
2160 /* vp == NULL or vp not exclusive both OK */
2162 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2166 * preattach a volume.
2168 * @param[out] ec outbound error code
2169 * @param[in] partp pointer to partition object
2170 * @param[in] vp pointer to volume object
2171 * @param[in] vid volume id
2173 * @return volume object pointer
2175 * @pre VOL_LOCK is held.
2177 * @pre vp (if specified) must not be in exclusive state.
2179 * @warning Returned volume object pointer does not have to
2180 * equal the pointer passed in as argument vp. There
2181 * are potential race conditions which can result in
2182 * the pointers having different values. It is up to
2183 * the caller to make sure that references are handled
2184 * properly in this case.
2186 * @note If there is already a volume object registered with
2187 * the same volume id, its pointer MUST be passed as
2188 * argument vp. Failure to do so will result in a silent
2189 * failure to preattach.
2191 * @internal volume package internal use only.
2194 VPreAttachVolumeByVp_r(Error * ec,
2195 struct DiskPartition64 * partp,
2203 /* don't proceed unless it's safe */
2205 opr_Assert(!VIsExclusiveState(V_attachState(vp)));
2208 /* check to see if pre-attach already happened */
2210 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2211 (V_attachState(vp) != VOL_STATE_DELETED) &&
2212 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2213 !VIsErrorState(V_attachState(vp))) {
2215 * pre-attach is a no-op in all but the following cases:
2217 * - volume is unattached
2218 * - volume is in an error state
2219 * - volume is pre-attached
2221 Log("VPreattachVolumeByVp_r: volume %" AFS_VOLID_FMT " not in quiescent state (state %u flags 0x%x)\n",
2222 afs_printable_VolumeId_lu(vid), V_attachState(vp),
2226 /* we're re-attaching a volume; clear out some old state */
2227 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2229 if (V_partition(vp) != partp) {
2230 /* XXX potential race */
2231 DeleteVolumeFromVByPList_r(vp);
2234 /* if we need to allocate a new Volume struct,
2235 * go ahead and drop the vol glock, otherwise
2236 * do the basic setup synchronised, as it's
2237 * probably not worth dropping the lock */
2240 /* allocate the volume structure */
2241 vp = nvp = calloc(1, sizeof(Volume));
2242 opr_Assert(vp != NULL);
2243 queue_Init(&vp->vnode_list);
2244 queue_Init(&vp->rx_call_list);
2245 opr_cv_init(&V_attachCV(vp));
2248 /* link the volume with its associated vice partition */
2249 vp->device = partp->device;
2250 vp->partition = partp;
2253 vp->specialStatus = 0;
2255 /* if we dropped the lock, reacquire the lock,
2256 * check for pre-attach races, and then add
2257 * the volume to the hash table */
2260 nvp = VLookupVolume_r(ec, vid, NULL);
2265 } else if (nvp) { /* race detected */
2270 /* hack to make up for VChangeState_r() decrementing
2271 * the old state counter */
2272 VStats.state_levels[0]++;
2276 /* put pre-attached volume onto the hash table
2277 * and bring it up to the pre-attached state */
2278 AddVolumeToHashTable(vp, vp->hashid);
2279 AddVolumeToVByPList_r(vp);
2280 VLRU_Init_Node_r(vp);
2281 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2283 if (GetLogLevel() >= 5)
2284 Log("VPreAttachVolumeByVp_r: volume %" AFS_VOLID_FMT " pre-attached\n", afs_printable_VolumeId_lu(vp->hashid));
2292 #endif /* AFS_DEMAND_ATTACH_FS */
2294 /* Attach an existing volume, given its pathname, and return a
2295 pointer to the volume header information. The volume also
2296 normally goes online at this time. An offline volume
2297 must be reattached to make it go online */
2299 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2303 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2309 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2312 struct DiskPartition64 *partp;
2317 #ifdef AFS_DEMAND_ATTACH_FS
2318 VolumeStats stats_save;
2320 #endif /* AFS_DEMAND_ATTACH_FS */
2324 volumeId = VolumeNumber(name);
2326 if (!(partp = VGetPartition_r(partition, 0))) {
2328 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2332 if (VRequiresPartLock()) {
2333 opr_Assert(VInit == 3);
2334 VLockPartition_r(partition);
2335 } else if (programType == fileServer) {
2336 #ifdef AFS_DEMAND_ATTACH_FS
2337 /* lookup the volume in the hash table */
2338 vp = VLookupVolume_r(ec, volumeId, NULL);
2344 /* save any counters that are supposed to
2345 * be monotonically increasing over the
2346 * lifetime of the fileserver */
2347 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2349 memset(&stats_save, 0, sizeof(VolumeStats));
2352 /* if there's something in the hash table, and it's not
2353 * in the pre-attach state, then we may need to detach
2354 * it before proceeding */
2355 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2356 VCreateReservation_r(vp);
2357 VWaitExclusiveState_r(vp);
2359 /* at this point state must be one of:
2369 if (vp->specialStatus == VBUSY)
2372 /* if it's already attached, see if we can return it */
2373 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2374 VGetVolumeByVp_r(ec, vp);
2375 if (V_inUse(vp) == fileServer) {
2376 VCancelReservation_r(vp);
2380 /* otherwise, we need to detach, and attempt to re-attach */
2381 VDetachVolume_r(ec, vp);
2383 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2386 /* if it isn't fully attached, delete from the hash tables,
2387 and let the refcounter handle the rest */
2388 DeleteVolumeFromHashTable(vp);
2389 DeleteVolumeFromVByPList_r(vp);
2392 VCancelReservation_r(vp);
2396 /* pre-attach volume if it hasn't been done yet */
2398 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2399 (V_attachState(vp) == VOL_STATE_DELETED) ||
2400 (V_attachState(vp) == VOL_STATE_ERROR)) {
2402 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2408 opr_Assert(vp != NULL);
2410 /* handle pre-attach races
2412 * multiple threads can race to pre-attach a volume,
2413 * but we can't let them race beyond that
2415 * our solution is to let the first thread to bring
2416 * the volume into an exclusive state win; the other
2417 * threads just wait until it finishes bringing the
2418 * volume online, and then they do a vgetvolumebyvp
2420 if (svp && (svp != vp)) {
2421 /* wait for other exclusive ops to finish */
2422 VCreateReservation_r(vp);
2423 VWaitExclusiveState_r(vp);
2425 /* get a heavyweight ref, kill the lightweight ref, and return */
2426 VGetVolumeByVp_r(ec, vp);
2427 VCancelReservation_r(vp);
2431 /* at this point, we are chosen as the thread to do
2432 * demand attachment for this volume. all other threads
2433 * doing a getvolume on vp->hashid will block until we finish */
2435 /* make sure any old header cache entries are invalidated
2436 * before proceeding */
2437 FreeVolumeHeader(vp);
2439 VChangeState_r(vp, VOL_STATE_ATTACHING);
2441 /* restore any saved counters */
2442 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2443 #else /* AFS_DEMAND_ATTACH_FS */
2444 vp = VGetVolume_r(ec, volumeId);
2446 if (V_inUse(vp) == fileServer)
2448 if (vp->specialStatus == VBUSY)
2450 VDetachVolume_r(ec, vp);
2452 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2456 #endif /* AFS_DEMAND_ATTACH_FS */
2460 strcpy(path, VPartitionPath(partp));
2464 strcat(path, OS_DIRSEP);
2468 vp = (Volume *) calloc(1, sizeof(Volume));
2469 opr_Assert(vp != NULL);
2470 vp->hashid = volumeId;
2471 vp->device = partp->device;
2472 vp->partition = partp;
2473 queue_Init(&vp->vnode_list);
2474 queue_Init(&vp->rx_call_list);
2475 #ifdef AFS_DEMAND_ATTACH_FS
2476 opr_cv_init(&V_attachCV(vp));
2477 #endif /* AFS_DEMAND_ATTACH_FS */
2480 /* attach2 is entered without any locks, and returns
2481 * with vol_glock_mutex held */
2482 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2484 if (VCanUseFSSYNC() && vp) {
2485 #ifdef AFS_DEMAND_ATTACH_FS
2486 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2487 /* mark volume header as in use so that volser crashes lead to a
2488 * salvage attempt */
2489 VUpdateVolume_r(ec, vp, 0);
2491 /* for dafs, we should tell the fileserver, except for V_PEEK
2492 * where we know it is not necessary */
2493 if (mode == V_PEEK) {
2494 vp->needsPutBack = 0;
2496 vp->needsPutBack = VOL_PUTBACK;
2498 #else /* !AFS_DEMAND_ATTACH_FS */
2499 /* duplicate computation in fssync.c about whether the server
2500 * takes the volume offline or not. If the volume isn't
2501 * offline, we must not return it when we detach the volume,
2502 * or the server will abort */
2503 if (mode == V_READONLY || mode == V_PEEK
2504 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2505 vp->needsPutBack = 0;
2507 vp->needsPutBack = VOL_PUTBACK;
2508 #endif /* !AFS_DEMAND_ATTACH_FS */
2510 #ifdef FSSYNC_BUILD_CLIENT
2511 /* Only give back the vol to the fileserver if we checked it out; attach2
2512 * will set checkedOut only if we successfully checked it out from the
2514 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2516 #ifdef AFS_DEMAND_ATTACH_FS
2517 /* If we couldn't attach but we scheduled a salvage, we already
2518 * notified the fileserver; don't online it now */
2519 if (*ec != VSALVAGING)
2520 #endif /* AFS_DEMAND_ATTACH_FS */
2521 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2524 if (programType == fileServer && vp) {
2525 #ifdef AFS_DEMAND_ATTACH_FS
2527 * we can get here in cases where we don't "own"
2528 * the volume (e.g. volume owned by a utility).
2529 * short circuit around potential disk header races.
2531 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2535 VUpdateVolume_r(ec, vp, 0);
2537 Log("VAttachVolume: Error updating volume\n");
2542 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2543 #ifndef AFS_DEMAND_ATTACH_FS
2544 /* This is a hack: by temporarily setting the incore
2545 * dontSalvage flag ON, the volume will be put back on the
2546 * Update list (with dontSalvage OFF again). It will then
2547 * come back in N minutes with DONT_SALVAGE eventually
2548 * set. This is the way that volumes that have never had
2549 * it set get it set; or that volumes that have been
2550 * offline without DONT SALVAGE having been set also
2551 * eventually get it set */
2552 V_dontSalvage(vp) = DONT_SALVAGE;
2553 #endif /* !AFS_DEMAND_ATTACH_FS */
2554 VAddToVolumeUpdateList_r(ec, vp);
2556 Log("VAttachVolume: Error adding volume to update list\n");
2562 if (GetLogLevel() != 0)
2563 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n", afs_printable_VolumeId_lu(V_id(vp)),
2568 if (VRequiresPartLock()) {
2569 VUnlockPartition_r(partition);
2572 #ifdef AFS_DEMAND_ATTACH_FS
2573 /* attach failed; make sure we're in error state */
2574 if (vp && !VIsErrorState(V_attachState(vp))) {
2575 VChangeState_r(vp, VOL_STATE_ERROR);
2577 #endif /* AFS_DEMAND_ATTACH_FS */
2584 #ifdef AFS_DEMAND_ATTACH_FS
2585 /* VAttachVolumeByVp_r
2587 * finish attaching a volume that is
2588 * in a less than fully attached state
2590 /* caller MUST hold a ref count on vp */
2592 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2594 char name[VMAXPATHLEN];
2596 struct DiskPartition64 *partp;
2600 Volume * nvp = NULL;
2601 VolumeStats stats_save;
2605 /* volume utility should never call AttachByVp */
2606 opr_Assert(programType == fileServer);
2608 volumeId = vp->hashid;
2609 partp = vp->partition;
2610 VolumeExternalName_r(volumeId, name, sizeof(name));
2613 /* if another thread is performing a blocking op, wait */
2614 VWaitExclusiveState_r(vp);
2616 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2618 /* if it's already attached, see if we can return it */
2619 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2620 VGetVolumeByVp_r(ec, vp);
2621 if (V_inUse(vp) == fileServer) {
2624 if (vp->specialStatus == VBUSY)
2626 VDetachVolume_r(ec, vp);
2628 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2634 /* pre-attach volume if it hasn't been done yet */
2636 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2637 (V_attachState(vp) == VOL_STATE_DELETED) ||
2638 (V_attachState(vp) == VOL_STATE_ERROR)) {
2639 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2645 VCreateReservation_r(nvp);
2650 opr_Assert(vp != NULL);
2651 VChangeState_r(vp, VOL_STATE_ATTACHING);
2653 /* restore monotonically increasing stats */
2654 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2658 /* compute path to disk header */
2659 strcpy(path, VPartitionPath(partp));
2663 strcat(path, OS_DIRSEP);
2668 * NOTE: attach2 is entered without any locks, and returns
2669 * with vol_glock_mutex held */
2670 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2673 * the event that an error was encountered, or
2674 * the volume was not brought to an attached state
2675 * for any reason, skip to the end. We cannot
2676 * safely call VUpdateVolume unless we "own" it.
2680 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2684 VUpdateVolume_r(ec, vp, 0);
2686 Log("VAttachVolume: Error updating volume %" AFS_VOLID_FMT "\n",
2687 afs_printable_VolumeId_lu(vp->hashid));
2691 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2692 #ifndef AFS_DEMAND_ATTACH_FS
2693 /* This is a hack: by temporarily setting the incore
2694 * dontSalvage flag ON, the volume will be put back on the
2695 * Update list (with dontSalvage OFF again). It will then
2696 * come back in N minutes with DONT_SALVAGE eventually
2697 * set. This is the way that volumes that have never had
2698 * it set get it set; or that volumes that have been
2699 * offline without DONT SALVAGE having been set also
2700 * eventually get it set */
2701 V_dontSalvage(vp) = DONT_SALVAGE;
2702 #endif /* !AFS_DEMAND_ATTACH_FS */
2703 VAddToVolumeUpdateList_r(ec, vp);
2705 Log("VAttachVolume: Error adding volume %" AFS_VOLID_FMT " to update list\n",
2706 afs_printable_VolumeId_lu(vp->hashid));
2712 if (GetLogLevel() != 0)
2713 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n",
2714 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
2717 VCancelReservation_r(nvp);
2720 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2721 if (vp && !VIsErrorState(V_attachState(vp))) {
2722 VChangeState_r(vp, VOL_STATE_ERROR);
2731 * lock a volume on disk (non-blocking).
2733 * @param[in] vp The volume to lock
2734 * @param[in] locktype READ_LOCK or WRITE_LOCK
2736 * @return operation status
2737 * @retval 0 success, lock was obtained
2738 * @retval EBUSY a conflicting lock was held by another process
2739 * @retval EIO error acquiring lock
2741 * @pre If we're in the fileserver, vp is in an exclusive state
2743 * @pre vp is not already locked
2746 VLockVolumeNB(Volume *vp, int locktype)
2750 opr_Assert(programType != fileServer
2751 || VIsExclusiveState(V_attachState(vp)));
2752 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2754 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2756 V_attachFlags(vp) |= VOL_LOCKED;
2763 * unlock a volume on disk that was locked with VLockVolumeNB.
2765 * @param[in] vp volume to unlock
2767 * @pre If we're in the fileserver, vp is in an exclusive state
2769 * @pre vp has already been locked
2772 VUnlockVolume(Volume *vp)
2774 opr_Assert(programType != fileServer
2775 || VIsExclusiveState(V_attachState(vp)));
2776 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2778 VUnlockVolumeById(vp->hashid, vp->partition);
2780 V_attachFlags(vp) &= ~VOL_LOCKED;
2782 #endif /* AFS_DEMAND_ATTACH_FS */
2785 * read in a vol header, possibly lock the vol header, and possibly check out
2786 * the vol header from the fileserver, as part of volume attachment.
2788 * @param[out] ec error code
2789 * @param[in] vp volume pointer object
2790 * @param[in] partp disk partition object of the attaching partition
2791 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2793 * @param[in] peek 1 to just try to read in the volume header and make sure
2794 * we don't try to lock the vol, or check it out from
2795 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2797 * @param[out] acheckedOut If we successfully checked-out the volume from
2798 * the fileserver (if we needed to), this is set
2799 * to 1, otherwise it is untouched.
2801 * @note As part of DAFS volume attachment, the volume header may be either
2802 * read- or write-locked to ensure mutual exclusion of certain volume
2803 * operations. In some cases in order to determine whether we need to
2804 * read- or write-lock the header, we need to read in the header to see
2805 * if the volume is RW or not. So, if we read in the header under a
2806 * read-lock and determine that we actually need a write-lock on the
2807 * volume header, this function will drop the read lock, acquire a write
2808 * lock, and read the header in again.
2811 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2812 int mode, int peek, int *acheckedOut)
2814 struct VolumeDiskHeader diskHeader;
2815 struct VolumeHeader header;
2818 int lock_tries = 0, checkout_tries = 0;
2820 VolumeId volid = vp->hashid;
2821 #ifdef FSSYNC_BUILD_CLIENT
2822 int checkout, done_checkout = 0;
2823 #endif /* FSSYNC_BUILD_CLIENT */
2824 #ifdef AFS_DEMAND_ATTACH_FS
2825 int locktype = 0, use_locktype = -1;
2826 #endif /* AFS_DEMAND_ATTACH_FS */
2832 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2833 Log("VAttachVolume: retried too many times trying to lock header for "
2834 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2835 VPartitionPath(partp));
2839 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2840 Log("VAttachVolume: retried too many times trying to checkout "
2841 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2842 VPartitionPath(partp));
2847 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2848 /* short-circuit the 'volume does not exist' case */
2853 #ifdef FSSYNC_BUILD_CLIENT
2854 checkout = !done_checkout;
2856 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2858 memset(&res, 0, sizeof(res));
2860 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2863 if (res.hdr.reason == FSYNC_SALVAGE) {
2864 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2865 afs_printable_uint32_lu(volid));
2868 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2869 afs_printable_uint32_lu(volid));
2870 *ec = VNOVOL; /* XXXX */
2878 #ifdef AFS_DEMAND_ATTACH_FS
2879 if (use_locktype < 0) {
2880 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2881 * if it turns out to be RW */
2882 locktype = VVolLockType(mode, 0);
2885 /* a previous try says we should use use_locktype to lock the volume,
2887 locktype = use_locktype;
2890 if (!peek && locktype) {
2891 code = VLockVolumeNB(vp, locktype);
2893 if (code == EBUSY) {
2894 Log("VAttachVolume: another program has vol %lu locked\n",
2895 afs_printable_uint32_lu(volid));
2897 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2898 code, afs_printable_uint32_lu(volid));
2905 #endif /* AFS_DEMAND_ATTACH_FS */
2907 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2917 DiskToVolumeHeader(&header, &diskHeader);
2919 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2920 header.largeVnodeIndex);
2921 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2922 header.smallVnodeIndex);
2923 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2925 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2928 /* only need to do this once */
2930 GetVolumeHeader(vp);
2934 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2935 /* demand attach changes the V_PEEK mechanism
2937 * we can now suck the current disk data structure over
2938 * the fssync interface without going to disk
2940 * (technically, we don't need to restrict this feature
2941 * to demand attach fileservers. However, I'm trying
2942 * to limit the number of common code changes)
2944 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2946 res.payload.len = sizeof(VolumeDiskData);
2947 res.payload.buf = &(V_disk(vp));
2949 if (FSYNC_VolOp(vp->hashid,
2951 FSYNC_VOL_QUERY_HDR,
2954 goto disk_header_loaded;
2957 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2958 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2959 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2961 #ifdef AFS_DEMAND_ATTACH_FS
2964 IncUInt64(&VStats.hdr_loads);
2965 IncUInt64(&vp->stats.hdr_loads);
2967 #endif /* AFS_DEMAND_ATTACH_FS */
2970 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2971 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2975 #ifdef AFS_DEMAND_ATTACH_FS
2976 # ifdef FSSYNC_BUILD_CLIENT
2978 # endif /* FSSYNC_BUILD_CLIENT */
2980 /* if the lock type we actually used to lock the volume is different than
2981 * the lock type we should have used, retry with the lock type we should
2983 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2984 if (locktype != use_locktype) {
2988 #endif /* AFS_DEMAND_ATTACH_FS */
2993 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2994 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2996 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2998 if (code == SYNC_DENIED) {
2999 /* must retry checkout; fileserver no longer thinks we have
3005 } else if (code != SYNC_OK) {
3009 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3012 /* either we are going to be called again for a second pass, or we
3013 * encountered an error; clean up in either case */
3015 #ifdef AFS_DEMAND_ATTACH_FS
3016 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3019 #endif /* AFS_DEMAND_ATTACH_FS */
3020 if (vp->linkHandle) {
3021 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3022 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3023 IH_RELEASE(vp->diskDataHandle);
3024 IH_RELEASE(vp->linkHandle);
3030 FreeVolumeHeader(vp);
3040 #ifdef AFS_DEMAND_ATTACH_FS
3042 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3043 Volume *vp, int *acheckedOut)
3047 if (vp->pending_vol_op) {
3051 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3053 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3055 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3056 } else if (code == 0) {
3057 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3060 /* we need the vol header to determine if the volume can be
3061 * left online for the vop, so... get the header */
3065 /* attach header with peek=1 to avoid checking out the volume
3066 * or locking it; we just want the header info, we're not
3067 * messing with the volume itself at all */
3068 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3075 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3076 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3078 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3081 /* make sure we grab a new vol header and re-open stuff on
3082 * actual attachment; we can't keep the data we grabbed, since
3083 * it was not done under a lock and thus not safe */
3084 FreeVolumeHeader(vp);
3085 VReleaseVolumeHandles_r(vp);
3088 /* see if the pending volume op requires exclusive access */
3089 switch (vp->pending_vol_op->vol_op_state) {
3090 case FSSYNC_VolOpPending:
3091 /* this should never happen */
3092 opr_Assert(vp->pending_vol_op->vol_op_state
3093 != FSSYNC_VolOpPending);
3096 case FSSYNC_VolOpRunningUnknown:
3097 /* this should never happen; we resolved 'unknown' above */
3098 opr_Assert(vp->pending_vol_op->vol_op_state
3099 != FSSYNC_VolOpRunningUnknown);
3102 case FSSYNC_VolOpRunningOffline:
3103 /* mark the volume down */
3105 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3107 /* do not set V_offlineMessage here; we don't have ownership of
3108 * the volume (and probably do not have the header loaded), so we
3109 * can't alter the disk header */
3111 /* check to see if we should set the specialStatus flag */
3112 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3113 /* don't overwrite specialStatus if it was already set to
3114 * something else (e.g. VMOVED) */
3115 if (!vp->specialStatus) {
3116 vp->specialStatus = VBUSY;
3128 #endif /* AFS_DEMAND_ATTACH_FS */
3131 * volume attachment helper function.
3133 * @param[out] ec error code
3134 * @param[in] volumeId volume ID of the attaching volume
3135 * @param[in] path full path to the volume header .vol file
3136 * @param[in] partp disk partition object for the attaching partition
3137 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3138 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3139 * DAFS) should already be initialized
3140 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3141 * if there is a volume operation running for this volume
3142 * that should set the volume to VBUSY during its run. 0
3143 * otherwise. (see VVolOpSetVBusy_r)
3144 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3146 * @param[out] acheckedOut If we successfully checked-out the volume from
3147 * the fileserver (if we needed to), this is set
3148 * to 1, otherwise it is 0.
3150 * @return pointer to the semi-attached volume pointer
3151 * @retval NULL an error occurred (check value of *ec)
3152 * @retval vp volume successfully attaching
3154 * @pre no locks held
3156 * @post VOL_LOCK held
3159 attach2(Error * ec, VolumeId volumeId, char *path, struct DiskPartition64 *partp,
3160 Volume * vp, int isbusy, int mode, int *acheckedOut)
3162 /* have we read in the header successfully? */
3163 int read_header = 0;
3165 #ifdef AFS_DEMAND_ATTACH_FS
3166 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3170 /* in the case of an error, to what state should the volume be
3172 VolState error_state = VOL_STATE_ERROR;
3173 #endif /* AFS_DEMAND_ATTACH_FS */
3177 vp->vnodeIndex[vLarge].handle = NULL;
3178 vp->vnodeIndex[vSmall].handle = NULL;
3179 vp->diskDataHandle = NULL;
3180 vp->linkHandle = NULL;
3184 #ifdef AFS_DEMAND_ATTACH_FS
3185 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3187 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3190 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3191 #endif /* !AFS_DEMAND_ATTACH_FS */
3193 if (*ec == VNOVOL) {
3194 /* if the volume doesn't exist, skip straight to 'error' so we don't
3195 * request a salvage */
3196 goto unlocked_error;
3202 /* ensure that we don't override specialStatus if it was set to
3203 * something else (e.g. VMOVED) */
3204 if (isbusy && !vp->specialStatus) {
3205 vp->specialStatus = VBUSY;
3207 vp->shuttingDown = 0;
3208 vp->goingOffline = 0;
3210 #ifdef AFS_DEMAND_ATTACH_FS
3211 vp->stats.last_attach = FT_ApproxTime();
3212 vp->stats.attaches++;
3216 IncUInt64(&VStats.attaches);
3217 vp->cacheCheck = ++VolumeCacheCheck;
3218 /* just in case this ever rolls over */
3219 if (!vp->cacheCheck)
3220 vp->cacheCheck = ++VolumeCacheCheck;
3223 #ifdef AFS_DEMAND_ATTACH_FS
3224 V_attachFlags(vp) |= VOL_HDR_LOADED;
3225 vp->stats.last_hdr_load = vp->stats.last_attach;
3226 #endif /* AFS_DEMAND_ATTACH_FS */
3230 struct IndexFileHeader iHead;
3233 * We just read in the diskstuff part of the header. If the detailed
3234 * volume stats area has not yet been initialized, we should bzero the
3235 * area and mark it as initialized.
3237 if (!(V_stat_initialized(vp))) {
3238 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3239 V_stat_initialized(vp) = 1;
3242 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3243 (char *)&iHead, sizeof(iHead),
3244 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3247 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3252 struct IndexFileHeader iHead;
3254 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3255 (char *)&iHead, sizeof(iHead),
3256 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3259 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3263 #ifdef AFS_NAMEI_ENV
3265 struct versionStamp stamp;
3267 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3268 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3271 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3274 #endif /* AFS_NAMEI_ENV */
3276 #if defined(AFS_DEMAND_ATTACH_FS)
3277 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3279 if (!VCanScheduleSalvage()) {
3280 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3282 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3287 /* volume operation in progress */
3289 /* we have already transitioned the vp away from ATTACHING state, so we
3290 * can go right to the end of attach2, and we do not need to transition
3292 goto error_notbroken;
3294 #else /* AFS_DEMAND_ATTACH_FS */
3296 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3297 goto unlocked_error;
3299 #endif /* AFS_DEMAND_ATTACH_FS */
3301 if (V_needsSalvaged(vp)) {
3302 if (vp->specialStatus)
3303 vp->specialStatus = 0;
3305 #if defined(AFS_DEMAND_ATTACH_FS)
3306 if (!VCanScheduleSalvage()) {
3307 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3309 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3312 #else /* AFS_DEMAND_ATTACH_FS */
3314 #endif /* AFS_DEMAND_ATTACH_FS */
3320 vp->nextVnodeUnique = V_uniquifier(vp);
3322 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3323 if (!V_needsSalvaged(vp)) {
3324 V_needsSalvaged(vp) = 1;
3325 VUpdateVolume_r(ec, vp, 0);
3327 #if defined(AFS_DEMAND_ATTACH_FS)
3328 if (!VCanScheduleSalvage()) {
3329 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3331 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3334 #else /* AFS_DEMAND_ATTACH_FS */
3335 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3337 #endif /* AFS_DEMAND_ATTACH_FS */
3342 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3343 /* Only check destroyMe if we are the fileserver, since the
3344 * volserver et al sometimes need to work with volumes with
3345 * destroyMe set. Examples are 'temporary' volumes the
3346 * volserver creates, and when we create a volume (destroyMe
3347 * is set on creation; sometimes a separate volserver
3348 * transaction is created to clear destroyMe).
3351 #if defined(AFS_DEMAND_ATTACH_FS)
3352 /* schedule a salvage so the volume goes away on disk */
3353 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3354 VChangeState_r(vp, VOL_STATE_ERROR);
3357 #endif /* AFS_DEMAND_ATTACH_FS */
3358 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3363 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3364 #ifndef BITMAP_LATER
3365 if (programType == fileServer && VolumeWriteable(vp)) {
3367 for (i = 0; i < nVNODECLASSES; i++) {
3368 VGetBitmap_r(ec, vp, i);
3370 #ifdef AFS_DEMAND_ATTACH_FS
3371 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3373 #endif /* AFS_DEMAND_ATTACH_FS */
3374 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3380 #endif /* BITMAP_LATER */
3382 if (VInit >= 2 && V_needsCallback(vp)) {
3383 if (V_BreakVolumeCallbacks) {
3384 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3385 afs_printable_uint32_lu(V_id(vp)));
3386 V_needsCallback(vp) = 0;
3388 (*V_BreakVolumeCallbacks) (V_id(vp));
3391 VUpdateVolume_r(ec, vp, 0);
3393 #ifdef FSSYNC_BUILD_CLIENT
3394 else if (VCanUseFSSYNC()) {
3395 afs_int32 fsync_code;
3397 V_needsCallback(vp) = 0;
3399 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3403 V_needsCallback(vp) = 1;
3404 Log("Error trying to tell the fileserver to break callbacks for "
3405 "changed volume %lu; error code %ld\n",
3406 afs_printable_uint32_lu(V_id(vp)),
3407 afs_printable_int32_ld(fsync_code));
3409 VUpdateVolume_r(ec, vp, 0);
3412 #endif /* FSSYNC_BUILD_CLIENT */
3415 Log("VAttachVolume: error %d clearing needsCallback on volume "
3416 "%lu; needs salvage\n", (int)*ec,
3417 afs_printable_uint32_lu(V_id(vp)));
3418 #ifdef AFS_DEMAND_ATTACH_FS
3419 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3421 #else /* !AFS_DEMAND_ATTACH_FS */
3423 #endif /* !AFS_DEMAND_ATTACh_FS */
3428 if (programType == fileServer) {
3429 if (vp->specialStatus)
3430 vp->specialStatus = 0;
3431 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3432 V_inUse(vp) = fileServer;
3433 V_offlineMessage(vp)[0] = '\0';
3435 #ifdef AFS_DEMAND_ATTACH_FS
3436 /* check if the volume is actually usable. only do this for DAFS; for
3437 * non-DAFS, volumes that are not inService/blessed can still be
3438 * attached, even if clients cannot access them. this is relevant
3439 * because for non-DAFS, we try to attach the volume when e.g.
3440 * volserver gives us back then vol when its done with it, but
3441 * volserver may give us back a volume that is not inService/blessed. */
3445 /* Put the vol into PREATTACHED state, so if someone tries to
3446 * access it again, we try to attach, see that we're not blessed,
3447 * and give a VNOVOL error again. Putting it into UNATTACHED state
3448 * would result in a VOFFLINE error instead. */
3449 error_state = VOL_STATE_PREATTACHED;
3451 /* mimic e.g. GetVolume errors */
3452 if (!V_blessed(vp)) {
3453 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3454 FreeVolumeHeader(vp);
3455 } else if (!V_inService(vp)) {
3456 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3457 /* the volume is offline and should be unattached */
3459 error_state = VOL_STATE_UNATTACHED;
3460 FreeVolumeHeader(vp);
3462 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3464 error_state = VOL_STATE_ERROR;
3465 /* see if we can recover */
3466 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3471 #endif /* AFS_DEMAND_ATTACH_FS */
3473 #ifdef AFS_DEMAND_ATTACH_FS
3474 if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3475 V_inUse(vp) = programType;
3476 #endif /* AFS_DEMAND_ATTACH_FS */
3477 V_checkoutMode(vp) = mode;
3480 AddVolumeToHashTable(vp, vp->hashid);
3481 #ifdef AFS_DEMAND_ATTACH_FS
3482 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3485 if ((programType != fileServer) ||
3486 (V_inUse(vp) == fileServer)) {
3487 AddVolumeToVByPList_r(vp);
3489 VChangeState_r(vp, VOL_STATE_ATTACHED);
3491 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3500 #ifdef AFS_DEMAND_ATTACH_FS
3501 if (!VIsErrorState(V_attachState(vp))) {
3502 if (programType != fileServer && *ec == VNOVOL) {
3503 /* do not log anything in this case; it is common for
3504 * non-fileserver programs to fail here with VNOVOL, since that
3505 * is what happens when they simply try to use a volume, but that
3506 * volume doesn't exist. */
3508 } else if (VIsErrorState(error_state)) {
3509 Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3510 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3511 V_attachFlags(vp), *ec);
3513 VChangeState_r(vp, error_state);
3515 #endif /* AFS_DEMAND_ATTACH_FS */
3518 VReleaseVolumeHandles_r(vp);
3521 #ifdef AFS_DEMAND_ATTACH_FS
3523 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3524 /* The salvage could not be scheduled with the salvage server
3525 * due to a hard error. Reset the error code to prevent retry loops by
3527 if (*ec == VSALVAGING) {
3536 #else /* !AFS_DEMAND_ATTACH_FS */
3538 #endif /* !AFS_DEMAND_ATTACH_FS */
3542 /* Attach an existing volume.
3543 The volume also normally goes online at this time.
3544 An offline volume must be reattached to make it go online.
3548 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3552 retVal = VAttachVolume_r(ec, volumeId, mode);
3558 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3561 VGetVolumePath(ec, volumeId, &part, &name);
3565 vp = VGetVolume_r(&error, volumeId);
3567 opr_Assert(V_inUse(vp) == 0);
3568 VDetachVolume_r(ec, vp);
3572 return VAttachVolumeByName_r(ec, part, name, mode);
3575 /* Increment a reference count to a volume, sans context swaps. Requires
3576 * possibly reading the volume header in from the disk, since there's
3577 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3579 * N.B. This call can fail if we can't read in the header!! In this case
3580 * we still guarantee we won't context swap, but the ref count won't be
3581 * incremented (otherwise we'd violate the invariant).
3583 /* NOTE: with the demand attach fileserver extensions, the global lock
3584 * is dropped within VHold */
3585 #ifdef AFS_DEMAND_ATTACH_FS
3587 VHold_r(Volume * vp)
3591 VCreateReservation_r(vp);
3592 VWaitExclusiveState_r(vp);
3594 LoadVolumeHeader(&error, vp);
3596 VCancelReservation_r(vp);
3600 VCancelReservation_r(vp);
3603 #else /* AFS_DEMAND_ATTACH_FS */
3605 VHold_r(Volume * vp)
3609 LoadVolumeHeader(&error, vp);
3615 #endif /* AFS_DEMAND_ATTACH_FS */
3617 /**** volume timeout-related stuff ****/
3619 #ifdef AFS_PTHREAD_ENV
3621 static struct timespec *shutdown_timeout;
3622 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3625 VTimedOut(const struct timespec *ts)
3630 if (ts->tv_sec == 0) {
3631 /* short-circuit; this will have always timed out */
3635 code = gettimeofday(&tv, NULL);
3637 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3638 /* assume no timeout; failure mode is we just wait longer than normal
3639 * instead of returning errors when we shouldn't */
3643 if (tv.tv_sec < ts->tv_sec ||
3644 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3653 * Calculate an absolute timeout.
3655 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3656 * NULL, the memory is not touched
3657 * @param[in] timeout How long the timeout should be from now
3659 * @return timeout to use
3660 * @retval NULL no timeout; wait forever
3661 * @retval non-NULL the given value for "ts"
3665 static struct timespec *
3666 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3676 ts->tv_sec = ts->tv_nsec = 0;
3680 code = gettimeofday(&now, NULL);
3682 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3686 ts->tv_sec = now.tv_sec + timeout;
3687 ts->tv_nsec = now.tv_usec * 1000;
3693 * Initialize the shutdown_timeout global.
3696 VShutdownTimeoutInit(void)
3698 struct timespec *ts;
3700 ts = malloc(sizeof(*ts));
3702 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3704 if (!shutdown_timeout) {
3710 * Figure out the timeout that should be used for waiting for offline volumes.
3712 * @param[out] ats Storage space for a local timeout value if needed
3714 * @return The timeout value that should be used
3715 * @retval NULL No timeout; wait forever for offlining volumes
3716 * @retval non-NULL A pointer to the absolute time that should be used as
3717 * the deadline for waiting for offlining volumes.
3719 * @note If we return non-NULL, the pointer we return may or may not be the
3722 static const struct timespec *
3723 VOfflineTimeout(struct timespec *ats)
3725 if (vol_shutting_down) {
3726 opr_Verify(pthread_once(&shutdown_timeout_once,
3727 VShutdownTimeoutInit) == 0);
3728 return shutdown_timeout;
3730 return VCalcTimeout(ats, vol_opts.offline_timeout);
3734 #else /* AFS_PTHREAD_ENV */
3736 /* Waiting a certain amount of time for offlining volumes is not supported
3737 * for LWP due to a lack of primitives. So, we never time out */
3738 # define VTimedOut(x) (0)
3739 # define VOfflineTimeout(x) (NULL)
3741 #endif /* !AFS_PTHREAD_ENV */
3744 VIsGoingOffline_r(struct Volume *vp)
3748 if (vp->goingOffline) {
3749 if (vp->specialStatus) {
3750 code = vp->specialStatus;
3751 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3762 * Tell the caller if a volume is waiting to go offline.
3764 * @param[in] vp The volume we want to know about
3766 * @return volume status
3767 * @retval 0 volume is not waiting to go offline, go ahead and use it
3768 * @retval nonzero volume is waiting to offline, and give the returned code
3769 * as an error to anyone accessing the volume
3771 * @pre VOL_LOCK is NOT held
3772 * @pre caller holds a heavyweight reference on vp
3775 VIsGoingOffline(struct Volume *vp)
3780 code = VIsGoingOffline_r(vp);
3787 * Register an RX call with a volume.
3789 * @param[inout] ec Error code; if unset when passed in, may be set if
3790 * the volume starts going offline
3791 * @param[out] client_ec @see GetVolume
3792 * @param[in] vp Volume struct
3793 * @param[in] cbv VCallByVol struct containing the RX call to register
3795 * @pre VOL_LOCK held
3796 * @pre caller holds heavy ref on vp
3801 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3804 #ifdef AFS_DEMAND_ATTACH_FS
3806 /* just in case the volume started going offline after we got the
3807 * reference to it... otherwise, if the volume started going
3808 * offline right at the end of GetVolume(), we might race with the
3809 * RX call scanner, and return success and add our cbv to the
3810 * rx_call_list _after_ the scanner has scanned the list. */
3811 *ec = VIsGoingOffline_r(vp);
3817 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3818 VWaitStateChange_r(vp);
3820 #endif /* AFS_DEMAND_ATTACH_FS */
3822 queue_Prepend(&vp->rx_call_list, cbv);
3827 * Deregister an RX call with a volume.
3829 * @param[in] vp Volume struct
3830 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3832 * @pre VOL_LOCK held
3833 * @pre caller holds heavy ref on vp
3838 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3840 if (cbv && queue_IsOnQueue(cbv)) {
3841 #ifdef AFS_DEMAND_ATTACH_FS
3842 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3843 VWaitStateChange_r(vp);
3845 #endif /* AFS_DEMAND_ATTACH_FS */
3851 /***************************************************/
3852 /* get and put volume routines */
3853 /***************************************************/
3856 * put back a heavyweight reference to a volume object.
3858 * @param[in] vp volume object pointer
3860 * @pre VOL_LOCK held
3862 * @post heavyweight volume reference put back.
3863 * depending on state, volume may have been taken offline,
3864 * detached, salvaged, freed, etc.
3866 * @internal volume package internal use only
3869 VPutVolume_r(Volume * vp)
3871 opr_Verify(--vp->nUsers >= 0);
3872 if (vp->nUsers == 0) {
3874 ReleaseVolumeHeader(vp->header);
3875 #ifdef AFS_DEMAND_ATTACH_FS
3876 if (!VCheckDetach(vp)) {
3880 #else /* AFS_DEMAND_ATTACH_FS */
3882 #endif /* AFS_DEMAND_ATTACH_FS */
3887 VPutVolume(Volume * vp)
3895 * Puts a volume reference obtained with VGetVolumeWithCall.
3897 * @param[in] vp Volume struct
3898 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3900 * @pre VOL_LOCK is NOT held
3903 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3906 VDeregisterCall_r(vp, cbv);
3911 /* Get a pointer to an attached volume. The pointer is returned regardless
3912 of whether or not the volume is in service or on/off line. An error
3913 code, however, is returned with an indication of the volume's status */
3915 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3919 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3925 * Get a volume reference associated with an RX call.
3927 * @param[out] ec @see GetVolume
3928 * @param[out] client_ec @see GetVolume
3929 * @param[in] volumeId @see GetVolume
3930 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3931 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3932 * with an error if the volume is going offline.
3933 * @param[in] cbv Contains an RX call to be associated with this volume
3934 * reference. This call may be interrupted if the volume is
3935 * requested to go offline while we hold a ref on it. Give NULL
3936 * to not associate an RX call with this reference.
3938 * @return @see GetVolume
3940 * @note for LWP builds, ts must be NULL
3942 * @note A reference obtained with this function MUST be put back with
3943 * VPutVolumeWithCall
3946 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3947 const struct timespec *ts, struct VCallByVol *cbv)
3951 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3952 VRegisterCall_r(ec, client_ec, retVal, cbv);
3958 VGetVolume_r(Error * ec, VolumeId volumeId)
3960 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3963 /* try to get a volume we've previously looked up */
3964 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3966 VGetVolumeByVp_r(Error * ec, Volume * vp)
3968 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3972 * private interface for getting a volume handle
3974 * @param[out] ec error code (0 if no error)
3975 * @param[out] client_ec wire error code to be given to clients
3976 * @param[in] volumeId ID of the volume we want
3977 * @param[in] hint optional hint for hash lookups, or NULL
3978 * @param[in] timeout absolute deadline for waiting for the volume to go
3979 * offline, if it is going offline. NULL to wait forever.
3981 * @return a volume handle for the specified volume
3982 * @retval NULL an error occurred, or the volume is in such a state that
3983 * we cannot load a header or return any volume struct
3985 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3987 * @note 'timeout' is only checked if the volume is actually going offline; so
3988 * if you pass timeout->tv_sec = 0, this will exhibit typical
3989 * nonblocking behavior.
3991 * @note for LWP builds, 'timeout' must be NULL
3994 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
3995 const struct timespec *timeout)
3998 #ifdef AFS_DEMAND_ATTACH_FS
3999 Volume *avp, * rvp = hint;
4003 * if VInit is zero, the volume package dynamic
4004 * data structures have not been initialized yet,
4005 * and we must immediately return an error
4011 *client_ec = VOFFLINE;
4016 #ifdef AFS_DEMAND_ATTACH_FS
4018 VCreateReservation_r(rvp);
4020 #endif /* AFS_DEMAND_ATTACH_FS */
4027 vp = VLookupVolume_r(ec, volumeId, vp);
4033 #ifdef AFS_DEMAND_ATTACH_FS
4034 if (rvp && (rvp != vp)) {
4035 /* break reservation on old vp */
4036 VCancelReservation_r(rvp);
4039 #endif /* AFS_DEMAND_ATTACH_FS */
4043 /* Until we have reached an initialization level of 2
4044 * we don't know whether this volume exists or not.
4045 * We can't sleep and retry later because before a volume
4046 * is attached, the caller tries to get it first. Just
4047 * return VOFFLINE and the caller can choose whether to
4048 * retry the command or not. */
4057 IncUInt64(&VStats.hdr_gets);
4059 #ifdef AFS_DEMAND_ATTACH_FS
4060 /* block if someone else is performing an exclusive op on this volume */
4063 VCreateReservation_r(rvp);
4065 VWaitExclusiveState_r(vp);
4067 /* short circuit with VNOVOL in the following circumstances:
4070 * - VOL_STATE_SHUTTING_DOWN
4072 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4073 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4080 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4081 * VNOVOL for VOL_STATE_DELETED
4083 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4084 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4085 (V_attachState(vp) == VOL_STATE_DELETED)) {
4086 if (vp->specialStatus) {
4087 *ec = vp->specialStatus;
4088 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4097 /* allowable states:
4104 if (vp->salvage.requested) {
4105 VUpdateSalvagePriority_r(vp);
4108 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4109 if (vp->specialStatus) {
4110 *ec = vp->specialStatus;
4114 avp = VAttachVolumeByVp_r(ec, vp, 0);
4117 /* VAttachVolumeByVp_r can return a pointer
4118 * != the vp passed to it under certain
4119 * conditions; make sure we don't leak
4120 * reservations if that happens */
4122 VCancelReservation_r(rvp);
4124 VCreateReservation_r(rvp);
4135 if (vp->specialStatus) {
4136 *ec = vp->specialStatus;
4141 if (vp->specialStatus) {
4142 *ec = vp->specialStatus;
4155 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4157 /* see CheckVnode() in afsfileprocs.c for an explanation
4158 * of this error code logic */
4159 afs_uint32 now = FT_ApproxTime();
4160 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4163 *client_ec = VRESTARTING;
4171 if (VIsErrorState(V_attachState(vp))) {
4172 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4173 * it, or transition it out of that state */
4182 * this test MUST happen after VAttachVolymeByVp, so we have no
4183 * conflicting vol op. (attach2 would have errored out if we had one;
4184 * specifically attach_check_vop must have detected a conflicting vop)
4186 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4188 #endif /* AFS_DEMAND_ATTACH_FS */
4190 LoadVolumeHeader(ec, vp);
4192 /* Only log the error if it was a totally unexpected error. Simply
4193 * a missing inode is likely to be caused by the volume being deleted */
4194 if (errno != ENXIO || GetLogLevel() != 0)
4195 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4196 afs_printable_VolumeId_lu(vp->hashid));
4197 #ifdef AFS_DEMAND_ATTACH_FS
4198 if (VCanScheduleSalvage()) {
4199 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4204 #else /* AFS_DEMAND_ATTACH_FS */
4207 #endif /* AFS_DEMAND_ATTACH_FS */
4211 if (vp->shuttingDown) {
4217 if (programType == fileServer) {
4218 if (vp->goingOffline) {
4219 if (timeout && VTimedOut(timeout)) {
4220 /* we've timed out; don't wait for the vol */
4222 #ifdef AFS_DEMAND_ATTACH_FS
4223 /* wait for the volume to go offline */
4224 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4225 VTimedWaitStateChange_r(vp, timeout, NULL);
4227 #elif defined(AFS_PTHREAD_ENV)
4228 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4229 #else /* AFS_PTHREAD_ENV */
4230 /* LWP has no timed wait, so the caller better not be
4232 opr_Assert(!timeout);
4233 LWP_WaitProcess(VPutVolume);
4234 #endif /* AFS_PTHREAD_ENV */
4238 if (vp->specialStatus) {
4239 *ec = vp->specialStatus;
4240 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4242 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4249 #ifdef AFS_DEMAND_ATTACH_FS
4250 /* if no error, bump nUsers */
4253 VLRU_UpdateAccess_r(vp);
4256 VCancelReservation_r(rvp);
4259 if (client_ec && !*client_ec) {
4262 #else /* AFS_DEMAND_ATTACH_FS */
4263 /* if no error, bump nUsers */
4270 #endif /* AFS_DEMAND_ATTACH_FS */
4273 opr_Assert(vp || *ec);
4278 /***************************************************/
4279 /* Volume offline/detach routines */
4280 /***************************************************/
4282 /* caller MUST hold a heavyweight ref on vp */
4283 #ifdef AFS_DEMAND_ATTACH_FS
4285 VTakeOffline_r(Volume * vp)
4289 opr_Assert(vp->nUsers > 0);
4290 opr_Assert(programType == fileServer);
4292 VCreateReservation_r(vp);
4293 VWaitExclusiveState_r(vp);
4295 vp->goingOffline = 1;
4296 V_needsSalvaged(vp) = 1;
4298 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4299 VCancelReservation_r(vp);
4301 #else /* AFS_DEMAND_ATTACH_FS */
4303 VTakeOffline_r(Volume * vp)
4305 opr_Assert(vp->nUsers > 0);
4306 opr_Assert(programType == fileServer);
4308 vp->goingOffline = 1;
4309 V_needsSalvaged(vp) = 1;
4311 #endif /* AFS_DEMAND_ATTACH_FS */
4314 VTakeOffline(Volume * vp)
4322 * force a volume offline.
4324 * @param[in] vp volume object pointer
4325 * @param[in] flags flags (see note below)
4327 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4328 * used when VUpdateVolume_r needs to call VForceOffline_r
4329 * (which in turn would normally call VUpdateVolume_r)
4331 * @see VUpdateVolume_r
4333 * @pre VOL_LOCK must be held.
4334 * for DAFS, caller must hold ref.
4336 * @note for DAFS, it _is safe_ to call this function from an
4339 * @post needsSalvaged flag is set.
4340 * for DAFS, salvage is requested.
4341 * no further references to the volume through the volume
4342 * package will be honored.
4343 * all file descriptor and vnode caches are invalidated.
4345 * @warning this is a heavy-handed interface. it results in
4346 * a volume going offline regardless of the current
4347 * reference count state.
4349 * @internal volume package internal use only
4352 VForceOffline_r(Volume * vp, int flags)
4356 #ifdef AFS_DEMAND_ATTACH_FS
4357 VChangeState_r(vp, VOL_STATE_ERROR);
4362 strcpy(V_offlineMessage(vp),
4363 "Forced offline due to internal error: volume needs to be salvaged");
4364 Log("Volume %" AFS_VOLID_FMT " forced offline: it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4367 vp->goingOffline = 0;
4368 V_needsSalvaged(vp) = 1;
4369 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4370 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4373 #ifdef AFS_DEMAND_ATTACH_FS
4374 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4375 #endif /* AFS_DEMAND_ATTACH_FS */
4377 #ifdef AFS_PTHREAD_ENV
4378 opr_cv_broadcast(&vol_put_volume_cond);
4379 #else /* AFS_PTHREAD_ENV */
4380 LWP_NoYieldSignal(VPutVolume);
4381 #endif /* AFS_PTHREAD_ENV */
4383 VReleaseVolumeHandles_r(vp);
4387 * force a volume offline.
4389 * @param[in] vp volume object pointer
4391 * @see VForceOffline_r
4394 VForceOffline(Volume * vp)
4397 VForceOffline_r(vp, 0);
4402 * Iterate over the RX calls associated with a volume, and interrupt them.
4404 * @param[in] vp The volume whose RX calls we want to scan
4406 * @pre VOL_LOCK held
4409 VScanCalls_r(struct Volume *vp)
4411 struct VCallByVol *cbv, *ncbv;
4413 #ifdef AFS_DEMAND_ATTACH_FS
4414 VolState state_save;
4417 if (queue_IsEmpty(&vp->rx_call_list))
4418 return; /* no calls to interrupt */
4419 if (!vol_opts.interrupt_rxcall)
4420 return; /* we have no function with which to interrupt calls */
4421 err = VIsGoingOffline_r(vp);
4423 return; /* we're not going offline anymore */
4425 #ifdef AFS_DEMAND_ATTACH_FS
4426 VWaitExclusiveState_r(vp);
4427 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4429 #endif /* AFS_DEMAND_ATTACH_FS */
4431 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4432 if (GetLogLevel() != 0) {
4433 struct rx_peer *peer;
4435 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4437 Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4438 "from it; kicking client off with error %ld\n",
4439 afs_printable_VolumeId_lu(vp->hashid),
4440 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4441 (unsigned) ntohs(rx_PortOf(peer)),
4444 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4447 #ifdef AFS_DEMAND_ATTACH_FS
4449 VChangeState_r(vp, state_save);
4450 #endif /* AFS_DEMAND_ATTACH_FS */
4453 #ifdef AFS_DEMAND_ATTACH_FS
4455 * Wait for a vp to go offline.
4457 * @param[out] ec 1 if a salvage on the volume has been requested and
4458 * salvok == 0, 0 otherwise
4459 * @param[in] vp The volume to wait for
4460 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4461 * has been requested to salvage. Otherwise we keep waiting
4462 * until the volume has gone offline.
4464 * @pre VOL_LOCK held
4465 * @pre caller holds a lightweight ref on vp
4470 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4472 struct timespec timeout_ts;
4473 const struct timespec *ts;
4476 ts = VOfflineTimeout(&timeout_ts);
4480 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4481 if (!salvok && vp->salvage.requested) {
4485 VTimedWaitStateChange_r(vp, ts, &timedout);
4488 /* we didn't time out, so the volume must be offline, so we're done */
4492 /* If we got here, we timed out waiting for the volume to go offline.
4493 * Kick off the accessing RX calls and wait again */
4497 while (!VIsOfflineState(V_attachState(vp))) {
4498 if (!salvok && vp->salvage.requested) {
4503 VWaitStateChange_r(vp);
4507 #else /* AFS_DEMAND_ATTACH_FS */
4510 * Wait for a volume to go offline.
4512 * @pre VOL_LOCK held
4514 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4517 VWaitForOffline_r(Error *ec, VolumeId volid)
4520 const struct timespec *ts;
4521 #ifdef AFS_PTHREAD_ENV
4522 struct timespec timeout_ts;
4525 ts = VOfflineTimeout(&timeout_ts);
4527 vp = GetVolume(ec, NULL, volid, NULL, ts);
4529 /* error occurred so bad that we can't even get a vp; we have no
4530 * information on the vol so we don't know whether to wait, so just
4534 if (!VIsGoingOffline_r(vp)) {
4535 /* volume is no longer going offline, so we're done */
4540 /* If we got here, we timed out waiting for the volume to go offline.
4541 * Kick off the accessing RX calls and wait again */
4547 vp = VGetVolume_r(ec, volid);
4549 /* In case it was reattached... */
4553 #endif /* !AFS_DEMAND_ATTACH_FS */
4555 /* The opposite of VAttachVolume. The volume header is written to disk, with
4556 the inUse bit turned off. A copy of the header is maintained in memory,
4557 however (which is why this is VOffline, not VDetach).
4560 VOffline_r(Volume * vp, char *message)
4563 #ifndef AFS_DEMAND_ATTACH_FS
4564 VolumeId vid = V_id(vp);
4567 opr_Assert(programType != volumeUtility && programType != volumeServer);
4572 if (V_offlineMessage(vp)[0] == '\0')
4573 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4574 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4576 vp->goingOffline = 1;
4577 #ifdef AFS_DEMAND_ATTACH_FS
4578 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4579 VCreateReservation_r(vp);
4581 VWaitForOfflineByVp_r(&error, vp, 1);
4582 VCancelReservation_r(vp);
4583 #else /* AFS_DEMAND_ATTACH_FS */
4585 VWaitForOffline_r(&error, vid);
4586 #endif /* AFS_DEMAND_ATTACH_FS */
4589 #ifdef AFS_DEMAND_ATTACH_FS
4591 * Take a volume offline in order to perform a volume operation.
4593 * @param[inout] ec address in which to store error code
4594 * @param[in] vp volume object pointer
4595 * @param[in] message volume offline status message
4598 * - VOL_LOCK is held
4599 * - caller MUST hold a heavyweight ref on vp
4602 * - volume is taken offline
4603 * - if possible, volume operation is promoted to running state
4604 * - on failure, *ec is set to nonzero
4606 * @note Although this function does not return any value, it may
4607 * still fail to promote our pending volume operation to
4608 * a running state. Any caller MUST check the value of *ec,
4609 * and MUST NOT blindly assume success.
4611 * @warning if the caller does not hold a lightweight ref on vp,
4612 * then it MUST NOT reference vp after this function
4613 * returns to the caller.
4615 * @internal volume package internal use only
4618 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4621 opr_Assert(vp->pending_vol_op);
4627 if (V_offlineMessage(vp)[0] == '\0')
4628 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4629 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4631 vp->goingOffline = 1;
4632 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4633 VCreateReservation_r(vp);
4636 if (vp->pending_vol_op->com.programType != salvageServer) {
4637 /* do not give corrupted volumes to the volserver */
4642 VWaitForOfflineByVp_r(ec, vp, salvok);
4644 VCancelReservation_r(vp);
4646 #endif /* AFS_DEMAND_ATTACH_FS */
4649 VOffline(Volume * vp, char *message)
4652 VOffline_r(vp, message);
4656 /* This gets used for the most part by utility routines that don't want
4657 * to keep all the volume headers around. Generally, the file server won't
4658 * call this routine, because then the offline message in the volume header
4659 * (or other information) won't be available to clients. For NAMEI, also
4660 * close the file handles. However, the fileserver does call this during
4661 * an attach following a volume operation.
4664 VDetachVolume_r(Error * ec, Volume * vp)
4666 #ifdef FSSYNC_BUILD_CLIENT
4668 struct DiskPartition64 *tpartp;
4669 int notifyServer = 0;
4670 int useDone = FSYNC_VOL_ON;
4672 if (VCanUseFSSYNC()) {
4673 notifyServer = vp->needsPutBack;
4674 if (V_destroyMe(vp) == DESTROY_ME)
4675 useDone = FSYNC_VOL_LEAVE_OFF;
4676 # ifdef AFS_DEMAND_ATTACH_FS
4677 else if (!V_blessed(vp) || !V_inService(vp))
4678 useDone = FSYNC_VOL_LEAVE_OFF;
4681 # ifdef AFS_DEMAND_ATTACH_FS
4682 if (V_needsSalvaged(vp)) {
4684 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4687 tpartp = vp->partition;
4689 #endif /* FSSYNC_BUILD_CLIENT */
4691 *ec = 0; /* always "succeeds" */
4692 DeleteVolumeFromHashTable(vp);
4693 vp->shuttingDown = 1;
4694 #ifdef AFS_DEMAND_ATTACH_FS
4695 DeleteVolumeFromVByPList_r(vp);
4697 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4699 if (programType != fileServer)
4701 #endif /* AFS_DEMAND_ATTACH_FS */
4703 /* Will be detached sometime in the future--this is OK since volume is offline */
4705 /* XXX the following code should really be moved to VCheckDetach() since the volume
4706 * is not technically detached until the refcounts reach zero
4708 #ifdef FSSYNC_BUILD_CLIENT
4709 if (VCanUseFSSYNC() && notifyServer) {
4710 if (notifyServer == VOL_PUTBACK_DELETE) {
4711 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4712 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4713 * to signify a deleted volume. */
4714 useDone = FSYNC_VOL_DONE;
4717 * Note: The server is not notified in the case of a bogus volume
4718 * explicitly to make it possible to create a volume, do a partial
4719 * restore, then abort the operation without ever putting the volume
4720 * online. This is essential in the case of a volume move operation
4721 * between two partitions on the same server. In that case, there
4722 * would be two instances of the same volume, one of them bogus,
4723 * which the file server would attempt to put on line
4725 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4727 #endif /* FSSYNC_BUILD_CLIENT */
4731 VDetachVolume(Error * ec, Volume * vp)
4734 VDetachVolume_r(ec, vp);
4739 /***************************************************/
4740 /* Volume fd/inode handle closing routines */
4741 /***************************************************/
4743 /* For VDetachVolume, we close all cached file descriptors, but keep
4744 * the Inode handles in case we need to read from a busy volume.
4746 /* for demand attach, caller MUST hold ref count on vp */
4748 VCloseVolumeHandles_r(Volume * vp)
4750 #ifdef AFS_DEMAND_ATTACH_FS
4751 VolState state_save;
4753 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4758 DFlushVolume(vp->hashid);
4760 #ifdef AFS_DEMAND_ATTACH_FS
4764 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4765 VCloseVnodeFiles_r(vp);
4767 #ifdef AFS_DEMAND_ATTACH_FS
4771 /* Too time consuming and unnecessary for the volserver */
4772 if (programType == fileServer) {
4773 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4774 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4775 IH_CONDSYNC(vp->diskDataHandle);
4776 #ifdef AFS_NAMEI_ENV
4777 IH_CONDSYNC(vp->linkHandle);
4778 #endif /* AFS_NAMEI_ENV */
4781 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4782 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4783 IH_REALLYCLOSE(vp->diskDataHandle);
4784 IH_REALLYCLOSE(vp->linkHandle);
4786 #ifdef AFS_DEMAND_ATTACH_FS
4787 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4792 VChangeState_r(vp, state_save);
4796 /* For both VForceOffline and VOffline, we close all relevant handles.
4797 * For VOffline, if we re-attach the volume, the files may possible be
4798 * different than before.
4800 /* for demand attach, caller MUST hold a ref count on vp */
4802 VReleaseVolumeHandles_r(Volume * vp)
4804 #ifdef AFS_DEMAND_ATTACH_FS
4805 VolState state_save;
4807 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4812 DFlushVolume(vp->hashid);
4814 #ifdef AFS_DEMAND_ATTACH_FS
4818 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4820 #ifdef AFS_DEMAND_ATTACH_FS
4824 /* Too time consuming and unnecessary for the volserver */
4825 if (programType == fileServer) {
4826 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4827 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4828 IH_CONDSYNC(vp->diskDataHandle);
4829 #ifdef AFS_NAMEI_ENV
4830 IH_CONDSYNC(vp->linkHandle);
4831 #endif /* AFS_NAMEI_ENV */
4834 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4835 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4836 IH_RELEASE(vp->diskDataHandle);
4837 IH_RELEASE(vp->linkHandle);
4839 #ifdef AFS_DEMAND_ATTACH_FS
4840 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4845 VChangeState_r(vp, state_save);
4850 /***************************************************/
4851 /* Volume write and fsync routines */
4852 /***************************************************/
4855 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4857 #ifdef AFS_DEMAND_ATTACH_FS
4858 VolState state_save;
4860 if (flags & VOL_UPDATE_WAIT) {
4861 VCreateReservation_r(vp);
4862 VWaitExclusiveState_r(vp);
4867 if (programType == fileServer) {
4869 V_uniquifier(vp) = V_nextVnodeUnique(vp);
4872 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4873 if (V_uniquifier(vp) < V_nextVnodeUnique(vp)) {
4874 /* uniquifier rolled over; reset the counters */
4875 V_nextVnodeUnique(vp) = 2; /* 1 is reserved for the root vnode */
4877 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4882 #ifdef AFS_DEMAND_ATTACH_FS
4883 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4887 WriteVolumeHeader_r(ec, vp);
4889 #ifdef AFS_DEMAND_ATTACH_FS
4891 VChangeState_r(vp, state_save);
4892 if (flags & VOL_UPDATE_WAIT) {
4893 VCancelReservation_r(vp);
4898 Log("VUpdateVolume: error updating volume header, volume %" AFS_VOLID_FMT " (%s)\n",
4899 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
4900 /* try to update on-disk header,
4901 * while preventing infinite recursion */
4902 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4903 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4909 VUpdateVolume(Error * ec, Volume * vp)
4912 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4917 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4921 #ifdef AFS_DEMAND_ATTACH_FS
4922 VolState state_save;
4925 if (flags & VOL_SYNC_WAIT) {
4926 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4928 VUpdateVolume_r(ec, vp, 0);
4931 #ifdef AFS_DEMAND_ATTACH_FS
4932 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4935 fdP = IH_OPEN(V_diskDataHandle(vp));
4936 opr_Assert(fdP != NULL);
4937 code = FDH_SYNC(fdP);
4938 opr_Assert(code == 0);
4940 #ifdef AFS_DEMAND_ATTACH_FS
4942 VChangeState_r(vp, state_save);
4948 VSyncVolume(Error * ec, Volume * vp)
4951 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4956 /***************************************************/
4957 /* Volume dealloaction routines */
4958 /***************************************************/
4960 #ifdef AFS_DEMAND_ATTACH_FS
4962 FreeVolume(Volume * vp)
4964 /* free the heap space, iff it's safe.
4965 * otherwise, pull it out of the hash table, so it
4966 * will get deallocated when all refs to it go away */
4967 if (!VCheckFree(vp)) {
4968 DeleteVolumeFromHashTable(vp);
4969 DeleteVolumeFromVByPList_r(vp);
4971 /* make sure we invalidate the header cache entry */
4972 FreeVolumeHeader(vp);
4975 #endif /* AFS_DEMAND_ATTACH_FS */
4978 ReallyFreeVolume(Volume * vp)
4983 #ifdef AFS_DEMAND_ATTACH_FS
4985 VChangeState_r(vp, VOL_STATE_FREED);
4986 if (vp->pending_vol_op)
4987 free(vp->pending_vol_op);
4988 #endif /* AFS_DEMAND_ATTACH_FS */
4989 for (i = 0; i < nVNODECLASSES; i++)
4990 if (vp->vnodeIndex[i].bitmap)
4991 free(vp->vnodeIndex[i].bitmap);
4992 FreeVolumeHeader(vp);
4993 #ifndef AFS_DEMAND_ATTACH_FS
4994 DeleteVolumeFromHashTable(vp);
4995 #endif /* AFS_DEMAND_ATTACH_FS */
4999 /* check to see if we should shutdown this volume
5000 * returns 1 if volume was freed, 0 otherwise */
5001 #ifdef AFS_DEMAND_ATTACH_FS
5003 VCheckDetach(Volume * vp)
5008 if (vp->nUsers || vp->nWaiters)
5011 if (vp->shuttingDown) {
5013 if ((programType != fileServer) &&
5014 (V_inUse(vp) == programType) &&
5015 ((V_checkoutMode(vp) == V_VOLUPD) ||
5016 (V_checkoutMode(vp) == V_SECRETLY) ||
5017 ((V_checkoutMode(vp) == V_CLONE) &&
5018 (VolumeWriteable(vp))))) {
5020 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5022 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " "
5023 "failed with errno %d\n", afs_printable_VolumeId_lu(vp->hashid), errno);
5026 VReleaseVolumeHandles_r(vp);
5028 ReallyFreeVolume(vp);
5029 if (programType == fileServer) {
5030 opr_cv_broadcast(&vol_put_volume_cond);
5035 #else /* AFS_DEMAND_ATTACH_FS */
5037 VCheckDetach(Volume * vp)
5045 if (vp->shuttingDown) {
5047 if ((programType != fileServer) &&
5048 (V_inUse(vp) == programType) &&
5049 ((V_checkoutMode(vp) == V_VOLUPD) ||
5050 (V_checkoutMode(vp) == V_SECRETLY) ||
5051 ((V_checkoutMode(vp) == V_CLONE) &&
5052 (VolumeWriteable(vp))))) {
5054 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5056 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " failed with errno %d\n",
5057 afs_printable_VolumeId_lu(vp->hashid), errno);
5060 VReleaseVolumeHandles_r(vp);
5061 ReallyFreeVolume(vp);
5062 if (programType == fileServer) {
5063 #if defined(AFS_PTHREAD_ENV)
5064 opr_cv_broadcast(&vol_put_volume_cond);
5065 #else /* AFS_PTHREAD_ENV */
5066 LWP_NoYieldSignal(VPutVolume);
5067 #endif /* AFS_PTHREAD_ENV */
5072 #endif /* AFS_DEMAND_ATTACH_FS */
5074 /* check to see if we should offline this volume
5075 * return 1 if volume went offline, 0 otherwise */
5076 #ifdef AFS_DEMAND_ATTACH_FS
5078 VCheckOffline(Volume * vp)
5082 if (vp->goingOffline && !vp->nUsers) {
5084 opr_Assert(programType == fileServer);
5085 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5086 (V_attachState(vp) != VOL_STATE_FREED) &&
5087 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5088 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5089 (V_attachState(vp) != VOL_STATE_DELETED));
5093 * VOL_STATE_GOING_OFFLINE
5094 * VOL_STATE_SHUTTING_DOWN
5095 * VIsErrorState(V_attachState(vp))
5096 * VIsExclusiveState(V_attachState(vp))
5099 VCreateReservation_r(vp);
5100 VChangeState_r(vp, VOL_STATE_OFFLINING);
5103 /* must clear the goingOffline flag before we drop the glock */
5104 vp->goingOffline = 0;
5109 /* perform async operations */
5110 VUpdateVolume_r(&error, vp, 0);
5111 VCloseVolumeHandles_r(vp);
5113 if (GetLogLevel() != 0) {
5114 if (V_offlineMessage(vp)[0]) {
5115 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5116 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5117 V_offlineMessage(vp));
5119 Log("VOffline: Volume %lu (%s) is now offline\n",
5120 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5124 /* invalidate the volume header cache entry */
5125 FreeVolumeHeader(vp);
5127 /* if nothing changed state to error or salvaging,
5128 * drop state to unattached */
5129 if (!VIsErrorState(V_attachState(vp))) {
5130 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5132 VCancelReservation_r(vp);
5133 /* no usage of vp is safe beyond this point */
5137 #else /* AFS_DEMAND_ATTACH_FS */
5139 VCheckOffline(Volume * vp)
5143 if (vp->goingOffline && !vp->nUsers) {
5145 opr_Assert(programType == fileServer);
5148 vp->goingOffline = 0;
5150 VUpdateVolume_r(&error, vp, 0);
5151 VCloseVolumeHandles_r(vp);
5152 if (GetLogLevel() != 0) {
5153 if (V_offlineMessage(vp)[0]) {
5154 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5155 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5156 V_offlineMessage(vp));
5158 Log("VOffline: Volume %lu (%s) is now offline\n",
5159 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5162 FreeVolumeHeader(vp);
5163 #ifdef AFS_PTHREAD_ENV
5164 opr_cv_broadcast(&vol_put_volume_cond);
5165 #else /* AFS_PTHREAD_ENV */
5166 LWP_NoYieldSignal(VPutVolume);
5167 #endif /* AFS_PTHREAD_ENV */
5171 #endif /* AFS_DEMAND_ATTACH_FS */
5173 /***************************************************/
5174 /* demand attach fs ref counting routines */
5175 /***************************************************/
5177 #ifdef AFS_DEMAND_ATTACH_FS
5178 /* the following two functions handle reference counting for
5179 * asynchronous operations on volume structs.
5181 * their purpose is to prevent a VDetachVolume or VShutdown
5182 * from free()ing the Volume struct during an async i/o op */
5184 /* register with the async volume op ref counter */
5185 /* VCreateReservation_r moved into inline code header because it
5186 * is now needed in vnode.c -- tkeiser 11/20/2007
5190 * decrement volume-package internal refcount.
5192 * @param vp volume object pointer
5194 * @internal volume package internal use only
5197 * @arg VOL_LOCK is held
5198 * @arg lightweight refcount held
5200 * @post volume waiters refcount is decremented; volume may
5201 * have been deallocated/shutdown/offlined/salvaged/
5202 * whatever during the process
5204 * @warning once you have tossed your last reference (you can acquire
5205 * lightweight refs recursively) it is NOT SAFE to reference
5206 * a volume object pointer ever again
5208 * @see VCreateReservation_r
5210 * @note DEMAND_ATTACH_FS only
5213 VCancelReservation_r(Volume * vp)
5215 opr_Verify(--vp->nWaiters >= 0);
5216 if (vp->nWaiters == 0) {
5218 if (!VCheckDetach(vp)) {
5225 /* check to see if we should free this volume now
5226 * return 1 if volume was freed, 0 otherwise */
5228 VCheckFree(Volume * vp)
5231 if ((vp->nUsers == 0) &&
5232 (vp->nWaiters == 0) &&
5233 !(V_attachFlags(vp) & (VOL_IN_HASH |
5237 ReallyFreeVolume(vp);
5242 #endif /* AFS_DEMAND_ATTACH_FS */
5245 /***************************************************/
5246 /* online volume operations routines */
5247 /***************************************************/
5249 #ifdef AFS_DEMAND_ATTACH_FS
5251 * register a volume operation on a given volume.
5253 * @param[in] vp volume object
5254 * @param[in] vopinfo volume operation info object
5256 * @pre VOL_LOCK is held
5258 * @post volume operation info object attached to volume object.
5259 * volume operation statistics updated.
5261 * @note by "attached" we mean a copy of the passed in object is made
5263 * @internal volume package internal use only
5266 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5268 FSSYNC_VolOp_info * info;
5270 /* attach a vol op info node to the volume struct */
5271 info = malloc(sizeof(FSSYNC_VolOp_info));
5272 opr_Assert(info != NULL);
5273 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5274 vp->pending_vol_op = info;
5277 vp->stats.last_vol_op = FT_ApproxTime();
5278 vp->stats.vol_ops++;
5279 IncUInt64(&VStats.vol_ops);
5285 * deregister the volume operation attached to this volume.
5287 * @param[in] vp volume object pointer
5289 * @pre VOL_LOCK is held
5291 * @post the volume operation info object is detached from the volume object
5293 * @internal volume package internal use only
5296 VDeregisterVolOp_r(Volume * vp)
5298 if (vp->pending_vol_op) {
5299 free(vp->pending_vol_op);
5300 vp->pending_vol_op = NULL;
5304 #endif /* AFS_DEMAND_ATTACH_FS */
5307 * determine whether it is safe to leave a volume online during
5308 * the volume operation described by the vopinfo object.
5310 * @param[in] vp volume object
5311 * @param[in] vopinfo volume operation info object
5313 * @return whether it is safe to leave volume online
5314 * @retval 0 it is NOT SAFE to leave the volume online
5315 * @retval 1 it is safe to leave the volume online during the operation
5318 * @arg VOL_LOCK is held
5319 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5320 * this condition is met)
5322 * @internal volume package internal use only
5325 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5327 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5328 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5329 (vopinfo->com.reason == V_READONLY ||
5330 (!VolumeWriteable(vp) &&
5331 (vopinfo->com.reason == V_CLONE ||
5332 vopinfo->com.reason == V_DUMP)))));
5336 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5339 * @param[in] vp volume object
5340 * @param[in] vopinfo volume operation info object
5342 * @return whether it is safe to leave volume online
5343 * @retval 0 it is NOT SAFE to leave the volume online
5344 * @retval 1 it is safe to leave the volume online during the operation
5345 * @retval -1 unsure; volume header is required in order to know whether or
5346 * not is is safe to leave the volume online
5348 * @pre VOL_LOCK is held
5350 * @internal volume package internal use only
5353 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5355 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5356 * assume that we don't know VolumeWriteable; return -1 if the answer
5357 * depends on VolumeWriteable */
5359 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5362 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5363 vopinfo->com.reason == V_READONLY) {
5367 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5368 (vopinfo->com.reason == V_CLONE ||
5369 vopinfo->com.reason == V_DUMP)) {
5371 /* must know VolumeWriteable */
5378 * determine whether VBUSY should be set during this volume operation.
5380 * @param[in] vp volume object
5381 * @param[in] vopinfo volume operation info object
5383 * @return whether VBUSY should be set
5384 * @retval 0 VBUSY does NOT need to be set
5385 * @retval 1 VBUSY SHOULD be set
5387 * @pre VOL_LOCK is held
5389 * @internal volume package internal use only
5392 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5394 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5395 vopinfo->com.reason == FSYNC_SALVAGE) ||
5396 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5397 (vopinfo->com.reason == V_CLONE ||
5398 vopinfo->com.reason == V_DUMP)));
5402 /***************************************************/
5403 /* online salvager routines */
5404 /***************************************************/
5405 #if defined(AFS_DEMAND_ATTACH_FS)
5408 * offline a volume to let it be salvaged.
5410 * @param[in] vp Volume to offline
5412 * @return whether we offlined the volume successfully
5413 * @retval 0 volume was not offlined
5414 * @retval 1 volume is now offline
5416 * @note This is similar to VCheckOffline, but slightly different. We do not
5417 * deal with vp->goingOffline, and we try to avoid touching the volume
5418 * header except just to set needsSalvaged
5420 * @pre VOL_LOCK held
5421 * @pre vp->nUsers == 0
5422 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5425 VOfflineForSalvage_r(struct Volume *vp)
5429 VCreateReservation_r(vp);
5430 VWaitExclusiveState_r(vp);
5432 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5433 /* Someone's using the volume, or someone got to scheduling the salvage
5434 * before us. I don't think either of these should be possible, as we
5435 * should gain no new heavyweight references while we're trying to
5436 * salvage, but just to be sure... */
5437 VCancelReservation_r(vp);
5441 VChangeState_r(vp, VOL_STATE_OFFLINING);
5445 V_needsSalvaged(vp) = 1;
5446 /* ignore error; updating needsSalvaged is just best effort */
5447 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5449 VCloseVolumeHandles_r(vp);
5451 FreeVolumeHeader(vp);
5453 /* volume has been effectively offlined; we can mark it in the SALVAGING
5454 * state now, which lets FSSYNC give it away */
5455 VChangeState_r(vp, VOL_STATE_SALVAGING);
5457 VCancelReservation_r(vp);
5463 * check whether a salvage needs to be performed on this volume.
5465 * @param[in] vp pointer to volume object
5467 * @return status code
5468 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5469 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5470 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5471 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5472 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5474 * @pre VOL_LOCK is held
5476 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5477 * then a salvage will be requested
5479 * @note this is one of the event handlers called by VCancelReservation_r
5481 * @note the caller must check if the volume needs to be freed after calling
5482 * this; the volume may not have any references or be on any lists after
5483 * we return, and we do not free it
5485 * @see VCancelReservation_r
5487 * @internal volume package internal use only.
5490 VCheckSalvage(Volume * vp)
5492 int ret = VCHECK_SALVAGE_OK;
5494 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5495 if (!vp->salvage.requested) {
5496 return VCHECK_SALVAGE_OK;
5499 return VCHECK_SALVAGE_ASYNC;
5502 /* prevent recursion; some of the code below creates and removes
5503 * lightweight refs, which can call VCheckSalvage */
5504 if (vp->salvage.scheduling) {
5505 return VCHECK_SALVAGE_ASYNC;
5507 vp->salvage.scheduling = 1;
5509 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5510 if (!VOfflineForSalvage_r(vp)) {
5511 vp->salvage.scheduling = 0;
5512 return VCHECK_SALVAGE_FAIL;
5516 if (vp->salvage.requested) {
5517 ret = VScheduleSalvage_r(vp);
5519 vp->salvage.scheduling = 0;
5520 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5525 * request volume salvage.
5527 * @param[out] ec computed client error code
5528 * @param[in] vp volume object pointer
5529 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5530 * @param[in] flags see flags note below
5533 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5534 * not been fully attached
5536 * @pre VOL_LOCK is held.
5538 * @post volume state is changed.
5539 * for fileserver, salvage will be requested once refcount reaches zero.
5541 * @return operation status code
5542 * @retval 0 volume salvage will occur
5543 * @retval 1 volume salvage could not be scheduled
5547 * @note in the fileserver, this call does not synchronously schedule a volume
5548 * salvage. rather, it sets volume state so that when volume refcounts
5549 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5550 * nUsers and nWaiters must be zero.
5552 * @internal volume package internal use only.
5555 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5559 * for DAFS volume utilities that are not supposed to schedule salvages,
5560 * just transition to error state instead
5562 if (!VCanScheduleSalvage()) {
5563 VChangeState_r(vp, VOL_STATE_ERROR);
5568 if (programType != fileServer && !VCanUseFSSYNC()) {
5569 VChangeState_r(vp, VOL_STATE_ERROR);
5574 if (!vp->salvage.requested) {
5575 vp->salvage.requested = 1;
5576 vp->salvage.reason = reason;
5577 vp->stats.last_salvage = FT_ApproxTime();
5579 /* Note that it is not possible for us to reach this point if a
5580 * salvage is already running on this volume (even if the fileserver
5581 * was restarted during the salvage). If a salvage were running, the
5582 * salvager would have write-locked the volume header file, so when
5583 * we tried to lock the volume header, the lock would have failed,
5584 * and we would have failed during attachment prior to calling
5585 * VRequestSalvage. So we know that we can schedule salvages without
5586 * fear of a salvage already running for this volume. */
5588 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5590 /* if we don't need to offline the volume, we can go directly
5591 * to SALVAGING. SALVAGING says the volume is offline and is
5592 * either salvaging or ready to be handed to the salvager.
5593 * SALVAGE_REQ says that we want to salvage the volume, but we
5594 * are waiting for it to go offline first. */
5595 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5596 VChangeState_r(vp, VOL_STATE_SALVAGING);
5598 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5599 if (vp->nUsers == 0) {
5600 /* normally VOfflineForSalvage_r would be called from
5601 * PutVolume et al when nUsers reaches 0, but if
5602 * it's already 0, just do it ourselves, since PutVolume
5603 * isn't going to get called */
5604 VOfflineForSalvage_r(vp);
5607 /* If we are non-fileserver, we're telling the fileserver to
5608 * salvage the vol, so we don't need to give it back separately. */
5609 vp->needsPutBack = 0;
5613 Log("VRequestSalvage: volume %" AFS_VOLID_FMT " online salvaged too many times; forced offline.\n", afs_printable_VolumeId_lu(vp->hashid));
5615 /* make sure neither VScheduleSalvage_r nor
5616 * VUpdateSalvagePriority_r try to schedule another salvage */
5617 vp->salvage.requested = vp->salvage.scheduled = 0;
5619 VChangeState_r(vp, VOL_STATE_ERROR);
5623 if ((flags & VOL_SALVAGE_NO_OFFLINE)) {
5624 /* Here, we free the header for the volume, but make sure to only
5625 * do this if VOL_SALVAGE_NO_OFFLINE is specified. The reason for
5626 * this requires a bit of explanation.
5628 * Normally, the volume header will be freed when the volume goes
5629 * goes offline. However, if VOL_SALVAGE_NO_OFFLINE has been
5630 * specified, the volume was in the process of being attached when
5631 * we discovered that it needed salvaging. Thus, the volume will
5632 * never go offline, since it never went fully online in the first
5633 * place. Specifically, we do not call VOfflineForSalvage_r above,
5634 * and we never get rid of the volume via VPutVolume_r; the volume
5635 * has not been initialized enough for those to work.
5637 * So instead, explicitly free the volume header here. If we do not
5638 * do this, we are wasting a header that some other volume could be
5639 * using, since the header remains attached to the volume. Also if
5640 * we do not free the header here, we end up with a volume where
5641 * nUsers == 0, but the volume has a header that is not on the
5642 * header LRU. Some code expects that all nUsers == 0 volumes have
5643 * their header on the header LRU (or have no header).
5645 * Also note that we must not free the volume header here if
5646 * VOL_SALVAGE_NO_OFFLINE is not set. Since, if
5647 * VOL_SALVAGE_NO_OFFLINE is not set, someone else may have a
5648 * reference to this volume, and they assume they can use the
5649 * volume's header. If we free the volume out from under them, they
5650 * can easily segfault.
5652 FreeVolumeHeader(vp);
5659 * update salvageserver scheduling priority for a volume.
5661 * @param[in] vp pointer to volume object
5663 * @return operation status
5665 * @retval 1 request denied, or SALVSYNC communications failure
5667 * @pre VOL_LOCK is held.
5669 * @post in-core salvage priority counter is incremented. if at least
5670 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5671 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5672 * to update its priority queue. if no salvage is scheduled,
5673 * this function is a no-op.
5675 * @note DAFS fileserver only
5677 * @note this should be called whenever a VGetVolume fails due to a
5678 * pending salvage request
5680 * @todo should set exclusive state and drop glock around salvsync call
5682 * @internal volume package internal use only.
5685 VUpdateSalvagePriority_r(Volume * vp)
5689 #ifdef SALVSYNC_BUILD_CLIENT
5694 now = FT_ApproxTime();
5696 /* update the salvageserver priority queue occasionally so that
5697 * frequently requested volumes get moved to the head of the queue
5699 if ((vp->salvage.scheduled) &&
5700 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5701 code = SALVSYNC_SalvageVolume(vp->hashid,
5702 VPartitionPath(vp->partition),
5707 vp->stats.last_salvage_req = now;
5708 if (code != SYNC_OK) {
5712 #endif /* SALVSYNC_BUILD_CLIENT */
5717 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5719 /* A couple of little helper functions. These return true if we tried to
5720 * use this mechanism to schedule a salvage, false if we haven't tried.
5721 * If we did try a salvage then the results are contained in code.
5725 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5726 #ifdef SALVSYNC_BUILD_CLIENT
5727 if (VCanUseSALVSYNC()) {
5728 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over SALVSYNC\n",
5729 afs_printable_VolumeId_lu(vp->hashid), partName);
5731 /* can't use V_id() since there's no guarantee
5732 * we have the disk data header at this point */
5733 *code = SALVSYNC_SalvageVolume(vp->hashid,
5746 try_FSSYNC(Volume *vp, char *partName, int *code) {
5747 #ifdef FSSYNC_BUILD_CLIENT
5748 if (VCanUseFSSYNC()) {
5749 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over FSSYNC\n",
5750 afs_printable_VolumeId_lu(vp->hashid), partName);
5753 * If we aren't the fileserver, tell the fileserver the volume
5754 * needs to be salvaged. We could directly tell the
5755 * salvageserver, but the fileserver keeps track of some stats
5756 * related to salvages, and handles some other salvage-related
5757 * complications for us.
5759 *code = FSYNC_VolOp(vp->hashid, partName,
5760 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5763 #endif /* FSSYNC_BUILD_CLIENT */
5768 * schedule a salvage with the salvage server or fileserver.
5770 * @param[in] vp pointer to volume object
5772 * @return operation status
5773 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5774 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5775 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5776 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5777 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5780 * @arg VOL_LOCK is held.
5781 * @arg nUsers and nWaiters should be zero.
5783 * @post salvageserver or fileserver is sent a salvage request
5785 * @note If we are the fileserver, the request will be sent to the salvage
5786 * server over SALVSYNC. If we are not the fileserver, the request will be
5787 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5789 * @note the caller must check if the volume needs to be freed after calling
5790 * this; the volume may not have any references or be on any lists after
5791 * we return, and we do not free it
5795 * @internal volume package internal use only.
5798 VScheduleSalvage_r(Volume * vp)
5800 int ret = VCHECK_SALVAGE_SCHEDULED;
5802 VolState state_save;
5803 VThreadOptions_t * thread_opts;
5806 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5808 if (vp->nWaiters || vp->nUsers) {
5809 return VCHECK_SALVAGE_ASYNC;
5812 /* prevent endless salvage,attach,salvage,attach,... loops */
5813 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5814 return VCHECK_SALVAGE_FAIL;
5818 * don't perform salvsync ops on certain threads
5820 thread_opts = pthread_getspecific(VThread_key);
5821 if (thread_opts == NULL) {
5822 thread_opts = &VThread_defaults;
5824 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5825 return VCHECK_SALVAGE_ASYNC;
5828 if (vp->salvage.scheduled) {
5829 return VCHECK_SALVAGE_SCHEDULED;
5832 VCreateReservation_r(vp);
5833 VWaitExclusiveState_r(vp);
5836 * XXX the scheduling process should really be done asynchronously
5837 * to avoid fssync deadlocks
5839 if (vp->salvage.scheduled) {
5840 ret = VCHECK_SALVAGE_SCHEDULED;
5842 /* if we haven't previously scheduled a salvage, do so now
5844 * set the volume to an exclusive state and drop the lock
5845 * around the SALVSYNC call
5847 strlcpy(partName, vp->partition->name, sizeof(partName));
5848 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5851 opr_Verify(try_SALVSYNC(vp, partName, &code)
5852 || try_FSSYNC(vp, partName, &code));
5855 VChangeState_r(vp, state_save);
5857 if (code == SYNC_OK) {
5858 ret = VCHECK_SALVAGE_SCHEDULED;
5859 vp->salvage.scheduled = 1;
5860 vp->stats.last_salvage_req = FT_ApproxTime();
5861 if (VCanUseSALVSYNC()) {
5862 /* don't record these stats for non-fileservers; let the
5863 * fileserver take care of these */
5864 vp->stats.salvages++;
5865 IncUInt64(&VStats.salvages);
5869 case SYNC_BAD_COMMAND:
5870 case SYNC_COM_ERROR:
5871 ret = VCHECK_SALVAGE_FAIL;
5874 ret = VCHECK_SALVAGE_DENIED;
5875 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5876 "denied\n", afs_printable_VolumeId_lu(vp->hashid));
5879 ret = VCHECK_SALVAGE_FAIL;
5880 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5881 "failed\n", afs_printable_VolumeId_lu(vp->hashid));
5884 ret = VCHECK_SALVAGE_FAIL;
5885 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5886 "received unknown protocol error %d\n",
5887 afs_printable_VolumeId_lu(vp->hashid), code);
5891 if (VCanUseFSSYNC()) {
5892 VChangeState_r(vp, VOL_STATE_ERROR);
5897 /* NB: this is cancelling the reservation we obtained above, but we do
5898 * not call VCancelReservation_r, since that may trigger the vp dtor,
5899 * possibly free'ing the vp. We need to keep the vp around after
5900 * this, as the caller may reference vp without any refs. Instead, it
5901 * is the duty of the caller to inspect 'vp' after we return to see if
5902 * needs to be freed. */
5903 opr_Verify(--vp->nWaiters >= 0);
5906 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5908 #ifdef SALVSYNC_BUILD_CLIENT
5911 * connect to the salvageserver SYNC service.
5913 * @return operation status
5917 * @post connection to salvageserver SYNC service established
5919 * @see VConnectSALV_r
5920 * @see VDisconnectSALV
5921 * @see VReconnectSALV
5928 retVal = VConnectSALV_r();
5934 * connect to the salvageserver SYNC service.
5936 * @return operation status
5940 * @pre VOL_LOCK is held.
5942 * @post connection to salvageserver SYNC service established
5945 * @see VDisconnectSALV_r
5946 * @see VReconnectSALV_r
5947 * @see SALVSYNC_clientInit
5949 * @internal volume package internal use only.
5952 VConnectSALV_r(void)
5954 return SALVSYNC_clientInit();
5958 * disconnect from the salvageserver SYNC service.
5960 * @return operation status
5963 * @pre client should have a live connection to the salvageserver
5965 * @post connection to salvageserver SYNC service destroyed
5967 * @see VDisconnectSALV_r
5969 * @see VReconnectSALV
5972 VDisconnectSALV(void)
5975 VDisconnectSALV_r();
5981 * disconnect from the salvageserver SYNC service.
5983 * @return operation status
5987 * @arg VOL_LOCK is held.
5988 * @arg client should have a live connection to the salvageserver.
5990 * @post connection to salvageserver SYNC service destroyed
5992 * @see VDisconnectSALV
5993 * @see VConnectSALV_r
5994 * @see VReconnectSALV_r
5995 * @see SALVSYNC_clientFinis
5997 * @internal volume package internal use only.
6000 VDisconnectSALV_r(void)
6002 return SALVSYNC_clientFinis();
6006 * disconnect and then re-connect to the salvageserver SYNC service.
6008 * @return operation status
6012 * @pre client should have a live connection to the salvageserver
6014 * @post old connection is dropped, and a new one is established
6017 * @see VDisconnectSALV
6018 * @see VReconnectSALV_r
6021 VReconnectSALV(void)
6025 retVal = VReconnectSALV_r();
6031 * disconnect and then re-connect to the salvageserver SYNC service.
6033 * @return operation status
6038 * @arg VOL_LOCK is held.
6039 * @arg client should have a live connection to the salvageserver.
6041 * @post old connection is dropped, and a new one is established
6043 * @see VConnectSALV_r
6044 * @see VDisconnectSALV
6045 * @see VReconnectSALV
6046 * @see SALVSYNC_clientReconnect
6048 * @internal volume package internal use only.
6051 VReconnectSALV_r(void)
6053 return SALVSYNC_clientReconnect();
6055 #endif /* SALVSYNC_BUILD_CLIENT */
6056 #endif /* AFS_DEMAND_ATTACH_FS */
6059 /***************************************************/
6060 /* FSSYNC routines */
6061 /***************************************************/
6063 /* This must be called by any volume utility which needs to run while the
6064 file server is also running. This is separated from VInitVolumePackage2 so
6065 that a utility can fork--and each of the children can independently
6066 initialize communication with the file server */
6067 #ifdef FSSYNC_BUILD_CLIENT
6069 * connect to the fileserver SYNC service.
6071 * @return operation status
6076 * @arg VInit must equal 2.
6077 * @arg Program Type must not be fileserver or salvager.
6079 * @post connection to fileserver SYNC service established
6082 * @see VDisconnectFS
6083 * @see VChildProcReconnectFS
6090 retVal = VConnectFS_r();
6096 * connect to the fileserver SYNC service.
6098 * @return operation status
6103 * @arg VInit must equal 2.
6104 * @arg Program Type must not be fileserver or salvager.
6105 * @arg VOL_LOCK is held.
6107 * @post connection to fileserver SYNC service established
6110 * @see VDisconnectFS_r
6111 * @see VChildProcReconnectFS_r
6113 * @internal volume package internal use only.
6119 opr_Assert((VInit == 2) &&
6120 (programType != fileServer) &&
6121 (programType != salvager));
6122 rc = FSYNC_clientInit();
6130 * disconnect from the fileserver SYNC service.
6133 * @arg client should have a live connection to the fileserver.
6134 * @arg VOL_LOCK is held.
6135 * @arg Program Type must not be fileserver or salvager.
6137 * @post connection to fileserver SYNC service destroyed
6139 * @see VDisconnectFS
6141 * @see VChildProcReconnectFS_r
6143 * @internal volume package internal use only.
6146 VDisconnectFS_r(void)
6148 opr_Assert((programType != fileServer) &&
6149 (programType != salvager));
6150 FSYNC_clientFinis();
6155 * disconnect from the fileserver SYNC service.
6158 * @arg client should have a live connection to the fileserver.
6159 * @arg Program Type must not be fileserver or salvager.
6161 * @post connection to fileserver SYNC service destroyed
6163 * @see VDisconnectFS_r
6165 * @see VChildProcReconnectFS
6176 * connect to the fileserver SYNC service from a child process following a fork.
6178 * @return operation status
6183 * @arg VOL_LOCK is held.
6184 * @arg current FSYNC handle is shared with a parent process
6186 * @post current FSYNC handle is discarded and a new connection to the
6187 * fileserver SYNC service is established
6189 * @see VChildProcReconnectFS
6191 * @see VDisconnectFS_r
6193 * @internal volume package internal use only.
6196 VChildProcReconnectFS_r(void)
6198 return FSYNC_clientChildProcReconnect();
6202 * connect to the fileserver SYNC service from a child process following a fork.
6204 * @return operation status
6208 * @pre current FSYNC handle is shared with a parent process
6210 * @post current FSYNC handle is discarded and a new connection to the
6211 * fileserver SYNC service is established
6213 * @see VChildProcReconnectFS_r
6215 * @see VDisconnectFS
6218 VChildProcReconnectFS(void)
6222 ret = VChildProcReconnectFS_r();
6226 #endif /* FSSYNC_BUILD_CLIENT */
6229 /***************************************************/
6230 /* volume bitmap routines */
6231 /***************************************************/
6234 * Grow the bitmap by the defined increment
6237 VGrowBitmap(struct vnodeIndex *index)
6241 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6242 osi_Assert(bp != NULL);
6244 bp += index->bitmapSize;
6245 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6246 index->bitmapOffset = index->bitmapSize;
6247 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6253 * allocate a vnode bitmap number for the vnode
6255 * @param[out] ec error code
6256 * @param[in] vp volume object pointer
6257 * @param[in] index vnode index number for the vnode
6258 * @param[in] flags flag values described in note
6260 * @note for DAFS, flags parameter controls locking behavior.
6261 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6262 * will create a reservation and block on any other exclusive
6263 * operations. Otherwise, this function assumes the caller
6264 * already has exclusive access to vp, and we just change the
6267 * @pre VOL_LOCK held
6269 * @return bit number allocated
6275 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6276 struct vnodeIndex *index, int flags)
6280 #ifdef AFS_DEMAND_ATTACH_FS
6281 VolState state_save;
6282 #endif /* AFS_DEMAND_ATTACH_FS */
6286 /* This test is probably redundant */
6287 if (!VolumeWriteable(vp)) {
6288 *ec = (bit32) VREADONLY;
6292 #ifdef AFS_DEMAND_ATTACH_FS
6293 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6294 VCreateReservation_r(vp);
6295 VWaitExclusiveState_r(vp);
6297 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6298 #endif /* AFS_DEMAND_ATTACH_FS */
6301 if ((programType == fileServer) && !index->bitmap) {
6303 #ifndef AFS_DEMAND_ATTACH_FS
6304 /* demand attach fs uses the volume state to avoid races.
6305 * specialStatus field is not used at all */
6307 if (vp->specialStatus == VBUSY) {
6308 if (vp->goingOffline) { /* vos dump waiting for the volume to
6309 * go offline. We probably come here
6310 * from AddNewReadableResidency */
6313 while (vp->specialStatus == VBUSY) {
6314 #ifdef AFS_PTHREAD_ENV
6318 #else /* !AFS_PTHREAD_ENV */
6320 #endif /* !AFS_PTHREAD_ENV */
6324 #endif /* !AFS_DEMAND_ATTACH_FS */
6326 if (!index->bitmap) {
6327 #ifndef AFS_DEMAND_ATTACH_FS
6328 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6329 #endif /* AFS_DEMAND_ATTACH_FS */
6330 for (i = 0; i < nVNODECLASSES; i++) {
6331 VGetBitmap_r(ec, vp, i);
6333 #ifdef AFS_DEMAND_ATTACH_FS
6334 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6335 #else /* AFS_DEMAND_ATTACH_FS */
6336 DeleteVolumeFromHashTable(vp);
6337 vp->shuttingDown = 1; /* Let who has it free it. */
6338 vp->specialStatus = 0;
6339 #endif /* AFS_DEMAND_ATTACH_FS */
6343 #ifndef AFS_DEMAND_ATTACH_FS
6345 vp->specialStatus = 0; /* Allow others to have access. */
6346 #endif /* AFS_DEMAND_ATTACH_FS */
6349 #endif /* BITMAP_LATER */
6351 #ifdef AFS_DEMAND_ATTACH_FS
6353 #endif /* AFS_DEMAND_ATTACH_FS */
6354 bp = index->bitmap + index->bitmapOffset;
6355 ep = index->bitmap + index->bitmapSize;
6357 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6359 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6362 o = opr_ffs(~*bp) - 1;
6364 ret = ((bp - index->bitmap) * 8 + o);
6365 #ifdef AFS_DEMAND_ATTACH_FS
6367 #endif /* AFS_DEMAND_ATTACH_FS */
6370 bp += sizeof(bit32) /* i.e. 4 */ ;
6372 /* No bit map entry--must grow bitmap */
6374 bp = index->bitmap + index->bitmapOffset;
6376 ret = index->bitmapOffset * 8;
6377 #ifdef AFS_DEMAND_ATTACH_FS
6379 #endif /* AFS_DEMAND_ATTACH_FS */
6382 #ifdef AFS_DEMAND_ATTACH_FS
6383 VChangeState_r(vp, state_save);
6384 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6385 VCancelReservation_r(vp);
6387 #endif /* AFS_DEMAND_ATTACH_FS */
6392 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6396 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6402 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6403 unsigned bitNumber, int flags)
6405 unsigned int offset;
6409 #ifdef AFS_DEMAND_ATTACH_FS
6410 if (flags & VOL_FREE_BITMAP_WAIT) {
6411 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6412 * state, so ensure we're not in an exclusive volume state when we update
6414 VCreateReservation_r(vp);
6415 VWaitExclusiveState_r(vp);
6422 #endif /* BITMAP_LATER */
6424 offset = bitNumber >> 3;
6425 if (offset >= index->bitmapSize) {
6429 if (offset < index->bitmapOffset)
6430 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6431 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6434 #ifdef AFS_DEMAND_ATTACH_FS
6435 if (flags & VOL_FREE_BITMAP_WAIT) {
6436 VCancelReservation_r(vp);
6439 return; /* make the compiler happy for non-DAFS */
6443 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6447 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6451 /* this function will drop the glock internally.
6452 * for old pthread fileservers, this is safe thanks to vbusy.
6454 * for demand attach fs, caller must have already called
6455 * VCreateReservation_r and VWaitExclusiveState_r */
6457 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6459 StreamHandle_t *file;
6460 afs_sfsize_t nVnodes, size;
6461 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6462 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6463 struct VnodeDiskObject *vnode;
6464 unsigned int unique = 0;
6468 #endif /* BITMAP_LATER */
6469 #ifdef AFS_DEMAND_ATTACH_FS
6470 VolState state_save;
6471 #endif /* AFS_DEMAND_ATTACH_FS */
6475 #ifdef AFS_DEMAND_ATTACH_FS
6476 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6477 #endif /* AFS_DEMAND_ATTACH_FS */
6480 fdP = IH_OPEN(vip->handle);
6481 opr_Assert(fdP != NULL);
6482 file = FDH_FDOPEN(fdP, "r");
6483 opr_Assert(file != NULL);
6484 vnode = malloc(vcp->diskSize);
6485 opr_Assert(vnode != NULL);
6486 size = OS_SIZE(fdP->fd_fd);
6487 opr_Assert(size != -1);
6488 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6490 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6491 * a few files can be created in this volume,
6492 * the whole thing is rounded up to nearest 4
6493 * bytes, because the bit map allocator likes
6496 BitMap = (byte *) calloc(1, vip->bitmapSize);
6497 opr_Assert(BitMap != NULL);
6498 #else /* BITMAP_LATER */
6499 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6500 opr_Assert(vip->bitmap != NULL);
6501 vip->bitmapOffset = 0;
6502 #endif /* BITMAP_LATER */
6503 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6505 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6506 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6508 if (vnode->type != vNull) {
6509 if (vnode->vnodeMagic != vcp->magic) {
6510 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6515 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6516 #else /* BITMAP_LATER */
6517 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6518 #endif /* BITMAP_LATER */
6519 if (unique <= vnode->uniquifier)
6520 unique = vnode->uniquifier + 1;
6522 #ifndef AFS_PTHREAD_ENV
6523 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6526 #endif /* !AFS_PTHREAD_ENV */
6529 if (vp->nextVnodeUnique < unique) {
6530 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6533 /* Paranoia, partly justified--I think fclose after fdopen
6534 * doesn't seem to close fd. In any event, the documentation
6535 * doesn't specify, so it's safer to close it twice.
6543 /* There may have been a racing condition with some other thread, both
6544 * creating the bitmaps for this volume. If the other thread was faster
6545 * the pointer to bitmap should already be filled and we can free ours.
6547 if (vip->bitmap == NULL) {
6548 vip->bitmap = BitMap;
6549 vip->bitmapOffset = 0;
6552 #endif /* BITMAP_LATER */
6553 #ifdef AFS_DEMAND_ATTACH_FS
6554 VChangeState_r(vp, state_save);
6555 #endif /* AFS_DEMAND_ATTACH_FS */
6559 /***************************************************/
6560 /* Volume Path and Volume Number utility routines */
6561 /***************************************************/
6564 * find the first occurrence of a volume header file and return the path.
6566 * @param[out] ec outbound error code
6567 * @param[in] volumeId volume id to find
6568 * @param[out] partitionp pointer to disk partition path string
6569 * @param[out] namep pointer to volume header file name string
6571 * @post path to first occurrence of volume header is returned in partitionp
6572 * and namep, or ec is set accordingly.
6574 * @warning this function is NOT re-entrant -- partitionp and namep point to
6575 * static data segments
6577 * @note if a volume utility inadvertently leaves behind a stale volume header
6578 * on a vice partition, it is possible for callers to get the wrong one,
6579 * depending on the order of the disk partition linked list.
6583 VGetVolumePath(Error * ec, VolumeId volumeId, char **partitionp, char **namep)
6585 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6586 char path[VMAXPATHLEN];
6588 struct DiskPartition64 *dp;
6591 name[0] = OS_DIRSEPC;
6592 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6593 afs_printable_VolumeId_lu(volumeId));
6594 for (dp = DiskPartitionList; dp; dp = dp->next) {
6595 struct afs_stat_st status;
6596 strcpy(path, VPartitionPath(dp));
6598 if (afs_stat(path, &status) == 0) {
6599 strcpy(partition, dp->name);
6606 *partitionp = *namep = NULL;
6608 *partitionp = partition;
6614 * extract a volume number from a volume header filename string.
6616 * @param[in] name volume header filename string
6618 * @return volume number
6620 * @note the string must be of the form VFORMAT. the only permissible
6621 * deviation is a leading OS_DIRSEPC character.
6626 VolumeNumber(char *name)
6628 if (*name == OS_DIRSEPC)
6630 return strtoul(name + 1, NULL, 10);
6634 * compute the volume header filename.
6636 * @param[in] volumeId
6638 * @return volume header filename
6640 * @post volume header filename string is constructed
6642 * @warning this function is NOT re-entrant -- the returned string is
6643 * stored in a static char array. see VolumeExternalName_r
6644 * for a re-entrant equivalent.
6646 * @see VolumeExternalName_r
6648 * @deprecated due to the above re-entrancy warning, this interface should
6649 * be considered deprecated. Please use VolumeExternalName_r
6653 VolumeExternalName(VolumeId volumeId)
6655 static char name[VMAXPATHLEN];
6656 snprintf(name, sizeof name, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6661 * compute the volume header filename.
6663 * @param[in] volumeId
6664 * @param[inout] name array in which to store filename
6665 * @param[in] len length of name array
6667 * @return result code from afs_snprintf
6669 * @see VolumeExternalName
6672 * @note re-entrant equivalent of VolumeExternalName
6675 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6677 return snprintf(name, len, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6681 /***************************************************/
6682 /* Volume Usage Statistics routines */
6683 /***************************************************/
6685 #define OneDay (86400) /* 24 hours' worth of seconds */
6688 Midnight(time_t t) {
6689 struct tm local, *l;
6692 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6693 l = localtime_r(&t, &local);
6699 /* the following is strictly speaking problematic on the
6700 switching day to daylight saving time, after the switch,
6701 as tm_isdst does not match. Similarly, on the looong day when
6702 switching back the OneDay check will not do what naively expected!
6703 The effects are minor, though, and more a matter of interpreting
6705 #ifndef AFS_PTHREAD_ENV
6708 local.tm_hour = local.tm_min=local.tm_sec = 0;
6709 midnight = mktime(&local);
6710 if (midnight != (time_t) -1) return(midnight);
6712 return( (t/OneDay)*OneDay );
6716 /*------------------------------------------------------------------------
6717 * [export] VAdjustVolumeStatistics
6720 * If we've passed midnight, we need to update all the day use
6721 * statistics as well as zeroing the detailed volume statistics
6722 * (if we are implementing them).
6725 * vp : Pointer to the volume structure describing the lucky
6726 * volume being considered for update.
6732 * Nothing interesting.
6736 *------------------------------------------------------------------------*/
6739 VAdjustVolumeStatistics_r(Volume * vp)
6741 unsigned int now = FT_ApproxTime();
6743 if (now - V_dayUseDate(vp) > OneDay) {
6746 ndays = (now - V_dayUseDate(vp)) / OneDay;
6747 for (i = 6; i > ndays - 1; i--)
6748 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6749 for (i = 0; i < ndays - 1 && i < 7; i++)
6750 V_weekUse(vp)[i] = 0;
6752 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6754 V_dayUseDate(vp) = Midnight(now);
6757 * All we need to do is bzero the entire VOL_STATS_BYTES of
6758 * the detailed volume statistics area.
6760 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6763 /*It's been more than a day of collection */
6765 * Always return happily.
6768 } /*VAdjustVolumeStatistics */
6771 VAdjustVolumeStatistics(Volume * vp)
6775 retVal = VAdjustVolumeStatistics_r(vp);
6781 VBumpVolumeUsage_r(Volume * vp)
6783 unsigned int now = FT_ApproxTime();
6784 V_accessDate(vp) = now;
6785 if (now - V_dayUseDate(vp) > OneDay)
6786 VAdjustVolumeStatistics_r(vp);
6788 * Save the volume header image to disk after a threshold of bumps to dayUse,
6789 * at most every usage_rate_limit seconds.
6792 vp->usage_bumps_outstanding++;
6793 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6794 && vp->usage_bumps_next_write <= now) {
6796 vp->usage_bumps_outstanding = 0;
6797 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6798 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6803 VBumpVolumeUsage(Volume * vp)
6806 VBumpVolumeUsage_r(vp);
6811 VSetDiskUsage_r(void)
6813 #ifndef AFS_DEMAND_ATTACH_FS
6814 static int FifteenMinuteCounter = 0;
6818 /* NOTE: Don't attempt to access the partitions list until the
6819 * initialization level indicates that all volumes are attached,
6820 * which implies that all partitions are initialized. */
6821 #ifdef AFS_PTHREAD_ENV
6822 VOL_CV_WAIT(&vol_vinit_cond);
6823 #else /* AFS_PTHREAD_ENV */
6825 #endif /* AFS_PTHREAD_ENV */
6828 VResetDiskUsage_r();
6830 #ifndef AFS_DEMAND_ATTACH_FS
6831 if (++FifteenMinuteCounter == 3) {
6832 FifteenMinuteCounter = 0;
6835 #endif /* !AFS_DEMAND_ATTACH_FS */
6847 /***************************************************/
6848 /* Volume Update List routines */
6849 /***************************************************/
6851 /* The number of minutes that a volume hasn't been updated before the
6852 * "Dont salvage" flag in the volume header will be turned on */
6853 #define SALVAGE_INTERVAL (10*60)
6858 * volume update list functionality has been moved into the VLRU
6859 * the DONT_SALVAGE flag is now set during VLRU demotion
6862 #ifndef AFS_DEMAND_ATTACH_FS
6863 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6864 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6865 static int updateSize = 0; /* number of entries possible */
6866 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6867 #endif /* !AFS_DEMAND_ATTACH_FS */
6870 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6873 vp->updateTime = FT_ApproxTime();
6874 if (V_dontSalvage(vp) == 0)
6876 V_dontSalvage(vp) = 0;
6877 VSyncVolume_r(ec, vp, 0);
6878 #ifdef AFS_DEMAND_ATTACH_FS
6879 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6880 #else /* !AFS_DEMAND_ATTACH_FS */
6883 if (UpdateList == NULL) {
6884 updateSize = UPDATE_LIST_SIZE;
6885 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6887 if (nUpdatedVolumes == updateSize) {
6889 if (updateSize > 524288) {
6890 Log("warning: there is likely a bug in the volume update scanner\n");
6893 UpdateList = realloc(UpdateList,
6894 sizeof(VolumeId) * updateSize);
6897 opr_Assert(UpdateList != NULL);
6898 UpdateList[nUpdatedVolumes++] = V_id(vp);
6899 #endif /* !AFS_DEMAND_ATTACH_FS */
6902 #ifndef AFS_DEMAND_ATTACH_FS
6904 VScanUpdateList(void)
6909 afs_uint32 now = FT_ApproxTime();
6910 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6911 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6913 UpdateList[i - gap] = UpdateList[i];
6915 /* XXX this routine needlessly messes up the Volume LRU by
6916 * breaking the LRU temporal-locality assumptions.....
6917 * we should use a special volume header allocator here */
6918 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6921 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6922 V_dontSalvage(vp) = DONT_SALVAGE;
6923 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6931 #ifndef AFS_PTHREAD_ENV
6933 #endif /* !AFS_PTHREAD_ENV */
6935 nUpdatedVolumes -= gap;
6937 #endif /* !AFS_DEMAND_ATTACH_FS */
6940 /***************************************************/
6941 /* Volume LRU routines */
6942 /***************************************************/
6947 * with demand attach fs, we attempt to soft detach(1)
6948 * volumes which have not been accessed in a long time
6949 * in order to speed up fileserver shutdown
6951 * (1) by soft detach we mean a process very similar
6952 * to VOffline, except the final state of the
6953 * Volume will be VOL_STATE_PREATTACHED, instead
6954 * of the usual VOL_STATE_UNATTACHED
6956 #ifdef AFS_DEMAND_ATTACH_FS
6958 /* implementation is reminiscent of a generational GC
6960 * queue 0 is newly attached volumes. this queue is
6961 * sorted by attach timestamp
6963 * queue 1 is volumes that have been around a bit
6964 * longer than queue 0. this queue is sorted by
6967 * queue 2 is volumes tha have been around the longest.
6968 * this queue is unsorted
6970 * queue 3 is volumes that have been marked as
6971 * candidates for soft detachment. this queue is
6974 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6975 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6978 * definition of a VLRU queue.
6981 volatile struct rx_queue q;
6988 * main VLRU data structure.
6991 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6994 /** time interval (in seconds) between promotion passes for
6995 * each young generation queue. */
6996 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6998 /** time interval (in seconds) between soft detach candidate
6999 * scans for each generation queue.
7001 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
7002 * we perform a soft detach pass. */
7003 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
7005 /* scheduler state */
7006 int next_idx; /**< next queue to receive attention */
7007 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
7008 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
7010 int scanner_state; /**< state of scanner thread */
7011 pthread_cond_t cv; /**< state transition CV */
7014 /** global VLRU state */
7015 static struct VLRU volume_LRU;
7018 * defined states for VLRU scanner thread.
7021 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7022 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7023 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7024 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7025 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7026 } vlru_thread_state_t;
7028 /* vlru disk data header stuff */
7029 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7030 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7032 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7033 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7036 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7037 * soft detachment. */
7038 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7040 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7041 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7043 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7044 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7046 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7047 static afs_uint32 VLRU_enabled = 1;
7049 /* queue synchronization routines */
7050 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7051 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7052 static void VLRU_Wait_r(struct VLRU_q * q);
7055 * set VLRU subsystem tunable parameters.
7057 * @param[in] option tunable option to modify
7058 * @param[in] val new value for tunable parameter
7060 * @pre @c VInitVolumePackage2 has not yet been called.
7062 * @post tunable parameter is modified
7066 * @note valid option parameters are:
7067 * @arg @c VLRU_SET_THRESH
7068 * set the period of inactivity after which
7069 * volumes are eligible for soft detachment
7070 * @arg @c VLRU_SET_INTERVAL
7071 * set the time interval between calls
7072 * to the volume LRU "garbage collector"
7073 * @arg @c VLRU_SET_MAX
7074 * set the max number of volumes to deallocate
7078 VLRU_SetOptions(int option, afs_uint32 val)
7080 if (option == VLRU_SET_THRESH) {
7081 VLRU_offline_thresh = val;
7082 } else if (option == VLRU_SET_INTERVAL) {
7083 VLRU_offline_interval = val;
7084 } else if (option == VLRU_SET_MAX) {
7085 VLRU_offline_max = val;
7086 } else if (option == VLRU_SET_ENABLED) {
7089 VLRU_ComputeConstants();
7093 * compute VLRU internal timing parameters.
7095 * @post VLRU scanner thread internal timing parameters are computed
7097 * @note computes internal timing parameters based upon user-modifiable
7098 * tunable parameters.
7102 * @internal volume package internal use only.
7105 VLRU_ComputeConstants(void)
7107 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7109 /* compute the candidate scan interval */
7110 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7112 /* compute the promotion intervals */
7113 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7114 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7117 /* compute the gen 0 scan interval */
7118 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7120 /* compute the gen 0 scan interval */
7121 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7126 * initialize VLRU subsystem.
7128 * @pre this function has not yet been called
7130 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7134 * @internal volume package internal use only.
7140 pthread_attr_t attrs;
7143 if (!VLRU_enabled) {
7144 Log("VLRU: disabled\n");
7148 /* initialize each of the VLRU queues */
7149 for (i = 0; i < VLRU_QUEUES; i++) {
7150 queue_Init(&volume_LRU.q[i]);
7151 volume_LRU.q[i].len = 0;
7152 volume_LRU.q[i].busy = 0;
7153 opr_cv_init(&volume_LRU.q[i].cv);
7156 /* setup the timing constants */
7157 VLRU_ComputeConstants();
7159 /* XXX put inside log level check? */
7160 Log("VLRU: starting scanner with the following configuration parameters:\n");
7161 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7162 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7163 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7164 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7165 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7166 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7168 /* start up the VLRU scanner */
7169 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7170 if (programType == fileServer) {
7171 opr_cv_init(&volume_LRU.cv);
7172 opr_Verify(pthread_attr_init(&attrs) == 0);
7173 opr_Verify(pthread_attr_setdetachstate(&attrs,
7174 PTHREAD_CREATE_DETACHED) == 0);
7175 opr_Verify(pthread_create(&tid, &attrs,
7176 &VLRU_ScannerThread, NULL) == 0);
7181 * initialize the VLRU-related fields of a newly allocated volume object.
7183 * @param[in] vp pointer to volume object
7186 * @arg @c VOL_LOCK is held.
7187 * @arg volume object is not on a VLRU queue.
7189 * @post VLRU fields are initialized to indicate that volume object is not
7190 * currently registered with the VLRU subsystem
7194 * @internal volume package interal use only.
7197 VLRU_Init_Node_r(Volume * vp)
7202 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7203 vp->vlru.idx = VLRU_QUEUE_INVALID;
7207 * add a volume object to a VLRU queue.
7209 * @param[in] vp pointer to volume object
7212 * @arg @c VOL_LOCK is held.
7213 * @arg caller MUST hold a lightweight ref on @p vp.
7214 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7216 * @post the volume object is added to the appropriate VLRU queue
7218 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7219 * then the volume is added to that queue. Otherwise, the value
7220 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7221 * volume is added to the NEW generation queue.
7223 * @note @c VOL_LOCK may be dropped internally
7225 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7226 * during the add operation, and is restored to the previous
7227 * state prior to return.
7231 * @internal volume package internal use only.
7234 VLRU_Add_r(Volume * vp)
7237 VolState state_save;
7242 if (queue_IsOnQueue(&vp->vlru))
7245 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7248 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7249 idx = VLRU_QUEUE_NEW;
7252 VLRU_Wait_r(&volume_LRU.q[idx]);
7254 /* repeat check since VLRU_Wait_r may have dropped
7256 if (queue_IsNotOnQueue(&vp->vlru)) {
7258 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7259 volume_LRU.q[idx].len++;
7260 V_attachFlags(vp) |= VOL_ON_VLRU;
7261 vp->stats.last_promote = FT_ApproxTime();
7264 VChangeState_r(vp, state_save);
7268 * delete a volume object from a VLRU queue.
7270 * @param[in] vp pointer to volume object
7273 * @arg @c VOL_LOCK is held.
7274 * @arg caller MUST hold a lightweight ref on @p vp.
7275 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7277 * @post volume object is removed from the VLRU queue
7279 * @note @c VOL_LOCK may be dropped internally
7283 * @todo We should probably set volume state to something exlcusive
7284 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7286 * @internal volume package internal use only.
7289 VLRU_Delete_r(Volume * vp)
7296 if (queue_IsNotOnQueue(&vp->vlru))
7302 if (idx == VLRU_QUEUE_INVALID)
7304 VLRU_Wait_r(&volume_LRU.q[idx]);
7305 } while (idx != vp->vlru.idx);
7307 /* now remove from the VLRU and update
7308 * the appropriate counter */
7309 queue_Remove(&vp->vlru);
7310 volume_LRU.q[idx].len--;
7311 vp->vlru.idx = VLRU_QUEUE_INVALID;
7312 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7316 * tell the VLRU subsystem that a volume was just accessed.
7318 * @param[in] vp pointer to volume object
7321 * @arg @c VOL_LOCK is held
7322 * @arg caller MUST hold a lightweight ref on @p vp
7323 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7325 * @post volume VLRU access statistics are updated. If the volume was on
7326 * the VLRU soft detach candidate queue, it is moved to the NEW
7329 * @note @c VOL_LOCK may be dropped internally
7333 * @internal volume package internal use only.
7336 VLRU_UpdateAccess_r(Volume * vp)
7338 Volume * rvp = NULL;
7343 if (queue_IsNotOnQueue(&vp->vlru))
7346 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7348 /* update the access timestamp */
7349 vp->stats.last_get = FT_ApproxTime();
7352 * if the volume is on the soft detach candidate
7353 * list, we need to safely move it back to a
7354 * regular generation. this has to be done
7355 * carefully so we don't race against the scanner
7359 /* if this volume is on the soft detach candidate queue,
7360 * then grab exclusive access to the necessary queues */
7361 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7363 VCreateReservation_r(rvp);
7365 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7366 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7367 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7368 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7371 /* make sure multiple threads don't race to update */
7372 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7373 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7377 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7378 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7379 VCancelReservation_r(rvp);
7384 * switch a volume between two VLRU queues.
7386 * @param[in] vp pointer to volume object
7387 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7388 * @param[in] append controls whether the volume will be appended or
7389 * prepended to the queue. A nonzero value means it will
7390 * be appended; zero means it will be prepended.
7392 * @pre The new (and old, if applicable) queue(s) must either be owned
7393 * exclusively by the calling thread for asynchronous manipulation,
7394 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7395 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7396 * for further details of the queue asynchronous processing mechanism.
7398 * @post If the volume object was already on a VLRU queue, it is
7399 * removed from the queue. Depending on the value of the append
7400 * parameter, the volume object is either appended or prepended
7401 * to the VLRU queue referenced by the new_idx parameter.
7405 * @see VLRU_BeginExclusive_r
7406 * @see VLRU_EndExclusive_r
7409 * @internal volume package internal use only.
7412 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7414 if (queue_IsNotOnQueue(&vp->vlru))
7417 queue_Remove(&vp->vlru);
7418 volume_LRU.q[vp->vlru.idx].len--;
7420 /* put the volume back on the correct generational queue */
7422 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7424 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7427 volume_LRU.q[new_idx].len++;
7428 vp->vlru.idx = new_idx;
7432 * VLRU background thread.
7434 * The VLRU Scanner Thread is responsible for periodically scanning through
7435 * each VLRU queue looking for volumes which should be moved to another
7436 * queue, or soft detached.
7438 * @param[in] args unused thread arguments parameter
7440 * @return unused thread return value
7441 * @retval NULL always
7443 * @internal volume package internal use only.
7446 VLRU_ScannerThread(void * args)
7448 afs_uint32 now, min_delay, delay;
7449 int i, min_idx, min_op, overdue, state;
7451 /* set t=0 for promotion cycle to be
7452 * fileserver startup */
7453 now = FT_ApproxTime();
7454 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7455 volume_LRU.last_promotion[i] = now;
7458 /* don't start the scanner until VLRU_offline_thresh
7459 * plus a small delay for VInitVolumePackage2 to finish
7462 sleep(VLRU_offline_thresh + 60);
7464 /* set t=0 for scan cycle to be now */
7465 now = FT_ApproxTime();
7466 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7467 volume_LRU.last_scan[i] = now;
7471 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7472 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7475 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7476 /* check to see if we've been asked to pause */
7477 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7478 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7479 opr_cv_broadcast(&volume_LRU.cv);
7481 VOL_CV_WAIT(&volume_LRU.cv);
7482 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7485 /* scheduling can happen outside the glock */
7488 /* figure out what is next on the schedule */
7490 /* figure out a potential schedule for the new generation first */
7492 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7495 if (min_delay > volume_LRU.scan_interval[0]) {
7496 /* unsigned overflow -- we're overdue to run this scan */
7501 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7503 i = VLRU_QUEUE_CANDIDATE;
7504 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7505 if (delay < min_delay) {
7509 if (delay > volume_LRU.scan_interval[i]) {
7510 /* unsigned overflow -- we're overdue to run this scan */
7517 /* if we're still not overdue for something, figure out schedules for promotions */
7518 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7519 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7520 if (delay < min_delay) {
7525 if (delay > volume_LRU.promotion_interval[i]) {
7526 /* unsigned overflow -- we're overdue to run this promotion */
7535 /* sleep as needed */
7540 /* do whatever is next */
7543 VLRU_Promote_r(min_idx);
7544 VLRU_Demote_r(min_idx+1);
7546 VLRU_Scan_r(min_idx);
7548 now = FT_ApproxTime();
7551 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7553 /* signal that scanner is down */
7554 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7555 opr_cv_broadcast(&volume_LRU.cv);
7561 * promote volumes from one VLRU generation to the next.
7563 * This routine scans a VLRU generation looking for volumes which are
7564 * eligible to be promoted to the next generation. All volumes which
7565 * meet the eligibility requirement are promoted.
7567 * Promotion eligibility is based upon meeting both of the following
7570 * @arg The volume has been accessed since the last promotion:
7571 * @c (vp->stats.last_get >= vp->stats.last_promote)
7572 * @arg The last promotion occurred at least
7573 * @c volume_LRU.promotion_interval[idx] seconds ago
7575 * As a performance optimization, promotions are "globbed". In other
7576 * words, we promote arbitrarily large contiguous sublists of elements
7579 * @param[in] idx VLRU queue index to scan
7583 * @internal VLRU internal use only.
7586 VLRU_Promote_r(int idx)
7588 int len, chaining, promote;
7589 afs_uint32 now, thresh;
7590 struct rx_queue *qp, *nqp;
7591 Volume * vp, *start = NULL, *end = NULL;
7593 /* get exclusive access to two chains, and drop the glock */
7594 VLRU_Wait_r(&volume_LRU.q[idx]);
7595 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7596 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7597 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7600 thresh = volume_LRU.promotion_interval[idx];
7601 now = FT_ApproxTime();
7604 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7605 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7606 promote = (((vp->stats.last_promote + thresh) <= now) &&
7607 (vp->stats.last_get >= vp->stats.last_promote));
7615 /* promote and prepend chain */
7616 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7630 /* promote and prepend */
7631 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7635 volume_LRU.q[idx].len -= len;
7636 volume_LRU.q[idx+1].len += len;
7639 /* release exclusive access to the two chains */
7641 volume_LRU.last_promotion[idx] = now;
7642 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7643 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7646 /* run the demotions */
7648 VLRU_Demote_r(int idx)
7651 int len, chaining, demote;
7652 afs_uint32 now, thresh;
7653 struct rx_queue *qp, *nqp;
7654 Volume * vp, *start = NULL, *end = NULL;
7655 Volume ** salv_flag_vec = NULL;
7656 int salv_vec_offset = 0;
7658 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7660 /* get exclusive access to two chains, and drop the glock */
7661 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7662 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7663 VLRU_Wait_r(&volume_LRU.q[idx]);
7664 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7667 /* no big deal if this allocation fails */
7668 if (volume_LRU.q[idx].len) {
7669 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7672 now = FT_ApproxTime();
7673 thresh = volume_LRU.promotion_interval[idx-1];
7676 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7677 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7678 demote = (((vp->stats.last_promote + thresh) <= now) &&
7679 (vp->stats.last_get < (now - thresh)));
7681 /* we now do volume update list DONT_SALVAGE flag setting during
7682 * demotion passes */
7683 if (salv_flag_vec &&
7684 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7686 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7687 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7688 salv_flag_vec[salv_vec_offset++] = vp;
7689 VCreateReservation_r(vp);
7698 /* demote and append chain */
7699 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7713 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7717 volume_LRU.q[idx].len -= len;
7718 volume_LRU.q[idx-1].len += len;
7721 /* release exclusive access to the two chains */
7723 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7724 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7726 /* now go back and set the DONT_SALVAGE flags as appropriate */
7727 if (salv_flag_vec) {
7729 for (i = 0; i < salv_vec_offset; i++) {
7730 vp = salv_flag_vec[i];
7731 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7732 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7733 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7736 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7737 V_dontSalvage(vp) = DONT_SALVAGE;
7738 VUpdateVolume_r(&ec, vp, 0);
7742 VCancelReservation_r(vp);
7744 free(salv_flag_vec);
7748 /* run a pass of the VLRU GC scanner */
7750 VLRU_Scan_r(int idx)
7752 afs_uint32 now, thresh;
7753 struct rx_queue *qp, *nqp;
7757 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7759 /* gain exclusive access to the idx VLRU */
7760 VLRU_Wait_r(&volume_LRU.q[idx]);
7761 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7763 if (idx != VLRU_QUEUE_CANDIDATE) {
7764 /* gain exclusive access to the candidate VLRU */
7765 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7766 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7769 now = FT_ApproxTime();
7770 thresh = now - VLRU_offline_thresh;
7772 /* perform candidate selection and soft detaching */
7773 if (idx == VLRU_QUEUE_CANDIDATE) {
7774 /* soft detach some volumes from the candidate pool */
7778 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7779 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7780 if (i >= VLRU_offline_max) {
7783 /* check timestamp to see if it's a candidate for soft detaching */
7784 if (vp->stats.last_get <= thresh) {
7786 if (VCheckSoftDetach(vp, thresh))
7792 /* scan for volumes to become soft detach candidates */
7793 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7794 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7796 /* check timestamp to see if it's a candidate for soft detaching */
7797 if (vp->stats.last_get <= thresh) {
7798 VCheckSoftDetachCandidate(vp, thresh);
7801 if (!(i&0x7f)) { /* lock coarsening optimization */
7809 /* relinquish exclusive access to the VLRU chains */
7813 volume_LRU.last_scan[idx] = now;
7814 if (idx != VLRU_QUEUE_CANDIDATE) {
7815 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7817 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7820 /* check whether volume is safe to soft detach
7821 * caller MUST NOT hold a ref count on vp */
7823 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7827 if (vp->nUsers || vp->nWaiters)
7830 if (vp->stats.last_get <= thresh) {
7831 ret = VSoftDetachVolume_r(vp, thresh);
7837 /* check whether volume should be made a
7838 * soft detach candidate */
7840 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7843 if (vp->nUsers || vp->nWaiters)
7848 opr_Assert(idx == VLRU_QUEUE_NEW);
7850 if (vp->stats.last_get <= thresh) {
7851 /* move to candidate pool */
7852 queue_Remove(&vp->vlru);
7853 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7854 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7855 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7856 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7864 /* begin exclusive access on VLRU */
7866 VLRU_BeginExclusive_r(struct VLRU_q * q)
7868 opr_Assert(q->busy == 0);
7872 /* end exclusive access on VLRU */
7874 VLRU_EndExclusive_r(struct VLRU_q * q)
7876 opr_Assert(q->busy);
7878 opr_cv_broadcast(&q->cv);
7881 /* wait for another thread to end exclusive access on VLRU */
7883 VLRU_Wait_r(struct VLRU_q * q)
7886 VOL_CV_WAIT(&q->cv);
7891 * volume soft detach
7893 * caller MUST NOT hold a ref count on vp */
7895 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7900 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7902 ts_save = vp->stats.last_get;
7903 if (ts_save > thresh)
7906 if (vp->nUsers || vp->nWaiters)
7909 if (VIsExclusiveState(V_attachState(vp))) {
7913 switch (V_attachState(vp)) {
7914 case VOL_STATE_UNATTACHED:
7915 case VOL_STATE_PREATTACHED:
7916 case VOL_STATE_ERROR:
7917 case VOL_STATE_GOING_OFFLINE:
7918 case VOL_STATE_SHUTTING_DOWN:
7919 case VOL_STATE_SALVAGING:
7920 case VOL_STATE_DELETED:
7921 volume_LRU.q[vp->vlru.idx].len--;
7923 /* create and cancel a reservation to
7924 * give the volume an opportunity to
7926 VCreateReservation_r(vp);
7927 queue_Remove(&vp->vlru);
7928 vp->vlru.idx = VLRU_QUEUE_INVALID;
7929 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7930 VCancelReservation_r(vp);
7936 /* hold the volume and take it offline.
7937 * no need for reservations, as VHold_r
7938 * takes care of that internally. */
7939 if (VHold_r(vp) == 0) {
7940 /* vhold drops the glock, so now we should
7941 * check to make sure we aren't racing against
7942 * other threads. if we are racing, offlining vp
7943 * would be wasteful, and block the scanner for a while
7947 (vp->shuttingDown) ||
7948 (vp->goingOffline) ||
7949 (vp->stats.last_get != ts_save)) {
7950 /* looks like we're racing someone else. bail */
7954 /* pull it off the VLRU */
7955 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7956 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7957 queue_Remove(&vp->vlru);
7958 vp->vlru.idx = VLRU_QUEUE_INVALID;
7959 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7961 /* take if offline */
7962 VOffline_r(vp, "volume has been soft detached");
7964 /* invalidate the volume header cache */
7965 FreeVolumeHeader(vp);
7968 IncUInt64(&VStats.soft_detaches);
7969 vp->stats.soft_detaches++;
7971 /* put in pre-attached state so demand
7972 * attacher can work on it */
7973 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7979 #endif /* AFS_DEMAND_ATTACH_FS */
7982 /***************************************************/
7983 /* Volume Header Cache routines */
7984 /***************************************************/
7987 * volume header cache.
7989 struct volume_hdr_LRU_t volume_hdr_LRU;
7992 * initialize the volume header cache.
7994 * @param[in] howMany number of header cache entries to preallocate
7996 * @pre VOL_LOCK held. Function has never been called before.
7998 * @post howMany cache entries are allocated, initialized, and added
7999 * to the LRU list. Header cache statistics are initialized.
8001 * @note only applicable to fileServer program type. Should only be
8002 * called once during volume package initialization.
8004 * @internal volume package internal use only.
8007 VInitVolumeHeaderCache(afs_uint32 howMany)
8009 struct volHeader *hp;
8010 if (programType != fileServer)
8012 queue_Init(&volume_hdr_LRU);
8013 volume_hdr_LRU.stats.free = 0;
8014 volume_hdr_LRU.stats.used = howMany;
8015 volume_hdr_LRU.stats.attached = 0;
8016 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8017 opr_Assert(hp != NULL);
8020 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8021 * to ensure they have the right values
8023 ReleaseVolumeHeader(hp++);
8026 /* get a volume header off of the volume header LRU.
8028 * @return volume header
8029 * @retval NULL no usable volume header is available on the LRU
8031 * @pre VOL_LOCK held
8033 * @post for DAFS, if the returned header is associated with a volume, that
8034 * volume is NOT in an exclusive state
8036 * @internal volume package internal use only.
8038 #ifdef AFS_DEMAND_ATTACH_FS
8039 static struct volHeader*
8040 GetVolHeaderFromLRU(void)
8042 struct volHeader *hd = NULL, *qh, *nqh;
8043 /* Usually, a volume in an exclusive state will not have its header on
8044 * the LRU. However, it is possible for this to occur when a salvage
8045 * request is received over FSSYNC, and possibly in other corner cases.
8046 * So just skip over headers whose volumes are in an exclusive state. We
8047 * could VWaitExclusiveState_r instead, but not waiting is faster and
8049 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8050 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8058 #else /* AFS_DEMAND_ATTACH_FS */
8059 static struct volHeader*
8060 GetVolHeaderFromLRU(void)
8062 struct volHeader *hd = NULL;
8063 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8064 hd = queue_First(&volume_hdr_LRU, volHeader);
8069 #endif /* !AFS_DEMAND_ATTACH_FS */
8072 * get a volume header and attach it to the volume object.
8074 * @param[in] vp pointer to volume object
8076 * @return cache entry status
8077 * @retval 0 volume header was newly attached; cache data is invalid
8078 * @retval 1 volume header was previously attached; cache data is valid
8080 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8082 * @post volume header attached to volume object. if necessary, header cache
8083 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8085 * @note VOL_LOCK may be dropped
8087 * @warning this interface does not load header data from disk. it merely
8088 * attaches a header object to the volume object, and may sync the old
8089 * header cache data out to disk in the process.
8091 * @internal volume package internal use only.
8094 GetVolumeHeader(Volume * vp)
8097 struct volHeader *hd;
8099 static int everLogged = 0;
8101 #ifdef AFS_DEMAND_ATTACH_FS
8102 VolState vp_save = 0, back_save = 0;
8104 /* XXX debug 9/19/05 we've apparently got
8105 * a ref counting bug somewhere that's
8106 * breaking the nUsers == 0 => header on LRU
8108 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8109 Log("nUsers == 0, but header not on LRU\n");
8114 old = (vp->header != NULL); /* old == volume already has a header */
8116 if (programType != fileServer) {
8117 /* for volume utilities, we allocate volHeaders as needed */
8119 hd = calloc(1, sizeof(*vp->header));
8120 opr_Assert(hd != NULL);
8123 #ifdef AFS_DEMAND_ATTACH_FS
8124 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8128 /* for the fileserver, we keep a volume header cache */
8130 /* the header we previously dropped in the lru is
8131 * still available. pull it off the lru and return */
8134 opr_Assert(hd->back == vp);
8135 #ifdef AFS_DEMAND_ATTACH_FS
8136 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8139 hd = GetVolHeaderFromLRU();
8141 /* LRU is empty, so allocate a new volHeader
8142 * this is probably indicative of a leak, so let the user know */
8143 hd = calloc(1, sizeof(struct volHeader));
8144 opr_Assert(hd != NULL);
8146 Log("****Allocated more volume headers, probably leak****\n");
8149 volume_hdr_LRU.stats.free++;
8152 /* this header used to belong to someone else.
8153 * we'll need to check if the header needs to
8154 * be sync'd out to disk */
8156 #ifdef AFS_DEMAND_ATTACH_FS
8157 /* GetVolHeaderFromLRU had better not give us back a header
8158 * with a volume in exclusive state... */
8159 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8162 if (hd->diskstuff.inUse) {
8163 /* volume was in use, so we'll need to sync
8164 * its header to disk */
8166 #ifdef AFS_DEMAND_ATTACH_FS
8167 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8168 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8169 VCreateReservation_r(hd->back);
8173 WriteVolumeHeader_r(&error, hd->back);
8174 /* Ignore errors; catch them later */
8176 #ifdef AFS_DEMAND_ATTACH_FS
8181 hd->back->header = NULL;
8182 #ifdef AFS_DEMAND_ATTACH_FS
8183 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8185 if (hd->diskstuff.inUse) {
8186 VChangeState_r(hd->back, back_save);
8187 VCancelReservation_r(hd->back);
8188 VChangeState_r(vp, vp_save);
8192 volume_hdr_LRU.stats.attached++;
8196 #ifdef AFS_DEMAND_ATTACH_FS
8197 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8200 volume_hdr_LRU.stats.free--;
8201 volume_hdr_LRU.stats.used++;
8203 IncUInt64(&VStats.hdr_gets);
8204 #ifdef AFS_DEMAND_ATTACH_FS
8205 IncUInt64(&vp->stats.hdr_gets);
8206 vp->stats.last_hdr_get = FT_ApproxTime();
8213 * make sure volume header is attached and contains valid cache data.
8215 * @param[out] ec outbound error code
8216 * @param[in] vp pointer to volume object
8218 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8220 * @post header cache entry attached, and loaded with valid data, or
8221 * *ec is nonzero, and the header is released back into the LRU.
8223 * @internal volume package internal use only.
8226 LoadVolumeHeader(Error * ec, Volume * vp)
8228 #ifdef AFS_DEMAND_ATTACH_FS
8229 VolState state_save;
8233 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8234 IncUInt64(&VStats.hdr_loads);
8235 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8238 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8239 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8241 IncUInt64(&vp->stats.hdr_loads);
8242 now = FT_ApproxTime();
8246 V_attachFlags(vp) |= VOL_HDR_LOADED;
8247 vp->stats.last_hdr_load = now;
8249 VChangeState_r(vp, state_save);
8251 #else /* AFS_DEMAND_ATTACH_FS */
8253 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8254 IncUInt64(&VStats.hdr_loads);
8256 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8257 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8260 #endif /* AFS_DEMAND_ATTACH_FS */
8262 /* maintain (nUsers==0) => header in LRU invariant */
8263 FreeVolumeHeader(vp);
8268 * release a header cache entry back into the LRU list.
8270 * @param[in] hd pointer to volume header cache object
8272 * @pre VOL_LOCK held.
8274 * @post header cache object appended onto end of LRU list.
8276 * @note only applicable to fileServer program type.
8278 * @note used to place a header cache entry back into the
8279 * LRU pool without invalidating it as a cache entry.
8281 * @internal volume package internal use only.
8284 ReleaseVolumeHeader(struct volHeader *hd)
8286 if (programType != fileServer)
8288 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8290 queue_Append(&volume_hdr_LRU, hd);
8291 #ifdef AFS_DEMAND_ATTACH_FS
8293 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8296 volume_hdr_LRU.stats.free++;
8297 volume_hdr_LRU.stats.used--;
8301 * free/invalidate a volume header cache entry.
8303 * @param[in] vp pointer to volume object
8305 * @pre VOL_LOCK is held.
8307 * @post For fileserver, header cache entry is returned to LRU, and it is
8308 * invalidated as a cache entry. For volume utilities, the header
8309 * cache entry is freed.
8311 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8312 * whenever it is necessary to invalidate the header cache entry.
8314 * @see ReleaseVolumeHeader
8316 * @internal volume package internal use only.
8319 FreeVolumeHeader(Volume * vp)
8321 struct volHeader *hd = vp->header;
8324 if (programType == fileServer) {
8325 ReleaseVolumeHeader(hd);
8330 #ifdef AFS_DEMAND_ATTACH_FS
8331 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8333 volume_hdr_LRU.stats.attached--;
8338 /***************************************************/
8339 /* Volume Hash Table routines */
8340 /***************************************************/
8343 * set size of volume object hash table.
8345 * @param[in] logsize log(2) of desired hash table size
8347 * @return operation status
8349 * @retval -1 failure
8351 * @pre MUST be called prior to VInitVolumePackage2
8353 * @post Volume Hash Table will have 2^logsize buckets
8356 VSetVolHashSize(int logsize)
8358 /* 64 to 268435456 hash buckets seems like a reasonable range */
8359 if ((logsize < 6 ) || (logsize > 28)) {
8364 VolumeHashTable.Size = opr_jhash_size(logsize);
8365 VolumeHashTable.Mask = opr_jhash_mask(logsize);
8367 /* we can't yet support runtime modification of this
8368 * parameter. we'll need a configuration rwlock to
8369 * make runtime modification feasible.... */
8376 * initialize dynamic data structures for volume hash table.
8378 * @post hash table is allocated, and fields are initialized.
8380 * @internal volume package internal use only.
8383 VInitVolumeHash(void)
8387 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8388 sizeof(VolumeHashChainHead));
8389 opr_Assert(VolumeHashTable.Table != NULL);
8391 for (i=0; i < VolumeHashTable.Size; i++) {
8392 queue_Init(&VolumeHashTable.Table[i]);
8393 #ifdef AFS_DEMAND_ATTACH_FS
8394 opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8395 #endif /* AFS_DEMAND_ATTACH_FS */
8400 * add a volume object to the hash table.
8402 * @param[in] vp pointer to volume object
8403 * @param[in] hashid hash of volume id
8405 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8408 * @post volume is added to hash chain.
8410 * @internal volume package internal use only.
8412 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8413 * asynchronous hash chain reordering to finish.
8416 AddVolumeToHashTable(Volume * vp, VolumeId hashid)
8418 VolumeHashChainHead * head;
8420 if (queue_IsOnQueue(vp))
8423 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8425 #ifdef AFS_DEMAND_ATTACH_FS
8426 /* wait for the hash chain to become available */
8429 V_attachFlags(vp) |= VOL_IN_HASH;
8430 vp->chainCacheCheck = ++head->cacheCheck;
8431 #endif /* AFS_DEMAND_ATTACH_FS */
8434 vp->hashid = hashid;
8435 queue_Append(head, vp);
8439 * delete a volume object from the hash table.
8441 * @param[in] vp pointer to volume object
8443 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8446 * @post volume is removed from hash chain.
8448 * @internal volume package internal use only.
8450 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8451 * asynchronous hash chain reordering to finish.
8454 DeleteVolumeFromHashTable(Volume * vp)
8456 VolumeHashChainHead * head;
8458 if (!queue_IsOnQueue(vp))
8461 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8463 #ifdef AFS_DEMAND_ATTACH_FS
8464 /* wait for the hash chain to become available */
8467 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8469 #endif /* AFS_DEMAND_ATTACH_FS */
8473 /* do NOT reset hashid to zero, as the online
8474 * salvager package may need to know the volume id
8475 * after the volume is removed from the hash */
8479 * lookup a volume object in the hash table given a volume id.
8481 * @param[out] ec error code return
8482 * @param[in] volumeId volume id
8483 * @param[in] hint volume object which we believe could be the correct
8486 * @return volume object pointer
8487 * @retval NULL no such volume id is registered with the hash table.
8489 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8492 * @post volume object with the given id is returned. volume object and
8493 * hash chain access statistics are updated. hash chain may have
8496 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8497 * asynchronous hash chain reordering operation to finish, or
8498 * in order for us to perform an asynchronous chain reordering.
8500 * @note Hash chain reorderings occur when the access count for the
8501 * volume object being looked up exceeds the sum of the previous
8502 * node's (the node ahead of it in the hash chain linked list)
8503 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8505 * @note For DAFS, the hint parameter allows us to short-circuit if the
8506 * cacheCheck fields match between the hash chain head and the
8507 * hint volume object.
8510 VLookupVolume_r(Error * ec, VolumeId volumeId, Volume * hint)
8514 #ifdef AFS_DEMAND_ATTACH_FS
8517 VolumeHashChainHead * head;
8520 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8522 #ifdef AFS_DEMAND_ATTACH_FS
8523 /* wait for the hash chain to become available */
8526 /* check to see if we can short circuit without walking the hash chain */
8527 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8528 IncUInt64(&hint->stats.hash_short_circuits);
8531 #endif /* AFS_DEMAND_ATTACH_FS */
8533 /* someday we need to either do per-chain locks, RWlocks,
8534 * or both for volhash access.
8535 * (and move to a data structure with better cache locality) */
8537 /* search the chain for this volume id */
8538 for(queue_Scan(head, vp, np, Volume)) {
8540 if (vp->hashid == volumeId) {
8545 if (queue_IsEnd(head, vp)) {
8549 #ifdef AFS_DEMAND_ATTACH_FS
8550 /* update hash chain statistics */
8553 FillInt64(lks, 0, looks);
8554 AddUInt64(head->looks, lks, &head->looks);
8555 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8556 IncUInt64(&head->gets);
8561 IncUInt64(&vp->stats.hash_lookups);
8563 /* for demand attach fileserver, we permit occasional hash chain reordering
8564 * so that frequently looked up volumes move towards the head of the chain */
8565 pp = queue_Prev(vp, Volume);
8566 if (!queue_IsEnd(head, pp)) {
8567 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8568 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8569 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8570 VReorderHash_r(head, pp, vp);
8574 /* update the short-circuit cache check */
8575 vp->chainCacheCheck = head->cacheCheck;
8577 #endif /* AFS_DEMAND_ATTACH_FS */
8582 #ifdef AFS_DEMAND_ATTACH_FS
8583 /* perform volume hash chain reordering.
8585 * advance a subchain beginning at vp ahead of
8586 * the adjacent subchain ending at pp */
8588 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8590 Volume *tp, *np, *lp;
8591 afs_uint64 move_thresh;
8593 /* this should never be called if the chain is already busy, so
8594 * no need to wait for other exclusive chain ops to finish */
8596 /* this is a rather heavy set of operations,
8597 * so let's set the chain busy flag and drop
8599 VHashBeginExclusive_r(head);
8602 /* scan forward in the chain from vp looking for the last element
8603 * in the chain we want to advance */
8604 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8605 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8606 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8607 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8611 lp = queue_Prev(tp, Volume);
8613 /* scan backwards from pp to determine where to splice and
8614 * insert the subchain we're advancing */
8615 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8616 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8620 tp = queue_Next(tp, Volume);
8622 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8623 queue_MoveChainBefore(tp,vp,lp);
8626 IncUInt64(&VStats.hash_reorders);
8628 IncUInt64(&head->reorders);
8630 /* wake up any threads waiting for the hash chain */
8631 VHashEndExclusive_r(head);
8635 /* demand-attach fs volume hash
8636 * asynchronous exclusive operations */
8639 * begin an asynchronous exclusive operation on a volume hash chain.
8641 * @param[in] head pointer to volume hash chain head object
8643 * @pre VOL_LOCK held. hash chain is quiescent.
8645 * @post hash chain marked busy.
8647 * @note this interface is used in conjunction with VHashEndExclusive_r and
8648 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8649 * volume hash chain. Its main use case is hash chain reordering, which
8650 * has the potential to be a highly latent operation.
8652 * @see VHashEndExclusive_r
8657 * @internal volume package internal use only.
8660 VHashBeginExclusive_r(VolumeHashChainHead * head)
8662 opr_Assert(head->busy == 0);
8667 * relinquish exclusive ownership of a volume hash chain.
8669 * @param[in] head pointer to volume hash chain head object
8671 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8673 * @post hash chain is marked quiescent. threads awaiting use of
8674 * chain are awakened.
8676 * @see VHashBeginExclusive_r
8681 * @internal volume package internal use only.
8684 VHashEndExclusive_r(VolumeHashChainHead * head)
8686 opr_Assert(head->busy);
8688 opr_cv_broadcast(&head->chain_busy_cv);
8692 * wait for all asynchronous operations on a hash chain to complete.
8694 * @param[in] head pointer to volume hash chain head object
8696 * @pre VOL_LOCK held.
8698 * @post hash chain object is quiescent.
8700 * @see VHashBeginExclusive_r
8701 * @see VHashEndExclusive_r
8705 * @note This interface should be called before any attempt to
8706 * traverse the hash chain. It is permissible for a thread
8707 * to gain exclusive access to the chain, and then perform
8708 * latent operations on the chain asynchronously wrt the
8711 * @warning if waiting is necessary, VOL_LOCK is dropped
8713 * @internal volume package internal use only.
8716 VHashWait_r(VolumeHashChainHead * head)
8718 while (head->busy) {
8719 VOL_CV_WAIT(&head->chain_busy_cv);
8722 #endif /* AFS_DEMAND_ATTACH_FS */
8725 /***************************************************/
8726 /* Volume by Partition List routines */
8727 /***************************************************/
8730 * demand attach fileserver adds a
8731 * linked list of volumes to each
8732 * partition object, thus allowing
8733 * for quick enumeration of all
8734 * volumes on a partition
8737 #ifdef AFS_DEMAND_ATTACH_FS
8739 * add a volume to its disk partition VByPList.
8741 * @param[in] vp pointer to volume object
8743 * @pre either the disk partition VByPList is owned exclusively
8744 * by the calling thread, or the list is quiescent and
8747 * @post volume is added to disk partition VByPList
8751 * @warning it is the caller's responsibility to ensure list
8754 * @see VVByPListWait_r
8755 * @see VVByPListBeginExclusive_r
8756 * @see VVByPListEndExclusive_r
8758 * @internal volume package internal use only.
8761 AddVolumeToVByPList_r(Volume * vp)
8763 if (queue_IsNotOnQueue(&vp->vol_list)) {
8764 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8765 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8766 vp->partition->vol_list.len++;
8771 * delete a volume from its disk partition VByPList.
8773 * @param[in] vp pointer to volume object
8775 * @pre either the disk partition VByPList is owned exclusively
8776 * by the calling thread, or the list is quiescent and
8779 * @post volume is removed from the disk partition VByPList
8783 * @warning it is the caller's responsibility to ensure list
8786 * @see VVByPListWait_r
8787 * @see VVByPListBeginExclusive_r
8788 * @see VVByPListEndExclusive_r
8790 * @internal volume package internal use only.
8793 DeleteVolumeFromVByPList_r(Volume * vp)
8795 if (queue_IsOnQueue(&vp->vol_list)) {
8796 queue_Remove(&vp->vol_list);
8797 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8798 vp->partition->vol_list.len--;
8803 * begin an asynchronous exclusive operation on a VByPList.
8805 * @param[in] dp pointer to disk partition object
8807 * @pre VOL_LOCK held. VByPList is quiescent.
8809 * @post VByPList marked busy.
8811 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8812 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8815 * @see VVByPListEndExclusive_r
8816 * @see VVByPListWait_r
8820 * @internal volume package internal use only.
8822 /* take exclusive control over the list */
8824 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8826 opr_Assert(dp->vol_list.busy == 0);
8827 dp->vol_list.busy = 1;
8831 * relinquish exclusive ownership of a VByPList.
8833 * @param[in] dp pointer to disk partition object
8835 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8837 * @post VByPList is marked quiescent. threads awaiting use of
8838 * the list are awakened.
8840 * @see VVByPListBeginExclusive_r
8841 * @see VVByPListWait_r
8845 * @internal volume package internal use only.
8848 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8850 opr_Assert(dp->vol_list.busy);
8851 dp->vol_list.busy = 0;
8852 opr_cv_broadcast(&dp->vol_list.cv);
8856 * wait for all asynchronous operations on a VByPList to complete.
8858 * @param[in] dp pointer to disk partition object
8860 * @pre VOL_LOCK is held.
8862 * @post disk partition's VByP list is quiescent
8866 * @note This interface should be called before any attempt to
8867 * traverse the VByPList. It is permissible for a thread
8868 * to gain exclusive access to the list, and then perform
8869 * latent operations on the list asynchronously wrt the
8872 * @warning if waiting is necessary, VOL_LOCK is dropped
8874 * @see VVByPListEndExclusive_r
8875 * @see VVByPListBeginExclusive_r
8877 * @internal volume package internal use only.
8880 VVByPListWait_r(struct DiskPartition64 * dp)
8882 while (dp->vol_list.busy) {
8883 VOL_CV_WAIT(&dp->vol_list.cv);
8886 #endif /* AFS_DEMAND_ATTACH_FS */
8888 /***************************************************/
8889 /* Volume Cache Statistics routines */
8890 /***************************************************/
8893 VPrintCacheStats_r(void)
8895 struct VnodeClassInfo *vcp;
8896 vcp = &VnodeClassInfo[vLarge];
8897 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);
8898 vcp = &VnodeClassInfo[vSmall];
8899 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);
8900 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8901 "%"AFS_INT64_FMT" replacements\n",
8902 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8906 VPrintCacheStats(void)
8909 VPrintCacheStats_r();
8913 #ifdef AFS_DEMAND_ATTACH_FS
8915 UInt64ToDouble(afs_uint64 * x)
8917 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8919 SplitInt64(*x, h, l);
8920 return (((double)h) * c32) + ((double) l);
8924 DoubleToPrintable(double x, char * buf, int len)
8926 static double billion = 1000000000.0;
8929 y[0] = (afs_uint32) (x / (billion * billion));
8930 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8931 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8934 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8936 snprintf(buf, len, "%d%09d", y[1], y[2]);
8938 snprintf(buf, len, "%d", y[2]);
8944 struct VLRUExtStatsEntry {
8948 struct VLRUExtStats {
8954 } queue_info[VLRU_QUEUE_INVALID];
8955 struct VLRUExtStatsEntry * vec;
8959 * add a 256-entry fudge factor onto the vector in case state changes
8960 * out from under us.
8962 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8965 * collect extended statistics for the VLRU subsystem.
8967 * @param[out] stats pointer to stats structure to be populated
8968 * @param[in] nvols number of volumes currently known to exist
8970 * @pre VOL_LOCK held
8972 * @post stats->vec allocated and populated
8974 * @return operation status
8979 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8981 afs_uint32 cur, idx, len;
8982 struct rx_queue * qp, * nqp;
8984 struct VLRUExtStatsEntry * vec;
8986 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8987 vec = stats->vec = calloc(len,
8988 sizeof(struct VLRUExtStatsEntry));
8994 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8995 VLRU_Wait_r(&volume_LRU.q[idx]);
8996 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8999 stats->queue_info[idx].start = cur;
9001 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
9003 /* out of space in vec */
9006 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
9007 vec[cur].volid = vp->hashid;
9011 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9014 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9022 #define ENUMTOSTRING(en) #en
9023 #define ENUMCASE(en) \
9024 case en: return ENUMTOSTRING(en)
9027 vlru_idx_to_string(int idx)
9030 ENUMCASE(VLRU_QUEUE_NEW);
9031 ENUMCASE(VLRU_QUEUE_MID);
9032 ENUMCASE(VLRU_QUEUE_OLD);
9033 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9034 ENUMCASE(VLRU_QUEUE_HELD);
9035 ENUMCASE(VLRU_QUEUE_INVALID);
9037 return "**UNKNOWN**";
9042 VPrintExtendedCacheStats_r(int flags)
9045 afs_uint32 vol_sum = 0;
9052 struct stats looks, gets, reorders, len;
9053 struct stats ch_looks, ch_gets, ch_reorders;
9055 VolumeHashChainHead *head;
9057 struct VLRUExtStats vlru_stats;
9059 /* zero out stats */
9060 memset(&looks, 0, sizeof(struct stats));
9061 memset(&gets, 0, sizeof(struct stats));
9062 memset(&reorders, 0, sizeof(struct stats));
9063 memset(&len, 0, sizeof(struct stats));
9064 memset(&ch_looks, 0, sizeof(struct stats));
9065 memset(&ch_gets, 0, sizeof(struct stats));
9066 memset(&ch_reorders, 0, sizeof(struct stats));
9068 for (i = 0; i < VolumeHashTable.Size; i++) {
9069 head = &VolumeHashTable.Table[i];
9072 VHashBeginExclusive_r(head);
9075 ch_looks.sum = UInt64ToDouble(&head->looks);
9076 ch_gets.sum = UInt64ToDouble(&head->gets);
9077 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9079 /* update global statistics */
9081 looks.sum += ch_looks.sum;
9082 gets.sum += ch_gets.sum;
9083 reorders.sum += ch_reorders.sum;
9084 len.sum += (double)head->len;
9085 vol_sum += head->len;
9088 len.min = (double) head->len;
9089 len.max = (double) head->len;
9090 looks.min = ch_looks.sum;
9091 looks.max = ch_looks.sum;
9092 gets.min = ch_gets.sum;
9093 gets.max = ch_gets.sum;
9094 reorders.min = ch_reorders.sum;
9095 reorders.max = ch_reorders.sum;
9097 if (((double)head->len) < len.min)
9098 len.min = (double) head->len;
9099 if (((double)head->len) > len.max)
9100 len.max = (double) head->len;
9101 if (ch_looks.sum < looks.min)
9102 looks.min = ch_looks.sum;
9103 else if (ch_looks.sum > looks.max)
9104 looks.max = ch_looks.sum;
9105 if (ch_gets.sum < gets.min)
9106 gets.min = ch_gets.sum;
9107 else if (ch_gets.sum > gets.max)
9108 gets.max = ch_gets.sum;
9109 if (ch_reorders.sum < reorders.min)
9110 reorders.min = ch_reorders.sum;
9111 else if (ch_reorders.sum > reorders.max)
9112 reorders.max = ch_reorders.sum;
9116 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9117 /* compute detailed per-chain stats */
9118 struct stats hdr_loads, hdr_gets;
9119 double v_looks, v_loads, v_gets;
9121 /* initialize stats with data from first element in chain */
9122 vp = queue_First(head, Volume);
9123 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9124 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9125 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9126 ch_gets.min = ch_gets.max = v_looks;
9127 hdr_loads.min = hdr_loads.max = v_loads;
9128 hdr_gets.min = hdr_gets.max = v_gets;
9129 hdr_loads.sum = hdr_gets.sum = 0;
9131 vp = queue_Next(vp, Volume);
9133 /* pull in stats from remaining elements in chain */
9134 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9135 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9136 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9137 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9139 hdr_loads.sum += v_loads;
9140 hdr_gets.sum += v_gets;
9142 if (v_looks < ch_gets.min)
9143 ch_gets.min = v_looks;
9144 else if (v_looks > ch_gets.max)
9145 ch_gets.max = v_looks;
9147 if (v_loads < hdr_loads.min)
9148 hdr_loads.min = v_loads;
9149 else if (v_loads > hdr_loads.max)
9150 hdr_loads.max = v_loads;
9152 if (v_gets < hdr_gets.min)
9153 hdr_gets.min = v_gets;
9154 else if (v_gets > hdr_gets.max)
9155 hdr_gets.max = v_gets;
9158 /* compute per-chain averages */
9159 ch_gets.avg = ch_gets.sum / ((double)head->len);
9160 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9161 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9163 /* dump per-chain stats */
9164 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9166 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9167 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9168 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9169 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9170 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9171 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9172 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9173 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9174 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9175 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9176 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9177 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9178 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9179 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9180 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9181 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9182 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9183 } else if (flags & VOL_STATS_PER_CHAIN) {
9184 /* dump simple per-chain stats */
9185 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9187 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9188 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9189 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9193 VHashEndExclusive_r(head);
9198 /* compute global averages */
9199 len.avg = len.sum / ((double)VolumeHashTable.Size);
9200 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9201 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9202 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9204 /* dump global stats */
9205 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9206 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9207 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9208 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9209 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9210 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9211 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9212 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9213 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9214 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9215 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9216 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9217 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9218 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9219 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9220 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9221 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9222 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9223 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9224 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9225 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9227 /* print extended disk related statistics */
9229 struct DiskPartition64 * diskP;
9230 afs_uint32 vol_count[VOLMAXPARTS+1];
9231 byte part_exists[VOLMAXPARTS+1];
9235 memset(vol_count, 0, sizeof(vol_count));
9236 memset(part_exists, 0, sizeof(part_exists));
9240 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9242 vol_count[id] = diskP->vol_list.len;
9243 part_exists[id] = 1;
9247 for (i = 0; i <= VOLMAXPARTS; i++) {
9248 if (part_exists[i]) {
9249 /* XXX while this is currently safe, it is a violation
9250 * of the VGetPartitionById_r interface contract. */
9251 diskP = VGetPartitionById_r(i, 0);
9253 Log("Partition %s has %d online volumes\n",
9254 VPartitionPath(diskP), diskP->vol_list.len);
9261 /* print extended VLRU statistics */
9262 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9263 afs_uint32 idx, cur, lpos;
9268 Log("VLRU State Dump:\n\n");
9270 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9271 Log("\t%s:\n", vlru_idx_to_string(idx));
9274 for (cur = vlru_stats.queue_info[idx].start;
9275 cur < vlru_stats.queue_info[idx].len;
9277 line[lpos++] = vlru_stats.vec[cur].volid;
9279 Log("\t\t%u, %u, %u, %u, %u,\n",
9280 line[0], line[1], line[2], line[3], line[4]);
9289 Log("\t\t%u, %u, %u, %u, %u\n",
9290 line[0], line[1], line[2], line[3], line[4]);
9295 free(vlru_stats.vec);
9302 VPrintExtendedCacheStats(int flags)
9305 VPrintExtendedCacheStats_r(flags);
9308 #endif /* AFS_DEMAND_ATTACH_FS */
9311 VCanScheduleSalvage(void)
9313 return vol_opts.canScheduleSalvage;
9319 return vol_opts.canUseFSSYNC;
9323 VCanUseSALVSYNC(void)
9325 return vol_opts.canUseSALVSYNC;
9329 VCanUnsafeAttach(void)
9331 return vol_opts.unsafe_attach;