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);
1849 case VOL_STATE_UNATTACHED:
1850 case VOL_STATE_DELETED:
1852 case VOL_STATE_GOING_OFFLINE:
1853 case VOL_STATE_SHUTTING_DOWN:
1854 case VOL_STATE_ATTACHED:
1857 if (GetLogLevel() >= 5)
1858 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1859 afs_printable_VolumeId_lu(vp->hashid));
1861 /* take the volume offline (drops reference count) */
1862 VOffline_r(vp, "File server was shut down");
1869 VCancelReservation_r(vp);
1873 #endif /* AFS_DEMAND_ATTACH_FS */
1876 /***************************************************/
1877 /* Header I/O routines */
1878 /***************************************************/
1881 HeaderName(bit32 magic)
1884 case VOLUMEINFOMAGIC:
1885 return "volume info";
1886 case SMALLINDEXMAGIC:
1887 return "small index";
1888 case LARGEINDEXMAGIC:
1889 return "large index";
1890 case LINKTABLEMAGIC:
1891 return "link table";
1896 /* open a descriptor for the inode (h),
1897 * read in an on-disk structure into buffer (to) of size (size),
1898 * verify versionstamp in structure has magic (magic) and
1899 * optionally verify version (version) if (version) is nonzero
1902 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1905 struct versionStamp *vsn;
1907 afs_sfsize_t nbytes;
1912 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1920 Log("ReadHeader: Failed to open %s header file "
1921 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1922 PrintInode(stmp, h->ih_ino), errno);
1927 vsn = (struct versionStamp *)to;
1928 nbytes = FDH_PREAD(fdP, to, size, 0);
1930 Log("ReadHeader: Failed to read %s header file "
1931 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1932 PrintInode(stmp, h->ih_ino), errno);
1934 FDH_REALLYCLOSE(fdP);
1937 if (nbytes != size) {
1938 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1939 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%d, read=%d\n",
1940 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1941 PrintInode(stmp, h->ih_ino), size, (int)nbytes);
1943 FDH_REALLYCLOSE(fdP);
1946 if (vsn->magic != magic) {
1947 Log("ReadHeader: Incorrect magic for %s header file "
1948 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=0x%x, read=0x%x\n",
1949 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1950 PrintInode(stmp, h->ih_ino), magic, vsn->magic);
1952 FDH_REALLYCLOSE(fdP);
1958 /* Check is conditional, in case caller wants to inspect version himself */
1959 if (version && vsn->version != version) {
1960 Log("ReadHeader: Incorrect version for %s header file "
1961 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%x, read=%x\n",
1962 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid), PrintInode(stmp, h->ih_ino),
1963 version, vsn->version);
1969 WriteVolumeHeader_r(Error * ec, Volume * vp)
1971 IHandle_t *h = V_diskDataHandle(vp);
1981 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1982 != sizeof(V_disk(vp))) {
1984 FDH_REALLYCLOSE(fdP);
1990 /* VolumeHeaderToDisk
1991 * Allows for storing 64 bit inode numbers in on-disk volume header
1994 /* convert in-memory representation of a volume header to the
1995 * on-disk representation of a volume header */
1997 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2000 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2001 dh->stamp = h->stamp;
2003 dh->parent = h->parent;
2005 #ifdef AFS_64BIT_IOPS_ENV
2006 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2007 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2008 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2009 dh->smallVnodeIndex_hi =
2010 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2011 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2012 dh->largeVnodeIndex_hi =
2013 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2014 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2015 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2017 dh->volumeInfo_lo = h->volumeInfo;
2018 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2019 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2020 dh->linkTable_lo = h->linkTable;
2024 /* DiskToVolumeHeader
2025 * Converts an on-disk representation of a volume header to
2026 * the in-memory representation of a volume header.
2028 * Makes the assumption that AFS has *always*
2029 * zero'd the volume header file so that high parts of inode
2030 * numbers are 0 in older (SGI EFS) volume header files.
2033 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2035 memset(h, 0, sizeof(VolumeHeader_t));
2036 h->stamp = dh->stamp;
2038 h->parent = dh->parent;
2040 #ifdef AFS_64BIT_IOPS_ENV
2042 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2044 h->smallVnodeIndex =
2045 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2046 smallVnodeIndex_hi << 32);
2048 h->largeVnodeIndex =
2049 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2050 largeVnodeIndex_hi << 32);
2052 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2054 h->volumeInfo = dh->volumeInfo_lo;
2055 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2056 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2057 h->linkTable = dh->linkTable_lo;
2062 /***************************************************/
2063 /* Volume Attachment routines */
2064 /***************************************************/
2066 #ifdef AFS_DEMAND_ATTACH_FS
2068 * pre-attach a volume given its path.
2070 * @param[out] ec outbound error code
2071 * @param[in] partition partition path string
2072 * @param[in] name volume id string
2074 * @return volume object pointer
2076 * @note A pre-attached volume will only have its partition
2077 * and hashid fields initialized. At first call to
2078 * VGetVolume, the volume will be fully attached.
2082 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2086 vp = VPreAttachVolumeByName_r(ec, partition, name);
2092 * pre-attach a volume given its path.
2094 * @param[out] ec outbound error code
2095 * @param[in] partition path to vice partition
2096 * @param[in] name volume id string
2098 * @return volume object pointer
2100 * @pre VOL_LOCK held
2102 * @internal volume package internal use only.
2105 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2107 return VPreAttachVolumeById_r(ec,
2109 VolumeNumber(name));
2113 * pre-attach a volume given its path and numeric volume id.
2115 * @param[out] ec error code return
2116 * @param[in] partition path to vice partition
2117 * @param[in] volumeId numeric volume id
2119 * @return volume object pointer
2121 * @pre VOL_LOCK held
2123 * @internal volume package internal use only.
2126 VPreAttachVolumeById_r(Error * ec,
2131 struct DiskPartition64 *partp;
2135 opr_Assert(programType == fileServer);
2137 if (!(partp = VGetPartition_r(partition, 0))) {
2139 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2143 /* ensure that any vp we pass to VPreAttachVolumeByVp_r
2144 * is NOT in exclusive state.
2147 vp = VLookupVolume_r(ec, volumeId, NULL);
2153 if (vp && VIsExclusiveState(V_attachState(vp))) {
2154 VCreateReservation_r(vp);
2155 VWaitExclusiveState_r(vp);
2156 VCancelReservation_r(vp);
2158 goto retry; /* look up volume again */
2161 /* vp == NULL or vp not exclusive both OK */
2163 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2167 * preattach a volume.
2169 * @param[out] ec outbound error code
2170 * @param[in] partp pointer to partition object
2171 * @param[in] vp pointer to volume object
2172 * @param[in] vid volume id
2174 * @return volume object pointer
2176 * @pre VOL_LOCK is held.
2178 * @pre vp (if specified) must not be in exclusive state.
2180 * @warning Returned volume object pointer does not have to
2181 * equal the pointer passed in as argument vp. There
2182 * are potential race conditions which can result in
2183 * the pointers having different values. It is up to
2184 * the caller to make sure that references are handled
2185 * properly in this case.
2187 * @note If there is already a volume object registered with
2188 * the same volume id, its pointer MUST be passed as
2189 * argument vp. Failure to do so will result in a silent
2190 * failure to preattach.
2192 * @internal volume package internal use only.
2195 VPreAttachVolumeByVp_r(Error * ec,
2196 struct DiskPartition64 * partp,
2204 /* don't proceed unless it's safe */
2206 opr_Assert(!VIsExclusiveState(V_attachState(vp)));
2209 /* check to see if pre-attach already happened */
2211 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2212 (V_attachState(vp) != VOL_STATE_DELETED) &&
2213 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2214 !VIsErrorState(V_attachState(vp))) {
2216 * pre-attach is a no-op in all but the following cases:
2218 * - volume is unattached
2219 * - volume is in an error state
2220 * - volume is pre-attached
2222 Log("VPreattachVolumeByVp_r: volume %" AFS_VOLID_FMT " not in quiescent state (state %u flags 0x%x)\n",
2223 afs_printable_VolumeId_lu(vid), V_attachState(vp),
2227 /* we're re-attaching a volume; clear out some old state */
2228 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2230 if (V_partition(vp) != partp) {
2231 /* XXX potential race */
2232 DeleteVolumeFromVByPList_r(vp);
2235 /* if we need to allocate a new Volume struct,
2236 * go ahead and drop the vol glock, otherwise
2237 * do the basic setup synchronised, as it's
2238 * probably not worth dropping the lock */
2241 /* allocate the volume structure */
2242 vp = nvp = calloc(1, sizeof(Volume));
2243 opr_Assert(vp != NULL);
2244 queue_Init(&vp->vnode_list);
2245 queue_Init(&vp->rx_call_list);
2246 opr_cv_init(&V_attachCV(vp));
2249 /* link the volume with its associated vice partition */
2250 vp->device = partp->device;
2251 vp->partition = partp;
2254 vp->specialStatus = 0;
2256 /* if we dropped the lock, reacquire the lock,
2257 * check for pre-attach races, and then add
2258 * the volume to the hash table */
2261 nvp = VLookupVolume_r(ec, vid, NULL);
2266 } else if (nvp) { /* race detected */
2271 /* hack to make up for VChangeState_r() decrementing
2272 * the old state counter */
2273 VStats.state_levels[0]++;
2277 /* put pre-attached volume onto the hash table
2278 * and bring it up to the pre-attached state */
2279 AddVolumeToHashTable(vp, vp->hashid);
2280 AddVolumeToVByPList_r(vp);
2281 VLRU_Init_Node_r(vp);
2282 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2284 if (GetLogLevel() >= 5)
2285 Log("VPreAttachVolumeByVp_r: volume %" AFS_VOLID_FMT " pre-attached\n", afs_printable_VolumeId_lu(vp->hashid));
2293 #endif /* AFS_DEMAND_ATTACH_FS */
2295 /* Attach an existing volume, given its pathname, and return a
2296 pointer to the volume header information. The volume also
2297 normally goes online at this time. An offline volume
2298 must be reattached to make it go online */
2300 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2304 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2310 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2313 struct DiskPartition64 *partp;
2318 #ifdef AFS_DEMAND_ATTACH_FS
2319 VolumeStats stats_save;
2321 #endif /* AFS_DEMAND_ATTACH_FS */
2325 volumeId = VolumeNumber(name);
2327 if (!(partp = VGetPartition_r(partition, 0))) {
2329 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2333 if (VRequiresPartLock()) {
2334 opr_Assert(VInit == 3);
2335 VLockPartition_r(partition);
2336 } else if (programType == fileServer) {
2337 #ifdef AFS_DEMAND_ATTACH_FS
2338 /* lookup the volume in the hash table */
2339 vp = VLookupVolume_r(ec, volumeId, NULL);
2345 /* save any counters that are supposed to
2346 * be monotonically increasing over the
2347 * lifetime of the fileserver */
2348 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2350 memset(&stats_save, 0, sizeof(VolumeStats));
2353 /* if there's something in the hash table, and it's not
2354 * in the pre-attach state, then we may need to detach
2355 * it before proceeding */
2356 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2357 VCreateReservation_r(vp);
2358 VWaitExclusiveState_r(vp);
2360 /* at this point state must be one of:
2370 if (vp->specialStatus == VBUSY)
2373 /* if it's already attached, see if we can return it */
2374 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2375 VGetVolumeByVp_r(ec, vp);
2376 if (V_inUse(vp) == fileServer) {
2377 VCancelReservation_r(vp);
2381 /* otherwise, we need to detach, and attempt to re-attach */
2382 VDetachVolume_r(ec, vp);
2384 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2387 /* if it isn't fully attached, delete from the hash tables,
2388 and let the refcounter handle the rest */
2389 DeleteVolumeFromHashTable(vp);
2390 DeleteVolumeFromVByPList_r(vp);
2393 VCancelReservation_r(vp);
2397 /* pre-attach volume if it hasn't been done yet */
2399 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2400 (V_attachState(vp) == VOL_STATE_DELETED) ||
2401 (V_attachState(vp) == VOL_STATE_ERROR)) {
2403 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2409 opr_Assert(vp != NULL);
2411 /* handle pre-attach races
2413 * multiple threads can race to pre-attach a volume,
2414 * but we can't let them race beyond that
2416 * our solution is to let the first thread to bring
2417 * the volume into an exclusive state win; the other
2418 * threads just wait until it finishes bringing the
2419 * volume online, and then they do a vgetvolumebyvp
2421 if (svp && (svp != vp)) {
2422 /* wait for other exclusive ops to finish */
2423 VCreateReservation_r(vp);
2424 VWaitExclusiveState_r(vp);
2426 /* get a heavyweight ref, kill the lightweight ref, and return */
2427 VGetVolumeByVp_r(ec, vp);
2428 VCancelReservation_r(vp);
2432 /* at this point, we are chosen as the thread to do
2433 * demand attachment for this volume. all other threads
2434 * doing a getvolume on vp->hashid will block until we finish */
2436 /* make sure any old header cache entries are invalidated
2437 * before proceeding */
2438 FreeVolumeHeader(vp);
2440 VChangeState_r(vp, VOL_STATE_ATTACHING);
2442 /* restore any saved counters */
2443 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2444 #else /* AFS_DEMAND_ATTACH_FS */
2445 vp = VGetVolume_r(ec, volumeId);
2447 if (V_inUse(vp) == fileServer)
2449 if (vp->specialStatus == VBUSY)
2451 VDetachVolume_r(ec, vp);
2453 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2457 #endif /* AFS_DEMAND_ATTACH_FS */
2461 strcpy(path, VPartitionPath(partp));
2465 strcat(path, OS_DIRSEP);
2469 vp = (Volume *) calloc(1, sizeof(Volume));
2470 opr_Assert(vp != NULL);
2471 vp->hashid = volumeId;
2472 vp->device = partp->device;
2473 vp->partition = partp;
2474 queue_Init(&vp->vnode_list);
2475 queue_Init(&vp->rx_call_list);
2476 #ifdef AFS_DEMAND_ATTACH_FS
2477 opr_cv_init(&V_attachCV(vp));
2478 #endif /* AFS_DEMAND_ATTACH_FS */
2481 /* attach2 is entered without any locks, and returns
2482 * with vol_glock_mutex held */
2483 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2485 if (VCanUseFSSYNC() && vp) {
2486 #ifdef AFS_DEMAND_ATTACH_FS
2487 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2488 /* mark volume header as in use so that volser crashes lead to a
2489 * salvage attempt */
2490 VUpdateVolume_r(ec, vp, 0);
2492 /* for dafs, we should tell the fileserver, except for V_PEEK
2493 * where we know it is not necessary */
2494 if (mode == V_PEEK) {
2495 vp->needsPutBack = 0;
2497 vp->needsPutBack = VOL_PUTBACK;
2499 #else /* !AFS_DEMAND_ATTACH_FS */
2500 /* duplicate computation in fssync.c about whether the server
2501 * takes the volume offline or not. If the volume isn't
2502 * offline, we must not return it when we detach the volume,
2503 * or the server will abort */
2504 if (mode == V_READONLY || mode == V_PEEK
2505 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2506 vp->needsPutBack = 0;
2508 vp->needsPutBack = VOL_PUTBACK;
2509 #endif /* !AFS_DEMAND_ATTACH_FS */
2511 #ifdef FSSYNC_BUILD_CLIENT
2512 /* Only give back the vol to the fileserver if we checked it out; attach2
2513 * will set checkedOut only if we successfully checked it out from the
2515 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2517 #ifdef AFS_DEMAND_ATTACH_FS
2518 /* If we couldn't attach but we scheduled a salvage, we already
2519 * notified the fileserver; don't online it now */
2520 if (*ec != VSALVAGING)
2521 #endif /* AFS_DEMAND_ATTACH_FS */
2522 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2525 if (programType == fileServer && vp) {
2526 #ifdef AFS_DEMAND_ATTACH_FS
2528 * we can get here in cases where we don't "own"
2529 * the volume (e.g. volume owned by a utility).
2530 * short circuit around potential disk header races.
2532 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2536 VUpdateVolume_r(ec, vp, 0);
2538 Log("VAttachVolume: Error updating volume\n");
2543 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2544 #ifndef AFS_DEMAND_ATTACH_FS
2545 /* This is a hack: by temporarily setting the incore
2546 * dontSalvage flag ON, the volume will be put back on the
2547 * Update list (with dontSalvage OFF again). It will then
2548 * come back in N minutes with DONT_SALVAGE eventually
2549 * set. This is the way that volumes that have never had
2550 * it set get it set; or that volumes that have been
2551 * offline without DONT SALVAGE having been set also
2552 * eventually get it set */
2553 V_dontSalvage(vp) = DONT_SALVAGE;
2554 #endif /* !AFS_DEMAND_ATTACH_FS */
2555 VAddToVolumeUpdateList_r(ec, vp);
2557 Log("VAttachVolume: Error adding volume to update list\n");
2563 if (GetLogLevel() != 0)
2564 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n", afs_printable_VolumeId_lu(V_id(vp)),
2569 if (VRequiresPartLock()) {
2570 VUnlockPartition_r(partition);
2573 #ifdef AFS_DEMAND_ATTACH_FS
2574 /* attach failed; make sure we're in error state */
2575 if (vp && !VIsErrorState(V_attachState(vp))) {
2576 VChangeState_r(vp, VOL_STATE_ERROR);
2578 #endif /* AFS_DEMAND_ATTACH_FS */
2585 #ifdef AFS_DEMAND_ATTACH_FS
2586 /* VAttachVolumeByVp_r
2588 * finish attaching a volume that is
2589 * in a less than fully attached state
2591 /* caller MUST hold a ref count on vp */
2593 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2595 char name[VMAXPATHLEN];
2597 struct DiskPartition64 *partp;
2601 Volume * nvp = NULL;
2602 VolumeStats stats_save;
2606 /* volume utility should never call AttachByVp */
2607 opr_Assert(programType == fileServer);
2609 volumeId = vp->hashid;
2610 partp = vp->partition;
2611 VolumeExternalName_r(volumeId, name, sizeof(name));
2614 /* if another thread is performing a blocking op, wait */
2615 VWaitExclusiveState_r(vp);
2617 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2619 /* if it's already attached, see if we can return it */
2620 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2621 VGetVolumeByVp_r(ec, vp);
2622 if (V_inUse(vp) == fileServer) {
2625 if (vp->specialStatus == VBUSY)
2627 VDetachVolume_r(ec, vp);
2629 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2635 /* pre-attach volume if it hasn't been done yet */
2637 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2638 (V_attachState(vp) == VOL_STATE_DELETED) ||
2639 (V_attachState(vp) == VOL_STATE_ERROR)) {
2640 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2646 VCreateReservation_r(nvp);
2651 opr_Assert(vp != NULL);
2652 VChangeState_r(vp, VOL_STATE_ATTACHING);
2654 /* restore monotonically increasing stats */
2655 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2659 /* compute path to disk header */
2660 strcpy(path, VPartitionPath(partp));
2664 strcat(path, OS_DIRSEP);
2669 * NOTE: attach2 is entered without any locks, and returns
2670 * with vol_glock_mutex held */
2671 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2674 * the event that an error was encountered, or
2675 * the volume was not brought to an attached state
2676 * for any reason, skip to the end. We cannot
2677 * safely call VUpdateVolume unless we "own" it.
2681 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2685 VUpdateVolume_r(ec, vp, 0);
2687 Log("VAttachVolume: Error updating volume %" AFS_VOLID_FMT "\n",
2688 afs_printable_VolumeId_lu(vp->hashid));
2692 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2693 #ifndef AFS_DEMAND_ATTACH_FS
2694 /* This is a hack: by temporarily setting the incore
2695 * dontSalvage flag ON, the volume will be put back on the
2696 * Update list (with dontSalvage OFF again). It will then
2697 * come back in N minutes with DONT_SALVAGE eventually
2698 * set. This is the way that volumes that have never had
2699 * it set get it set; or that volumes that have been
2700 * offline without DONT SALVAGE having been set also
2701 * eventually get it set */
2702 V_dontSalvage(vp) = DONT_SALVAGE;
2703 #endif /* !AFS_DEMAND_ATTACH_FS */
2704 VAddToVolumeUpdateList_r(ec, vp);
2706 Log("VAttachVolume: Error adding volume %" AFS_VOLID_FMT " to update list\n",
2707 afs_printable_VolumeId_lu(vp->hashid));
2713 if (GetLogLevel() != 0)
2714 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n",
2715 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
2718 VCancelReservation_r(nvp);
2721 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2722 if (vp && !VIsErrorState(V_attachState(vp))) {
2723 VChangeState_r(vp, VOL_STATE_ERROR);
2732 * lock a volume on disk (non-blocking).
2734 * @param[in] vp The volume to lock
2735 * @param[in] locktype READ_LOCK or WRITE_LOCK
2737 * @return operation status
2738 * @retval 0 success, lock was obtained
2739 * @retval EBUSY a conflicting lock was held by another process
2740 * @retval EIO error acquiring lock
2742 * @pre If we're in the fileserver, vp is in an exclusive state
2744 * @pre vp is not already locked
2747 VLockVolumeNB(Volume *vp, int locktype)
2751 opr_Assert(programType != fileServer
2752 || VIsExclusiveState(V_attachState(vp)));
2753 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2755 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2757 V_attachFlags(vp) |= VOL_LOCKED;
2764 * unlock a volume on disk that was locked with VLockVolumeNB.
2766 * @param[in] vp volume to unlock
2768 * @pre If we're in the fileserver, vp is in an exclusive state
2770 * @pre vp has already been locked
2773 VUnlockVolume(Volume *vp)
2775 opr_Assert(programType != fileServer
2776 || VIsExclusiveState(V_attachState(vp)));
2777 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2779 VUnlockVolumeById(vp->hashid, vp->partition);
2781 V_attachFlags(vp) &= ~VOL_LOCKED;
2783 #endif /* AFS_DEMAND_ATTACH_FS */
2786 * read in a vol header, possibly lock the vol header, and possibly check out
2787 * the vol header from the fileserver, as part of volume attachment.
2789 * @param[out] ec error code
2790 * @param[in] vp volume pointer object
2791 * @param[in] partp disk partition object of the attaching partition
2792 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2794 * @param[in] peek 1 to just try to read in the volume header and make sure
2795 * we don't try to lock the vol, or check it out from
2796 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2798 * @param[out] acheckedOut If we successfully checked-out the volume from
2799 * the fileserver (if we needed to), this is set
2800 * to 1, otherwise it is untouched.
2802 * @note As part of DAFS volume attachment, the volume header may be either
2803 * read- or write-locked to ensure mutual exclusion of certain volume
2804 * operations. In some cases in order to determine whether we need to
2805 * read- or write-lock the header, we need to read in the header to see
2806 * if the volume is RW or not. So, if we read in the header under a
2807 * read-lock and determine that we actually need a write-lock on the
2808 * volume header, this function will drop the read lock, acquire a write
2809 * lock, and read the header in again.
2812 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2813 int mode, int peek, int *acheckedOut)
2815 struct VolumeDiskHeader diskHeader;
2816 struct VolumeHeader header;
2819 int lock_tries = 0, checkout_tries = 0;
2821 VolumeId volid = vp->hashid;
2822 #ifdef FSSYNC_BUILD_CLIENT
2823 int checkout, done_checkout = 0;
2824 #endif /* FSSYNC_BUILD_CLIENT */
2825 #ifdef AFS_DEMAND_ATTACH_FS
2826 int locktype = 0, use_locktype = -1;
2827 #endif /* AFS_DEMAND_ATTACH_FS */
2833 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2834 Log("VAttachVolume: retried too many times trying to lock header for "
2835 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2836 VPartitionPath(partp));
2840 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2841 Log("VAttachVolume: retried too many times trying to checkout "
2842 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2843 VPartitionPath(partp));
2848 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2849 /* short-circuit the 'volume does not exist' case */
2854 #ifdef FSSYNC_BUILD_CLIENT
2855 checkout = !done_checkout;
2857 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2859 memset(&res, 0, sizeof(res));
2861 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2864 if (res.hdr.reason == FSYNC_SALVAGE) {
2865 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2866 afs_printable_uint32_lu(volid));
2869 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2870 afs_printable_uint32_lu(volid));
2871 *ec = VNOVOL; /* XXXX */
2879 #ifdef AFS_DEMAND_ATTACH_FS
2880 if (use_locktype < 0) {
2881 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2882 * if it turns out to be RW */
2883 locktype = VVolLockType(mode, 0);
2886 /* a previous try says we should use use_locktype to lock the volume,
2888 locktype = use_locktype;
2891 if (!peek && locktype) {
2892 code = VLockVolumeNB(vp, locktype);
2894 if (code == EBUSY) {
2895 Log("VAttachVolume: another program has vol %lu locked\n",
2896 afs_printable_uint32_lu(volid));
2898 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2899 code, afs_printable_uint32_lu(volid));
2906 #endif /* AFS_DEMAND_ATTACH_FS */
2908 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2918 DiskToVolumeHeader(&header, &diskHeader);
2920 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2921 header.largeVnodeIndex);
2922 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2923 header.smallVnodeIndex);
2924 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2926 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2929 /* only need to do this once */
2931 GetVolumeHeader(vp);
2935 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2936 /* demand attach changes the V_PEEK mechanism
2938 * we can now suck the current disk data structure over
2939 * the fssync interface without going to disk
2941 * (technically, we don't need to restrict this feature
2942 * to demand attach fileservers. However, I'm trying
2943 * to limit the number of common code changes)
2945 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2947 res.payload.len = sizeof(VolumeDiskData);
2948 res.payload.buf = &(V_disk(vp));
2950 if (FSYNC_VolOp(vp->hashid,
2952 FSYNC_VOL_QUERY_HDR,
2955 goto disk_header_loaded;
2958 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2959 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2960 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2962 #ifdef AFS_DEMAND_ATTACH_FS
2965 IncUInt64(&VStats.hdr_loads);
2966 IncUInt64(&vp->stats.hdr_loads);
2968 #endif /* AFS_DEMAND_ATTACH_FS */
2971 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2972 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2976 #ifdef AFS_DEMAND_ATTACH_FS
2977 # ifdef FSSYNC_BUILD_CLIENT
2979 # endif /* FSSYNC_BUILD_CLIENT */
2981 /* if the lock type we actually used to lock the volume is different than
2982 * the lock type we should have used, retry with the lock type we should
2984 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2985 if (locktype != use_locktype) {
2989 #endif /* AFS_DEMAND_ATTACH_FS */
2994 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2995 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2997 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2999 if (code == SYNC_DENIED) {
3000 /* must retry checkout; fileserver no longer thinks we have
3006 } else if (code != SYNC_OK) {
3010 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3013 /* either we are going to be called again for a second pass, or we
3014 * encountered an error; clean up in either case */
3016 #ifdef AFS_DEMAND_ATTACH_FS
3017 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3020 #endif /* AFS_DEMAND_ATTACH_FS */
3021 if (vp->linkHandle) {
3022 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3023 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3024 IH_RELEASE(vp->diskDataHandle);
3025 IH_RELEASE(vp->linkHandle);
3031 FreeVolumeHeader(vp);
3041 #ifdef AFS_DEMAND_ATTACH_FS
3043 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3044 Volume *vp, int *acheckedOut)
3048 if (vp->pending_vol_op) {
3052 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3054 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3056 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3057 } else if (code == 0) {
3058 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3061 /* we need the vol header to determine if the volume can be
3062 * left online for the vop, so... get the header */
3066 /* attach header with peek=1 to avoid checking out the volume
3067 * or locking it; we just want the header info, we're not
3068 * messing with the volume itself at all */
3069 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3076 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3077 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3079 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3082 /* make sure we grab a new vol header and re-open stuff on
3083 * actual attachment; we can't keep the data we grabbed, since
3084 * it was not done under a lock and thus not safe */
3085 FreeVolumeHeader(vp);
3086 VReleaseVolumeHandles_r(vp);
3089 /* see if the pending volume op requires exclusive access */
3090 switch (vp->pending_vol_op->vol_op_state) {
3091 case FSSYNC_VolOpPending:
3092 /* this should never happen */
3093 opr_Assert(vp->pending_vol_op->vol_op_state
3094 != FSSYNC_VolOpPending);
3097 case FSSYNC_VolOpRunningUnknown:
3098 /* this should never happen; we resolved 'unknown' above */
3099 opr_Assert(vp->pending_vol_op->vol_op_state
3100 != FSSYNC_VolOpRunningUnknown);
3103 case FSSYNC_VolOpRunningOffline:
3104 /* mark the volume down */
3106 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3108 /* do not set V_offlineMessage here; we don't have ownership of
3109 * the volume (and probably do not have the header loaded), so we
3110 * can't alter the disk header */
3112 /* check to see if we should set the specialStatus flag */
3113 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3114 /* don't overwrite specialStatus if it was already set to
3115 * something else (e.g. VMOVED) */
3116 if (!vp->specialStatus) {
3117 vp->specialStatus = VBUSY;
3129 #endif /* AFS_DEMAND_ATTACH_FS */
3132 * volume attachment helper function.
3134 * @param[out] ec error code
3135 * @param[in] volumeId volume ID of the attaching volume
3136 * @param[in] path full path to the volume header .vol file
3137 * @param[in] partp disk partition object for the attaching partition
3138 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3139 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3140 * DAFS) should already be initialized
3141 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3142 * if there is a volume operation running for this volume
3143 * that should set the volume to VBUSY during its run. 0
3144 * otherwise. (see VVolOpSetVBusy_r)
3145 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3147 * @param[out] acheckedOut If we successfully checked-out the volume from
3148 * the fileserver (if we needed to), this is set
3149 * to 1, otherwise it is 0.
3151 * @return pointer to the semi-attached volume pointer
3152 * @retval NULL an error occurred (check value of *ec)
3153 * @retval vp volume successfully attaching
3155 * @pre no locks held
3157 * @post VOL_LOCK held
3160 attach2(Error * ec, VolumeId volumeId, char *path, struct DiskPartition64 *partp,
3161 Volume * vp, int isbusy, int mode, int *acheckedOut)
3163 /* have we read in the header successfully? */
3164 int read_header = 0;
3166 #ifdef AFS_DEMAND_ATTACH_FS
3167 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3171 /* in the case of an error, to what state should the volume be
3173 VolState error_state = VOL_STATE_ERROR;
3174 #endif /* AFS_DEMAND_ATTACH_FS */
3178 vp->vnodeIndex[vLarge].handle = NULL;
3179 vp->vnodeIndex[vSmall].handle = NULL;
3180 vp->diskDataHandle = NULL;
3181 vp->linkHandle = NULL;
3185 #ifdef AFS_DEMAND_ATTACH_FS
3186 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3188 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3191 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3192 #endif /* !AFS_DEMAND_ATTACH_FS */
3194 if (*ec == VNOVOL) {
3195 /* if the volume doesn't exist, skip straight to 'error' so we don't
3196 * request a salvage */
3197 goto unlocked_error;
3203 /* ensure that we don't override specialStatus if it was set to
3204 * something else (e.g. VMOVED) */
3205 if (isbusy && !vp->specialStatus) {
3206 vp->specialStatus = VBUSY;
3208 vp->shuttingDown = 0;
3209 vp->goingOffline = 0;
3211 #ifdef AFS_DEMAND_ATTACH_FS
3212 vp->stats.last_attach = FT_ApproxTime();
3213 vp->stats.attaches++;
3217 IncUInt64(&VStats.attaches);
3218 vp->cacheCheck = ++VolumeCacheCheck;
3219 /* just in case this ever rolls over */
3220 if (!vp->cacheCheck)
3221 vp->cacheCheck = ++VolumeCacheCheck;
3224 #ifdef AFS_DEMAND_ATTACH_FS
3225 V_attachFlags(vp) |= VOL_HDR_LOADED;
3226 vp->stats.last_hdr_load = vp->stats.last_attach;
3227 #endif /* AFS_DEMAND_ATTACH_FS */
3231 struct IndexFileHeader iHead;
3234 * We just read in the diskstuff part of the header. If the detailed
3235 * volume stats area has not yet been initialized, we should bzero the
3236 * area and mark it as initialized.
3238 if (!(V_stat_initialized(vp))) {
3239 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3240 V_stat_initialized(vp) = 1;
3243 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3244 (char *)&iHead, sizeof(iHead),
3245 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3248 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3253 struct IndexFileHeader iHead;
3255 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3256 (char *)&iHead, sizeof(iHead),
3257 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3260 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3264 #ifdef AFS_NAMEI_ENV
3266 struct versionStamp stamp;
3268 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3269 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3272 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3275 #endif /* AFS_NAMEI_ENV */
3277 #if defined(AFS_DEMAND_ATTACH_FS)
3278 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3280 if (!VCanScheduleSalvage()) {
3281 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3283 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3288 /* volume operation in progress */
3290 /* we have already transitioned the vp away from ATTACHING state, so we
3291 * can go right to the end of attach2, and we do not need to transition
3293 goto error_notbroken;
3295 #else /* AFS_DEMAND_ATTACH_FS */
3297 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3298 goto unlocked_error;
3300 #endif /* AFS_DEMAND_ATTACH_FS */
3302 if (V_needsSalvaged(vp)) {
3303 if (vp->specialStatus)
3304 vp->specialStatus = 0;
3306 #if defined(AFS_DEMAND_ATTACH_FS)
3307 if (!VCanScheduleSalvage()) {
3308 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3310 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3313 #else /* AFS_DEMAND_ATTACH_FS */
3315 #endif /* AFS_DEMAND_ATTACH_FS */
3321 vp->nextVnodeUnique = V_uniquifier(vp);
3323 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3324 if (!V_needsSalvaged(vp)) {
3325 V_needsSalvaged(vp) = 1;
3326 VUpdateVolume_r(ec, vp, 0);
3328 #if defined(AFS_DEMAND_ATTACH_FS)
3329 if (!VCanScheduleSalvage()) {
3330 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3332 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3335 #else /* AFS_DEMAND_ATTACH_FS */
3336 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3338 #endif /* AFS_DEMAND_ATTACH_FS */
3343 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3344 /* Only check destroyMe if we are the fileserver, since the
3345 * volserver et al sometimes need to work with volumes with
3346 * destroyMe set. Examples are 'temporary' volumes the
3347 * volserver creates, and when we create a volume (destroyMe
3348 * is set on creation; sometimes a separate volserver
3349 * transaction is created to clear destroyMe).
3352 #if defined(AFS_DEMAND_ATTACH_FS)
3353 /* schedule a salvage so the volume goes away on disk */
3354 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3355 VChangeState_r(vp, VOL_STATE_ERROR);
3358 #endif /* AFS_DEMAND_ATTACH_FS */
3359 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3364 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3365 #ifndef BITMAP_LATER
3366 if (programType == fileServer && VolumeWriteable(vp)) {
3368 for (i = 0; i < nVNODECLASSES; i++) {
3369 VGetBitmap_r(ec, vp, i);
3371 #ifdef AFS_DEMAND_ATTACH_FS
3372 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3374 #endif /* AFS_DEMAND_ATTACH_FS */
3375 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3381 #endif /* BITMAP_LATER */
3383 if (VInit >= 2 && V_needsCallback(vp)) {
3384 if (V_BreakVolumeCallbacks) {
3385 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3386 afs_printable_uint32_lu(V_id(vp)));
3387 V_needsCallback(vp) = 0;
3389 (*V_BreakVolumeCallbacks) (V_id(vp));
3392 VUpdateVolume_r(ec, vp, 0);
3394 #ifdef FSSYNC_BUILD_CLIENT
3395 else if (VCanUseFSSYNC()) {
3396 afs_int32 fsync_code;
3398 V_needsCallback(vp) = 0;
3400 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3404 V_needsCallback(vp) = 1;
3405 Log("Error trying to tell the fileserver to break callbacks for "
3406 "changed volume %lu; error code %ld\n",
3407 afs_printable_uint32_lu(V_id(vp)),
3408 afs_printable_int32_ld(fsync_code));
3410 VUpdateVolume_r(ec, vp, 0);
3413 #endif /* FSSYNC_BUILD_CLIENT */
3416 Log("VAttachVolume: error %d clearing needsCallback on volume "
3417 "%lu; needs salvage\n", (int)*ec,
3418 afs_printable_uint32_lu(V_id(vp)));
3419 #ifdef AFS_DEMAND_ATTACH_FS
3420 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3422 #else /* !AFS_DEMAND_ATTACH_FS */
3424 #endif /* !AFS_DEMAND_ATTACh_FS */
3429 if (programType == fileServer) {
3430 if (vp->specialStatus)
3431 vp->specialStatus = 0;
3432 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3433 V_inUse(vp) = fileServer;
3434 V_offlineMessage(vp)[0] = '\0';
3436 #ifdef AFS_DEMAND_ATTACH_FS
3437 /* check if the volume is actually usable. only do this for DAFS; for
3438 * non-DAFS, volumes that are not inService/blessed can still be
3439 * attached, even if clients cannot access them. this is relevant
3440 * because for non-DAFS, we try to attach the volume when e.g.
3441 * volserver gives us back then vol when its done with it, but
3442 * volserver may give us back a volume that is not inService/blessed. */
3446 /* Put the vol into PREATTACHED state, so if someone tries to
3447 * access it again, we try to attach, see that we're not blessed,
3448 * and give a VNOVOL error again. Putting it into UNATTACHED state
3449 * would result in a VOFFLINE error instead. */
3450 error_state = VOL_STATE_PREATTACHED;
3452 /* mimic e.g. GetVolume errors */
3453 if (!V_blessed(vp)) {
3454 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3455 FreeVolumeHeader(vp);
3456 } else if (!V_inService(vp)) {
3457 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3458 /* the volume is offline and should be unattached */
3460 error_state = VOL_STATE_UNATTACHED;
3461 FreeVolumeHeader(vp);
3463 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3465 error_state = VOL_STATE_ERROR;
3466 /* see if we can recover */
3467 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3472 #endif /* AFS_DEMAND_ATTACH_FS */
3474 #ifdef AFS_DEMAND_ATTACH_FS
3475 if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3476 V_inUse(vp) = programType;
3477 #endif /* AFS_DEMAND_ATTACH_FS */
3478 V_checkoutMode(vp) = mode;
3481 AddVolumeToHashTable(vp, vp->hashid);
3482 #ifdef AFS_DEMAND_ATTACH_FS
3483 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3486 if ((programType != fileServer) ||
3487 (V_inUse(vp) == fileServer)) {
3488 AddVolumeToVByPList_r(vp);
3490 VChangeState_r(vp, VOL_STATE_ATTACHED);
3492 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3501 #ifdef AFS_DEMAND_ATTACH_FS
3502 if (!VIsErrorState(V_attachState(vp))) {
3503 if (programType != fileServer && *ec == VNOVOL) {
3504 /* do not log anything in this case; it is common for
3505 * non-fileserver programs to fail here with VNOVOL, since that
3506 * is what happens when they simply try to use a volume, but that
3507 * volume doesn't exist. */
3509 } else if (VIsErrorState(error_state)) {
3510 Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3511 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3512 V_attachFlags(vp), *ec);
3514 VChangeState_r(vp, error_state);
3516 #endif /* AFS_DEMAND_ATTACH_FS */
3519 VReleaseVolumeHandles_r(vp);
3522 #ifdef AFS_DEMAND_ATTACH_FS
3524 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3525 /* The salvage could not be scheduled with the salvage server
3526 * due to a hard error. Reset the error code to prevent retry loops by
3528 if (*ec == VSALVAGING) {
3537 #else /* !AFS_DEMAND_ATTACH_FS */
3539 #endif /* !AFS_DEMAND_ATTACH_FS */
3543 /* Attach an existing volume.
3544 The volume also normally goes online at this time.
3545 An offline volume must be reattached to make it go online.
3549 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3553 retVal = VAttachVolume_r(ec, volumeId, mode);
3559 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3562 VGetVolumePath(ec, volumeId, &part, &name);
3566 vp = VGetVolume_r(&error, volumeId);
3568 opr_Assert(V_inUse(vp) == 0);
3569 VDetachVolume_r(ec, vp);
3573 return VAttachVolumeByName_r(ec, part, name, mode);
3576 /* Increment a reference count to a volume, sans context swaps. Requires
3577 * possibly reading the volume header in from the disk, since there's
3578 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3580 * N.B. This call can fail if we can't read in the header!! In this case
3581 * we still guarantee we won't context swap, but the ref count won't be
3582 * incremented (otherwise we'd violate the invariant).
3584 /* NOTE: with the demand attach fileserver extensions, the global lock
3585 * is dropped within VHold */
3586 #ifdef AFS_DEMAND_ATTACH_FS
3588 VHold_r(Volume * vp)
3592 VCreateReservation_r(vp);
3593 VWaitExclusiveState_r(vp);
3595 LoadVolumeHeader(&error, vp);
3597 VCancelReservation_r(vp);
3601 VCancelReservation_r(vp);
3604 #else /* AFS_DEMAND_ATTACH_FS */
3606 VHold_r(Volume * vp)
3610 LoadVolumeHeader(&error, vp);
3616 #endif /* AFS_DEMAND_ATTACH_FS */
3618 /**** volume timeout-related stuff ****/
3620 #ifdef AFS_PTHREAD_ENV
3622 static struct timespec *shutdown_timeout;
3623 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3626 VTimedOut(const struct timespec *ts)
3631 if (ts->tv_sec == 0) {
3632 /* short-circuit; this will have always timed out */
3636 code = gettimeofday(&tv, NULL);
3638 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3639 /* assume no timeout; failure mode is we just wait longer than normal
3640 * instead of returning errors when we shouldn't */
3644 if (tv.tv_sec < ts->tv_sec ||
3645 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3654 * Calculate an absolute timeout.
3656 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3657 * NULL, the memory is not touched
3658 * @param[in] timeout How long the timeout should be from now
3660 * @return timeout to use
3661 * @retval NULL no timeout; wait forever
3662 * @retval non-NULL the given value for "ts"
3666 static struct timespec *
3667 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3677 ts->tv_sec = ts->tv_nsec = 0;
3681 code = gettimeofday(&now, NULL);
3683 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3687 ts->tv_sec = now.tv_sec + timeout;
3688 ts->tv_nsec = now.tv_usec * 1000;
3694 * Initialize the shutdown_timeout global.
3697 VShutdownTimeoutInit(void)
3699 struct timespec *ts;
3701 ts = malloc(sizeof(*ts));
3703 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3705 if (!shutdown_timeout) {
3711 * Figure out the timeout that should be used for waiting for offline volumes.
3713 * @param[out] ats Storage space for a local timeout value if needed
3715 * @return The timeout value that should be used
3716 * @retval NULL No timeout; wait forever for offlining volumes
3717 * @retval non-NULL A pointer to the absolute time that should be used as
3718 * the deadline for waiting for offlining volumes.
3720 * @note If we return non-NULL, the pointer we return may or may not be the
3723 static const struct timespec *
3724 VOfflineTimeout(struct timespec *ats)
3726 if (vol_shutting_down) {
3727 opr_Verify(pthread_once(&shutdown_timeout_once,
3728 VShutdownTimeoutInit) == 0);
3729 return shutdown_timeout;
3731 return VCalcTimeout(ats, vol_opts.offline_timeout);
3735 #else /* AFS_PTHREAD_ENV */
3737 /* Waiting a certain amount of time for offlining volumes is not supported
3738 * for LWP due to a lack of primitives. So, we never time out */
3739 # define VTimedOut(x) (0)
3740 # define VOfflineTimeout(x) (NULL)
3742 #endif /* !AFS_PTHREAD_ENV */
3745 VIsGoingOffline_r(struct Volume *vp)
3749 if (vp->goingOffline) {
3750 if (vp->specialStatus) {
3751 code = vp->specialStatus;
3752 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3763 * Tell the caller if a volume is waiting to go offline.
3765 * @param[in] vp The volume we want to know about
3767 * @return volume status
3768 * @retval 0 volume is not waiting to go offline, go ahead and use it
3769 * @retval nonzero volume is waiting to offline, and give the returned code
3770 * as an error to anyone accessing the volume
3772 * @pre VOL_LOCK is NOT held
3773 * @pre caller holds a heavyweight reference on vp
3776 VIsGoingOffline(struct Volume *vp)
3781 code = VIsGoingOffline_r(vp);
3788 * Register an RX call with a volume.
3790 * @param[inout] ec Error code; if unset when passed in, may be set if
3791 * the volume starts going offline
3792 * @param[out] client_ec @see GetVolume
3793 * @param[in] vp Volume struct
3794 * @param[in] cbv VCallByVol struct containing the RX call to register
3796 * @pre VOL_LOCK held
3797 * @pre caller holds heavy ref on vp
3802 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3805 #ifdef AFS_DEMAND_ATTACH_FS
3807 /* just in case the volume started going offline after we got the
3808 * reference to it... otherwise, if the volume started going
3809 * offline right at the end of GetVolume(), we might race with the
3810 * RX call scanner, and return success and add our cbv to the
3811 * rx_call_list _after_ the scanner has scanned the list. */
3812 *ec = VIsGoingOffline_r(vp);
3818 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3819 VWaitStateChange_r(vp);
3821 #endif /* AFS_DEMAND_ATTACH_FS */
3823 queue_Prepend(&vp->rx_call_list, cbv);
3828 * Deregister an RX call with a volume.
3830 * @param[in] vp Volume struct
3831 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3833 * @pre VOL_LOCK held
3834 * @pre caller holds heavy ref on vp
3839 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3841 if (cbv && queue_IsOnQueue(cbv)) {
3842 #ifdef AFS_DEMAND_ATTACH_FS
3843 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3844 VWaitStateChange_r(vp);
3846 #endif /* AFS_DEMAND_ATTACH_FS */
3852 /***************************************************/
3853 /* get and put volume routines */
3854 /***************************************************/
3857 * put back a heavyweight reference to a volume object.
3859 * @param[in] vp volume object pointer
3861 * @pre VOL_LOCK held
3863 * @post heavyweight volume reference put back.
3864 * depending on state, volume may have been taken offline,
3865 * detached, salvaged, freed, etc.
3867 * @internal volume package internal use only
3870 VPutVolume_r(Volume * vp)
3872 opr_Verify(--vp->nUsers >= 0);
3873 if (vp->nUsers == 0) {
3875 ReleaseVolumeHeader(vp->header);
3876 #ifdef AFS_DEMAND_ATTACH_FS
3877 if (!VCheckDetach(vp)) {
3881 #else /* AFS_DEMAND_ATTACH_FS */
3883 #endif /* AFS_DEMAND_ATTACH_FS */
3888 VPutVolume(Volume * vp)
3896 * Puts a volume reference obtained with VGetVolumeWithCall.
3898 * @param[in] vp Volume struct
3899 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3901 * @pre VOL_LOCK is NOT held
3904 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3907 VDeregisterCall_r(vp, cbv);
3912 /* Get a pointer to an attached volume. The pointer is returned regardless
3913 of whether or not the volume is in service or on/off line. An error
3914 code, however, is returned with an indication of the volume's status */
3916 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3920 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3926 * Get a volume reference associated with an RX call.
3928 * @param[out] ec @see GetVolume
3929 * @param[out] client_ec @see GetVolume
3930 * @param[in] volumeId @see GetVolume
3931 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3932 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3933 * with an error if the volume is going offline.
3934 * @param[in] cbv Contains an RX call to be associated with this volume
3935 * reference. This call may be interrupted if the volume is
3936 * requested to go offline while we hold a ref on it. Give NULL
3937 * to not associate an RX call with this reference.
3939 * @return @see GetVolume
3941 * @note for LWP builds, ts must be NULL
3943 * @note A reference obtained with this function MUST be put back with
3944 * VPutVolumeWithCall
3947 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3948 const struct timespec *ts, struct VCallByVol *cbv)
3952 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3953 VRegisterCall_r(ec, client_ec, retVal, cbv);
3959 VGetVolume_r(Error * ec, VolumeId volumeId)
3961 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3964 /* try to get a volume we've previously looked up */
3965 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3967 VGetVolumeByVp_r(Error * ec, Volume * vp)
3969 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3973 * private interface for getting a volume handle
3975 * @param[out] ec error code (0 if no error)
3976 * @param[out] client_ec wire error code to be given to clients
3977 * @param[in] volumeId ID of the volume we want
3978 * @param[in] hint optional hint for hash lookups, or NULL
3979 * @param[in] timeout absolute deadline for waiting for the volume to go
3980 * offline, if it is going offline. NULL to wait forever.
3982 * @return a volume handle for the specified volume
3983 * @retval NULL an error occurred, or the volume is in such a state that
3984 * we cannot load a header or return any volume struct
3986 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3988 * @note 'timeout' is only checked if the volume is actually going offline; so
3989 * if you pass timeout->tv_sec = 0, this will exhibit typical
3990 * nonblocking behavior.
3992 * @note for LWP builds, 'timeout' must be NULL
3995 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
3996 const struct timespec *timeout)
3999 #ifdef AFS_DEMAND_ATTACH_FS
4000 Volume *avp, * rvp = hint;
4004 * if VInit is zero, the volume package dynamic
4005 * data structures have not been initialized yet,
4006 * and we must immediately return an error
4012 *client_ec = VOFFLINE;
4017 #ifdef AFS_DEMAND_ATTACH_FS
4019 VCreateReservation_r(rvp);
4021 #endif /* AFS_DEMAND_ATTACH_FS */
4028 vp = VLookupVolume_r(ec, volumeId, vp);
4034 #ifdef AFS_DEMAND_ATTACH_FS
4035 if (rvp && (rvp != vp)) {
4036 /* break reservation on old vp */
4037 VCancelReservation_r(rvp);
4040 #endif /* AFS_DEMAND_ATTACH_FS */
4044 /* Until we have reached an initialization level of 2
4045 * we don't know whether this volume exists or not.
4046 * We can't sleep and retry later because before a volume
4047 * is attached, the caller tries to get it first. Just
4048 * return VOFFLINE and the caller can choose whether to
4049 * retry the command or not. */
4058 IncUInt64(&VStats.hdr_gets);
4060 #ifdef AFS_DEMAND_ATTACH_FS
4061 /* block if someone else is performing an exclusive op on this volume */
4064 VCreateReservation_r(rvp);
4066 VWaitExclusiveState_r(vp);
4068 /* short circuit with VNOVOL in the following circumstances:
4071 * - VOL_STATE_SHUTTING_DOWN
4073 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4074 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4081 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4082 * VNOVOL for VOL_STATE_DELETED
4084 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4085 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4086 (V_attachState(vp) == VOL_STATE_DELETED)) {
4087 if (vp->specialStatus) {
4088 *ec = vp->specialStatus;
4089 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4098 /* allowable states:
4105 if (vp->salvage.requested) {
4106 VUpdateSalvagePriority_r(vp);
4109 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4110 if (vp->specialStatus) {
4111 *ec = vp->specialStatus;
4115 avp = VAttachVolumeByVp_r(ec, vp, 0);
4118 /* VAttachVolumeByVp_r can return a pointer
4119 * != the vp passed to it under certain
4120 * conditions; make sure we don't leak
4121 * reservations if that happens */
4123 VCancelReservation_r(rvp);
4125 VCreateReservation_r(rvp);
4136 if (vp->specialStatus) {
4137 *ec = vp->specialStatus;
4142 if (vp->specialStatus) {
4143 *ec = vp->specialStatus;
4156 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4158 /* see CheckVnode() in afsfileprocs.c for an explanation
4159 * of this error code logic */
4160 afs_uint32 now = FT_ApproxTime();
4161 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4164 *client_ec = VRESTARTING;
4172 if (VIsErrorState(V_attachState(vp))) {
4173 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4174 * it, or transition it out of that state */
4183 * this test MUST happen after VAttachVolymeByVp, so we have no
4184 * conflicting vol op. (attach2 would have errored out if we had one;
4185 * specifically attach_check_vop must have detected a conflicting vop)
4187 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4189 #endif /* AFS_DEMAND_ATTACH_FS */
4191 LoadVolumeHeader(ec, vp);
4193 /* Only log the error if it was a totally unexpected error. Simply
4194 * a missing inode is likely to be caused by the volume being deleted */
4195 if (errno != ENXIO || GetLogLevel() != 0)
4196 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4197 afs_printable_VolumeId_lu(vp->hashid));
4198 #ifdef AFS_DEMAND_ATTACH_FS
4199 if (VCanScheduleSalvage()) {
4200 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4205 #else /* AFS_DEMAND_ATTACH_FS */
4208 #endif /* AFS_DEMAND_ATTACH_FS */
4212 if (vp->shuttingDown) {
4218 if (programType == fileServer) {
4219 if (vp->goingOffline) {
4220 if (timeout && VTimedOut(timeout)) {
4221 /* we've timed out; don't wait for the vol */
4223 #ifdef AFS_DEMAND_ATTACH_FS
4224 /* wait for the volume to go offline */
4225 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4226 VTimedWaitStateChange_r(vp, timeout, NULL);
4228 #elif defined(AFS_PTHREAD_ENV)
4229 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4230 #else /* AFS_PTHREAD_ENV */
4231 /* LWP has no timed wait, so the caller better not be
4233 opr_Assert(!timeout);
4234 LWP_WaitProcess(VPutVolume);
4235 #endif /* AFS_PTHREAD_ENV */
4239 if (vp->specialStatus) {
4240 *ec = vp->specialStatus;
4241 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4243 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4250 #ifdef AFS_DEMAND_ATTACH_FS
4251 /* if no error, bump nUsers */
4254 VLRU_UpdateAccess_r(vp);
4257 VCancelReservation_r(rvp);
4260 if (client_ec && !*client_ec) {
4263 #else /* AFS_DEMAND_ATTACH_FS */
4264 /* if no error, bump nUsers */
4271 #endif /* AFS_DEMAND_ATTACH_FS */
4274 opr_Assert(vp || *ec);
4279 /***************************************************/
4280 /* Volume offline/detach routines */
4281 /***************************************************/
4283 /* caller MUST hold a heavyweight ref on vp */
4284 #ifdef AFS_DEMAND_ATTACH_FS
4286 VTakeOffline_r(Volume * vp)
4290 opr_Assert(vp->nUsers > 0);
4291 opr_Assert(programType == fileServer);
4293 VCreateReservation_r(vp);
4294 VWaitExclusiveState_r(vp);
4296 vp->goingOffline = 1;
4297 V_needsSalvaged(vp) = 1;
4299 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4300 VCancelReservation_r(vp);
4302 #else /* AFS_DEMAND_ATTACH_FS */
4304 VTakeOffline_r(Volume * vp)
4306 opr_Assert(vp->nUsers > 0);
4307 opr_Assert(programType == fileServer);
4309 vp->goingOffline = 1;
4310 V_needsSalvaged(vp) = 1;
4312 #endif /* AFS_DEMAND_ATTACH_FS */
4315 VTakeOffline(Volume * vp)
4323 * force a volume offline.
4325 * @param[in] vp volume object pointer
4326 * @param[in] flags flags (see note below)
4328 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4329 * used when VUpdateVolume_r needs to call VForceOffline_r
4330 * (which in turn would normally call VUpdateVolume_r)
4332 * @see VUpdateVolume_r
4334 * @pre VOL_LOCK must be held.
4335 * for DAFS, caller must hold ref.
4337 * @note for DAFS, it _is safe_ to call this function from an
4340 * @post needsSalvaged flag is set.
4341 * for DAFS, salvage is requested.
4342 * no further references to the volume through the volume
4343 * package will be honored.
4344 * all file descriptor and vnode caches are invalidated.
4346 * @warning this is a heavy-handed interface. it results in
4347 * a volume going offline regardless of the current
4348 * reference count state.
4350 * @internal volume package internal use only
4353 VForceOffline_r(Volume * vp, int flags)
4357 #ifdef AFS_DEMAND_ATTACH_FS
4358 VChangeState_r(vp, VOL_STATE_ERROR);
4363 strcpy(V_offlineMessage(vp),
4364 "Forced offline due to internal error: volume needs to be salvaged");
4365 Log("Volume %" AFS_VOLID_FMT " forced offline: it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4368 vp->goingOffline = 0;
4369 V_needsSalvaged(vp) = 1;
4370 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4371 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4374 #ifdef AFS_DEMAND_ATTACH_FS
4375 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4376 #endif /* AFS_DEMAND_ATTACH_FS */
4378 #ifdef AFS_PTHREAD_ENV
4379 opr_cv_broadcast(&vol_put_volume_cond);
4380 #else /* AFS_PTHREAD_ENV */
4381 LWP_NoYieldSignal(VPutVolume);
4382 #endif /* AFS_PTHREAD_ENV */
4384 VReleaseVolumeHandles_r(vp);
4388 * force a volume offline.
4390 * @param[in] vp volume object pointer
4392 * @see VForceOffline_r
4395 VForceOffline(Volume * vp)
4398 VForceOffline_r(vp, 0);
4403 * Iterate over the RX calls associated with a volume, and interrupt them.
4405 * @param[in] vp The volume whose RX calls we want to scan
4407 * @pre VOL_LOCK held
4410 VScanCalls_r(struct Volume *vp)
4412 struct VCallByVol *cbv, *ncbv;
4414 #ifdef AFS_DEMAND_ATTACH_FS
4415 VolState state_save;
4418 if (queue_IsEmpty(&vp->rx_call_list))
4419 return; /* no calls to interrupt */
4420 if (!vol_opts.interrupt_rxcall)
4421 return; /* we have no function with which to interrupt calls */
4422 err = VIsGoingOffline_r(vp);
4424 return; /* we're not going offline anymore */
4426 #ifdef AFS_DEMAND_ATTACH_FS
4427 VWaitExclusiveState_r(vp);
4428 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4430 #endif /* AFS_DEMAND_ATTACH_FS */
4432 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4433 if (GetLogLevel() != 0) {
4434 struct rx_peer *peer;
4436 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4438 Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4439 "from it; kicking client off with error %ld\n",
4440 afs_printable_VolumeId_lu(vp->hashid),
4441 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4442 (unsigned) ntohs(rx_PortOf(peer)),
4445 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4448 #ifdef AFS_DEMAND_ATTACH_FS
4450 VChangeState_r(vp, state_save);
4451 #endif /* AFS_DEMAND_ATTACH_FS */
4454 #ifdef AFS_DEMAND_ATTACH_FS
4456 * Wait for a vp to go offline.
4458 * @param[out] ec 1 if a salvage on the volume has been requested and
4459 * salvok == 0, 0 otherwise
4460 * @param[in] vp The volume to wait for
4461 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4462 * has been requested to salvage. Otherwise we keep waiting
4463 * until the volume has gone offline.
4465 * @pre VOL_LOCK held
4466 * @pre caller holds a lightweight ref on vp
4471 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4473 struct timespec timeout_ts;
4474 const struct timespec *ts;
4477 ts = VOfflineTimeout(&timeout_ts);
4481 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4482 if (!salvok && vp->salvage.requested) {
4486 VTimedWaitStateChange_r(vp, ts, &timedout);
4489 /* we didn't time out, so the volume must be offline, so we're done */
4493 /* If we got here, we timed out waiting for the volume to go offline.
4494 * Kick off the accessing RX calls and wait again */
4498 while (!VIsOfflineState(V_attachState(vp))) {
4499 if (!salvok && vp->salvage.requested) {
4504 VWaitStateChange_r(vp);
4508 #else /* AFS_DEMAND_ATTACH_FS */
4511 * Wait for a volume to go offline.
4513 * @pre VOL_LOCK held
4515 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4518 VWaitForOffline_r(Error *ec, VolumeId volid)
4521 const struct timespec *ts;
4522 #ifdef AFS_PTHREAD_ENV
4523 struct timespec timeout_ts;
4526 ts = VOfflineTimeout(&timeout_ts);
4528 vp = GetVolume(ec, NULL, volid, NULL, ts);
4530 /* error occurred so bad that we can't even get a vp; we have no
4531 * information on the vol so we don't know whether to wait, so just
4535 if (!VIsGoingOffline_r(vp)) {
4536 /* volume is no longer going offline, so we're done */
4541 /* If we got here, we timed out waiting for the volume to go offline.
4542 * Kick off the accessing RX calls and wait again */
4548 vp = VGetVolume_r(ec, volid);
4550 /* In case it was reattached... */
4554 #endif /* !AFS_DEMAND_ATTACH_FS */
4556 /* The opposite of VAttachVolume. The volume header is written to disk, with
4557 the inUse bit turned off. A copy of the header is maintained in memory,
4558 however (which is why this is VOffline, not VDetach).
4561 VOffline_r(Volume * vp, char *message)
4564 #ifndef AFS_DEMAND_ATTACH_FS
4565 VolumeId vid = V_id(vp);
4568 opr_Assert(programType != volumeUtility && programType != volumeServer);
4573 if (V_offlineMessage(vp)[0] == '\0')
4574 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4575 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4577 vp->goingOffline = 1;
4578 #ifdef AFS_DEMAND_ATTACH_FS
4579 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4580 VCreateReservation_r(vp);
4582 VWaitForOfflineByVp_r(&error, vp, 1);
4583 VCancelReservation_r(vp);
4584 #else /* AFS_DEMAND_ATTACH_FS */
4586 VWaitForOffline_r(&error, vid);
4587 #endif /* AFS_DEMAND_ATTACH_FS */
4590 #ifdef AFS_DEMAND_ATTACH_FS
4592 * Take a volume offline in order to perform a volume operation.
4594 * @param[inout] ec address in which to store error code
4595 * @param[in] vp volume object pointer
4596 * @param[in] message volume offline status message
4599 * - VOL_LOCK is held
4600 * - caller MUST hold a heavyweight ref on vp
4603 * - volume is taken offline
4604 * - if possible, volume operation is promoted to running state
4605 * - on failure, *ec is set to nonzero
4607 * @note Although this function does not return any value, it may
4608 * still fail to promote our pending volume operation to
4609 * a running state. Any caller MUST check the value of *ec,
4610 * and MUST NOT blindly assume success.
4612 * @warning if the caller does not hold a lightweight ref on vp,
4613 * then it MUST NOT reference vp after this function
4614 * returns to the caller.
4616 * @internal volume package internal use only
4619 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4622 opr_Assert(vp->pending_vol_op);
4628 if (V_offlineMessage(vp)[0] == '\0')
4629 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4630 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4632 vp->goingOffline = 1;
4633 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4634 VCreateReservation_r(vp);
4637 if (vp->pending_vol_op->com.programType != salvageServer) {
4638 /* do not give corrupted volumes to the volserver */
4643 VWaitForOfflineByVp_r(ec, vp, salvok);
4645 VCancelReservation_r(vp);
4647 #endif /* AFS_DEMAND_ATTACH_FS */
4650 VOffline(Volume * vp, char *message)
4653 VOffline_r(vp, message);
4657 /* This gets used for the most part by utility routines that don't want
4658 * to keep all the volume headers around. Generally, the file server won't
4659 * call this routine, because then the offline message in the volume header
4660 * (or other information) won't be available to clients. For NAMEI, also
4661 * close the file handles. However, the fileserver does call this during
4662 * an attach following a volume operation.
4665 VDetachVolume_r(Error * ec, Volume * vp)
4667 #ifdef FSSYNC_BUILD_CLIENT
4669 struct DiskPartition64 *tpartp;
4670 int notifyServer = 0;
4671 int useDone = FSYNC_VOL_ON;
4673 if (VCanUseFSSYNC()) {
4674 notifyServer = vp->needsPutBack;
4675 if (V_destroyMe(vp) == DESTROY_ME)
4676 useDone = FSYNC_VOL_LEAVE_OFF;
4677 # ifdef AFS_DEMAND_ATTACH_FS
4678 else if (!V_blessed(vp) || !V_inService(vp))
4679 useDone = FSYNC_VOL_LEAVE_OFF;
4682 # ifdef AFS_DEMAND_ATTACH_FS
4683 if (V_needsSalvaged(vp)) {
4685 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4688 tpartp = vp->partition;
4690 #endif /* FSSYNC_BUILD_CLIENT */
4692 *ec = 0; /* always "succeeds" */
4693 DeleteVolumeFromHashTable(vp);
4694 vp->shuttingDown = 1;
4695 #ifdef AFS_DEMAND_ATTACH_FS
4696 DeleteVolumeFromVByPList_r(vp);
4698 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4700 if (programType != fileServer)
4702 #endif /* AFS_DEMAND_ATTACH_FS */
4704 /* Will be detached sometime in the future--this is OK since volume is offline */
4706 /* XXX the following code should really be moved to VCheckDetach() since the volume
4707 * is not technically detached until the refcounts reach zero
4709 #ifdef FSSYNC_BUILD_CLIENT
4710 if (VCanUseFSSYNC() && notifyServer) {
4711 if (notifyServer == VOL_PUTBACK_DELETE) {
4712 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4713 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4714 * to signify a deleted volume. */
4715 useDone = FSYNC_VOL_DONE;
4718 * Note: The server is not notified in the case of a bogus volume
4719 * explicitly to make it possible to create a volume, do a partial
4720 * restore, then abort the operation without ever putting the volume
4721 * online. This is essential in the case of a volume move operation
4722 * between two partitions on the same server. In that case, there
4723 * would be two instances of the same volume, one of them bogus,
4724 * which the file server would attempt to put on line
4726 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4728 #endif /* FSSYNC_BUILD_CLIENT */
4732 VDetachVolume(Error * ec, Volume * vp)
4735 VDetachVolume_r(ec, vp);
4740 /***************************************************/
4741 /* Volume fd/inode handle closing routines */
4742 /***************************************************/
4744 /* For VDetachVolume, we close all cached file descriptors, but keep
4745 * the Inode handles in case we need to read from a busy volume.
4747 /* for demand attach, caller MUST hold ref count on vp */
4749 VCloseVolumeHandles_r(Volume * vp)
4751 #ifdef AFS_DEMAND_ATTACH_FS
4752 VolState state_save;
4754 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4759 DFlushVolume(vp->hashid);
4761 #ifdef AFS_DEMAND_ATTACH_FS
4765 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4766 VCloseVnodeFiles_r(vp);
4768 #ifdef AFS_DEMAND_ATTACH_FS
4772 /* Too time consuming and unnecessary for the volserver */
4773 if (programType == fileServer) {
4774 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4775 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4776 IH_CONDSYNC(vp->diskDataHandle);
4777 #ifdef AFS_NAMEI_ENV
4778 IH_CONDSYNC(vp->linkHandle);
4779 #endif /* AFS_NAMEI_ENV */
4782 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4783 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4784 IH_REALLYCLOSE(vp->diskDataHandle);
4785 IH_REALLYCLOSE(vp->linkHandle);
4787 #ifdef AFS_DEMAND_ATTACH_FS
4788 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4793 VChangeState_r(vp, state_save);
4797 /* For both VForceOffline and VOffline, we close all relevant handles.
4798 * For VOffline, if we re-attach the volume, the files may possible be
4799 * different than before.
4801 /* for demand attach, caller MUST hold a ref count on vp */
4803 VReleaseVolumeHandles_r(Volume * vp)
4805 #ifdef AFS_DEMAND_ATTACH_FS
4806 VolState state_save;
4808 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4813 DFlushVolume(vp->hashid);
4815 #ifdef AFS_DEMAND_ATTACH_FS
4819 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4821 #ifdef AFS_DEMAND_ATTACH_FS
4825 /* Too time consuming and unnecessary for the volserver */
4826 if (programType == fileServer) {
4827 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4828 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4829 IH_CONDSYNC(vp->diskDataHandle);
4830 #ifdef AFS_NAMEI_ENV
4831 IH_CONDSYNC(vp->linkHandle);
4832 #endif /* AFS_NAMEI_ENV */
4835 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4836 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4837 IH_RELEASE(vp->diskDataHandle);
4838 IH_RELEASE(vp->linkHandle);
4840 #ifdef AFS_DEMAND_ATTACH_FS
4841 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4846 VChangeState_r(vp, state_save);
4851 /***************************************************/
4852 /* Volume write and fsync routines */
4853 /***************************************************/
4856 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4858 #ifdef AFS_DEMAND_ATTACH_FS
4859 VolState state_save;
4861 if (flags & VOL_UPDATE_WAIT) {
4862 VCreateReservation_r(vp);
4863 VWaitExclusiveState_r(vp);
4868 if (programType == fileServer) {
4870 V_uniquifier(vp) = V_nextVnodeUnique(vp);
4873 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4874 if (V_uniquifier(vp) < V_nextVnodeUnique(vp)) {
4875 /* uniquifier rolled over; reset the counters */
4876 V_nextVnodeUnique(vp) = 2; /* 1 is reserved for the root vnode */
4878 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4883 #ifdef AFS_DEMAND_ATTACH_FS
4884 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4888 WriteVolumeHeader_r(ec, vp);
4890 #ifdef AFS_DEMAND_ATTACH_FS
4892 VChangeState_r(vp, state_save);
4893 if (flags & VOL_UPDATE_WAIT) {
4894 VCancelReservation_r(vp);
4899 Log("VUpdateVolume: error updating volume header, volume %" AFS_VOLID_FMT " (%s)\n",
4900 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
4901 /* try to update on-disk header,
4902 * while preventing infinite recursion */
4903 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4904 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4910 VUpdateVolume(Error * ec, Volume * vp)
4913 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4918 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4922 #ifdef AFS_DEMAND_ATTACH_FS
4923 VolState state_save;
4926 if (flags & VOL_SYNC_WAIT) {
4927 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4929 VUpdateVolume_r(ec, vp, 0);
4932 #ifdef AFS_DEMAND_ATTACH_FS
4933 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4936 fdP = IH_OPEN(V_diskDataHandle(vp));
4937 opr_Assert(fdP != NULL);
4938 code = FDH_SYNC(fdP);
4939 opr_Assert(code == 0);
4941 #ifdef AFS_DEMAND_ATTACH_FS
4943 VChangeState_r(vp, state_save);
4949 VSyncVolume(Error * ec, Volume * vp)
4952 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4957 /***************************************************/
4958 /* Volume dealloaction routines */
4959 /***************************************************/
4961 #ifdef AFS_DEMAND_ATTACH_FS
4963 FreeVolume(Volume * vp)
4965 /* free the heap space, iff it's safe.
4966 * otherwise, pull it out of the hash table, so it
4967 * will get deallocated when all refs to it go away */
4968 if (!VCheckFree(vp)) {
4969 DeleteVolumeFromHashTable(vp);
4970 DeleteVolumeFromVByPList_r(vp);
4972 /* make sure we invalidate the header cache entry */
4973 FreeVolumeHeader(vp);
4976 #endif /* AFS_DEMAND_ATTACH_FS */
4979 ReallyFreeVolume(Volume * vp)
4984 #ifdef AFS_DEMAND_ATTACH_FS
4986 VChangeState_r(vp, VOL_STATE_FREED);
4987 if (vp->pending_vol_op)
4988 free(vp->pending_vol_op);
4989 #endif /* AFS_DEMAND_ATTACH_FS */
4990 for (i = 0; i < nVNODECLASSES; i++)
4991 if (vp->vnodeIndex[i].bitmap)
4992 free(vp->vnodeIndex[i].bitmap);
4993 FreeVolumeHeader(vp);
4994 #ifndef AFS_DEMAND_ATTACH_FS
4995 DeleteVolumeFromHashTable(vp);
4996 #endif /* AFS_DEMAND_ATTACH_FS */
5000 /* check to see if we should shutdown this volume
5001 * returns 1 if volume was freed, 0 otherwise */
5002 #ifdef AFS_DEMAND_ATTACH_FS
5004 VCheckDetach(Volume * vp)
5009 if (vp->nUsers || vp->nWaiters)
5012 if (vp->shuttingDown) {
5014 if ((programType != fileServer) &&
5015 (V_inUse(vp) == programType) &&
5016 ((V_checkoutMode(vp) == V_VOLUPD) ||
5017 (V_checkoutMode(vp) == V_SECRETLY) ||
5018 ((V_checkoutMode(vp) == V_CLONE) &&
5019 (VolumeWriteable(vp))))) {
5021 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5023 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " "
5024 "failed with errno %d\n", afs_printable_VolumeId_lu(vp->hashid), errno);
5027 VReleaseVolumeHandles_r(vp);
5029 ReallyFreeVolume(vp);
5030 if (programType == fileServer) {
5031 opr_cv_broadcast(&vol_put_volume_cond);
5036 #else /* AFS_DEMAND_ATTACH_FS */
5038 VCheckDetach(Volume * vp)
5046 if (vp->shuttingDown) {
5048 if ((programType != fileServer) &&
5049 (V_inUse(vp) == programType) &&
5050 ((V_checkoutMode(vp) == V_VOLUPD) ||
5051 (V_checkoutMode(vp) == V_SECRETLY) ||
5052 ((V_checkoutMode(vp) == V_CLONE) &&
5053 (VolumeWriteable(vp))))) {
5055 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5057 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " failed with errno %d\n",
5058 afs_printable_VolumeId_lu(vp->hashid), errno);
5061 VReleaseVolumeHandles_r(vp);
5062 ReallyFreeVolume(vp);
5063 if (programType == fileServer) {
5064 #if defined(AFS_PTHREAD_ENV)
5065 opr_cv_broadcast(&vol_put_volume_cond);
5066 #else /* AFS_PTHREAD_ENV */
5067 LWP_NoYieldSignal(VPutVolume);
5068 #endif /* AFS_PTHREAD_ENV */
5073 #endif /* AFS_DEMAND_ATTACH_FS */
5075 /* check to see if we should offline this volume
5076 * return 1 if volume went offline, 0 otherwise */
5077 #ifdef AFS_DEMAND_ATTACH_FS
5079 VCheckOffline(Volume * vp)
5083 if (vp->goingOffline && !vp->nUsers) {
5085 opr_Assert(programType == fileServer);
5086 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5087 (V_attachState(vp) != VOL_STATE_FREED) &&
5088 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5089 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5090 (V_attachState(vp) != VOL_STATE_DELETED));
5094 * VOL_STATE_GOING_OFFLINE
5095 * VOL_STATE_SHUTTING_DOWN
5096 * VIsErrorState(V_attachState(vp))
5097 * VIsExclusiveState(V_attachState(vp))
5100 VCreateReservation_r(vp);
5101 VChangeState_r(vp, VOL_STATE_OFFLINING);
5104 /* must clear the goingOffline flag before we drop the glock */
5105 vp->goingOffline = 0;
5110 /* perform async operations */
5111 VUpdateVolume_r(&error, vp, 0);
5112 VCloseVolumeHandles_r(vp);
5114 if (GetLogLevel() != 0) {
5115 if (V_offlineMessage(vp)[0]) {
5116 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5117 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5118 V_offlineMessage(vp));
5120 Log("VOffline: Volume %lu (%s) is now offline\n",
5121 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5125 /* invalidate the volume header cache entry */
5126 FreeVolumeHeader(vp);
5128 /* if nothing changed state to error or salvaging,
5129 * drop state to unattached */
5130 if (!VIsErrorState(V_attachState(vp))) {
5131 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5133 VCancelReservation_r(vp);
5134 /* no usage of vp is safe beyond this point */
5138 #else /* AFS_DEMAND_ATTACH_FS */
5140 VCheckOffline(Volume * vp)
5144 if (vp->goingOffline && !vp->nUsers) {
5146 opr_Assert(programType == fileServer);
5149 vp->goingOffline = 0;
5151 VUpdateVolume_r(&error, vp, 0);
5152 VCloseVolumeHandles_r(vp);
5153 if (GetLogLevel() != 0) {
5154 if (V_offlineMessage(vp)[0]) {
5155 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5156 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5157 V_offlineMessage(vp));
5159 Log("VOffline: Volume %lu (%s) is now offline\n",
5160 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5163 FreeVolumeHeader(vp);
5164 #ifdef AFS_PTHREAD_ENV
5165 opr_cv_broadcast(&vol_put_volume_cond);
5166 #else /* AFS_PTHREAD_ENV */
5167 LWP_NoYieldSignal(VPutVolume);
5168 #endif /* AFS_PTHREAD_ENV */
5172 #endif /* AFS_DEMAND_ATTACH_FS */
5174 /***************************************************/
5175 /* demand attach fs ref counting routines */
5176 /***************************************************/
5178 #ifdef AFS_DEMAND_ATTACH_FS
5179 /* the following two functions handle reference counting for
5180 * asynchronous operations on volume structs.
5182 * their purpose is to prevent a VDetachVolume or VShutdown
5183 * from free()ing the Volume struct during an async i/o op */
5185 /* register with the async volume op ref counter */
5186 /* VCreateReservation_r moved into inline code header because it
5187 * is now needed in vnode.c -- tkeiser 11/20/2007
5191 * decrement volume-package internal refcount.
5193 * @param vp volume object pointer
5195 * @internal volume package internal use only
5198 * @arg VOL_LOCK is held
5199 * @arg lightweight refcount held
5201 * @post volume waiters refcount is decremented; volume may
5202 * have been deallocated/shutdown/offlined/salvaged/
5203 * whatever during the process
5205 * @warning once you have tossed your last reference (you can acquire
5206 * lightweight refs recursively) it is NOT SAFE to reference
5207 * a volume object pointer ever again
5209 * @see VCreateReservation_r
5211 * @note DEMAND_ATTACH_FS only
5214 VCancelReservation_r(Volume * vp)
5216 opr_Verify(--vp->nWaiters >= 0);
5217 if (vp->nWaiters == 0) {
5219 if (!VCheckDetach(vp)) {
5226 /* check to see if we should free this volume now
5227 * return 1 if volume was freed, 0 otherwise */
5229 VCheckFree(Volume * vp)
5232 if ((vp->nUsers == 0) &&
5233 (vp->nWaiters == 0) &&
5234 !(V_attachFlags(vp) & (VOL_IN_HASH |
5238 ReallyFreeVolume(vp);
5243 #endif /* AFS_DEMAND_ATTACH_FS */
5246 /***************************************************/
5247 /* online volume operations routines */
5248 /***************************************************/
5250 #ifdef AFS_DEMAND_ATTACH_FS
5252 * register a volume operation on a given volume.
5254 * @param[in] vp volume object
5255 * @param[in] vopinfo volume operation info object
5257 * @pre VOL_LOCK is held
5259 * @post volume operation info object attached to volume object.
5260 * volume operation statistics updated.
5262 * @note by "attached" we mean a copy of the passed in object is made
5264 * @internal volume package internal use only
5267 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5269 FSSYNC_VolOp_info * info;
5271 /* attach a vol op info node to the volume struct */
5272 info = malloc(sizeof(FSSYNC_VolOp_info));
5273 opr_Assert(info != NULL);
5274 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5275 vp->pending_vol_op = info;
5278 vp->stats.last_vol_op = FT_ApproxTime();
5279 vp->stats.vol_ops++;
5280 IncUInt64(&VStats.vol_ops);
5286 * deregister the volume operation attached to this volume.
5288 * @param[in] vp volume object pointer
5290 * @pre VOL_LOCK is held
5292 * @post the volume operation info object is detached from the volume object
5294 * @internal volume package internal use only
5297 VDeregisterVolOp_r(Volume * vp)
5299 if (vp->pending_vol_op) {
5300 free(vp->pending_vol_op);
5301 vp->pending_vol_op = NULL;
5305 #endif /* AFS_DEMAND_ATTACH_FS */
5308 * determine whether it is safe to leave a volume online during
5309 * the volume operation described by the vopinfo object.
5311 * @param[in] vp volume object
5312 * @param[in] vopinfo volume operation info object
5314 * @return whether it is safe to leave volume online
5315 * @retval 0 it is NOT SAFE to leave the volume online
5316 * @retval 1 it is safe to leave the volume online during the operation
5319 * @arg VOL_LOCK is held
5320 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5321 * this condition is met)
5323 * @internal volume package internal use only
5326 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5328 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5329 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5330 (vopinfo->com.reason == V_READONLY ||
5331 (!VolumeWriteable(vp) &&
5332 (vopinfo->com.reason == V_CLONE ||
5333 vopinfo->com.reason == V_DUMP)))));
5337 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5340 * @param[in] vp volume object
5341 * @param[in] vopinfo volume operation info object
5343 * @return whether it is safe to leave volume online
5344 * @retval 0 it is NOT SAFE to leave the volume online
5345 * @retval 1 it is safe to leave the volume online during the operation
5346 * @retval -1 unsure; volume header is required in order to know whether or
5347 * not is is safe to leave the volume online
5349 * @pre VOL_LOCK is held
5351 * @internal volume package internal use only
5354 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5356 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5357 * assume that we don't know VolumeWriteable; return -1 if the answer
5358 * depends on VolumeWriteable */
5360 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5363 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5364 vopinfo->com.reason == V_READONLY) {
5368 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5369 (vopinfo->com.reason == V_CLONE ||
5370 vopinfo->com.reason == V_DUMP)) {
5372 /* must know VolumeWriteable */
5379 * determine whether VBUSY should be set during this volume operation.
5381 * @param[in] vp volume object
5382 * @param[in] vopinfo volume operation info object
5384 * @return whether VBUSY should be set
5385 * @retval 0 VBUSY does NOT need to be set
5386 * @retval 1 VBUSY SHOULD be set
5388 * @pre VOL_LOCK is held
5390 * @internal volume package internal use only
5393 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5395 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5396 vopinfo->com.reason == FSYNC_SALVAGE) ||
5397 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5398 (vopinfo->com.reason == V_CLONE ||
5399 vopinfo->com.reason == V_DUMP)));
5403 /***************************************************/
5404 /* online salvager routines */
5405 /***************************************************/
5406 #if defined(AFS_DEMAND_ATTACH_FS)
5409 * offline a volume to let it be salvaged.
5411 * @param[in] vp Volume to offline
5413 * @return whether we offlined the volume successfully
5414 * @retval 0 volume was not offlined
5415 * @retval 1 volume is now offline
5417 * @note This is similar to VCheckOffline, but slightly different. We do not
5418 * deal with vp->goingOffline, and we try to avoid touching the volume
5419 * header except just to set needsSalvaged
5421 * @pre VOL_LOCK held
5422 * @pre vp->nUsers == 0
5423 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5426 VOfflineForSalvage_r(struct Volume *vp)
5430 VCreateReservation_r(vp);
5431 VWaitExclusiveState_r(vp);
5433 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5434 /* Someone's using the volume, or someone got to scheduling the salvage
5435 * before us. I don't think either of these should be possible, as we
5436 * should gain no new heavyweight references while we're trying to
5437 * salvage, but just to be sure... */
5438 VCancelReservation_r(vp);
5442 VChangeState_r(vp, VOL_STATE_OFFLINING);
5446 V_needsSalvaged(vp) = 1;
5447 /* ignore error; updating needsSalvaged is just best effort */
5448 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5450 VCloseVolumeHandles_r(vp);
5452 FreeVolumeHeader(vp);
5454 /* volume has been effectively offlined; we can mark it in the SALVAGING
5455 * state now, which lets FSSYNC give it away */
5456 VChangeState_r(vp, VOL_STATE_SALVAGING);
5458 VCancelReservation_r(vp);
5464 * check whether a salvage needs to be performed on this volume.
5466 * @param[in] vp pointer to volume object
5468 * @return status code
5469 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5470 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5471 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5472 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5473 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5475 * @pre VOL_LOCK is held
5477 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5478 * then a salvage will be requested
5480 * @note this is one of the event handlers called by VCancelReservation_r
5482 * @note the caller must check if the volume needs to be freed after calling
5483 * this; the volume may not have any references or be on any lists after
5484 * we return, and we do not free it
5486 * @see VCancelReservation_r
5488 * @internal volume package internal use only.
5491 VCheckSalvage(Volume * vp)
5493 int ret = VCHECK_SALVAGE_OK;
5495 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5496 if (!vp->salvage.requested) {
5497 return VCHECK_SALVAGE_OK;
5500 return VCHECK_SALVAGE_ASYNC;
5503 /* prevent recursion; some of the code below creates and removes
5504 * lightweight refs, which can call VCheckSalvage */
5505 if (vp->salvage.scheduling) {
5506 return VCHECK_SALVAGE_ASYNC;
5508 vp->salvage.scheduling = 1;
5510 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5511 if (!VOfflineForSalvage_r(vp)) {
5512 vp->salvage.scheduling = 0;
5513 return VCHECK_SALVAGE_FAIL;
5517 if (vp->salvage.requested) {
5518 ret = VScheduleSalvage_r(vp);
5520 vp->salvage.scheduling = 0;
5521 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5526 * request volume salvage.
5528 * @param[out] ec computed client error code
5529 * @param[in] vp volume object pointer
5530 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5531 * @param[in] flags see flags note below
5534 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5535 * not been fully attached
5537 * @pre VOL_LOCK is held.
5539 * @post volume state is changed.
5540 * for fileserver, salvage will be requested once refcount reaches zero.
5542 * @return operation status code
5543 * @retval 0 volume salvage will occur
5544 * @retval 1 volume salvage could not be scheduled
5548 * @note in the fileserver, this call does not synchronously schedule a volume
5549 * salvage. rather, it sets volume state so that when volume refcounts
5550 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5551 * nUsers and nWaiters must be zero.
5553 * @internal volume package internal use only.
5556 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5560 * for DAFS volume utilities that are not supposed to schedule salvages,
5561 * just transition to error state instead
5563 if (!VCanScheduleSalvage()) {
5564 VChangeState_r(vp, VOL_STATE_ERROR);
5569 if (programType != fileServer && !VCanUseFSSYNC()) {
5570 VChangeState_r(vp, VOL_STATE_ERROR);
5575 if (!vp->salvage.requested) {
5576 vp->salvage.requested = 1;
5577 vp->salvage.reason = reason;
5578 vp->stats.last_salvage = FT_ApproxTime();
5580 /* Note that it is not possible for us to reach this point if a
5581 * salvage is already running on this volume (even if the fileserver
5582 * was restarted during the salvage). If a salvage were running, the
5583 * salvager would have write-locked the volume header file, so when
5584 * we tried to lock the volume header, the lock would have failed,
5585 * and we would have failed during attachment prior to calling
5586 * VRequestSalvage. So we know that we can schedule salvages without
5587 * fear of a salvage already running for this volume. */
5589 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5591 /* if we don't need to offline the volume, we can go directly
5592 * to SALVAGING. SALVAGING says the volume is offline and is
5593 * either salvaging or ready to be handed to the salvager.
5594 * SALVAGE_REQ says that we want to salvage the volume, but we
5595 * are waiting for it to go offline first. */
5596 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5597 VChangeState_r(vp, VOL_STATE_SALVAGING);
5599 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5600 if (vp->nUsers == 0) {
5601 /* normally VOfflineForSalvage_r would be called from
5602 * PutVolume et al when nUsers reaches 0, but if
5603 * it's already 0, just do it ourselves, since PutVolume
5604 * isn't going to get called */
5605 VOfflineForSalvage_r(vp);
5608 /* If we are non-fileserver, we're telling the fileserver to
5609 * salvage the vol, so we don't need to give it back separately. */
5610 vp->needsPutBack = 0;
5614 Log("VRequestSalvage: volume %" AFS_VOLID_FMT " online salvaged too many times; forced offline.\n", afs_printable_VolumeId_lu(vp->hashid));
5616 /* make sure neither VScheduleSalvage_r nor
5617 * VUpdateSalvagePriority_r try to schedule another salvage */
5618 vp->salvage.requested = vp->salvage.scheduled = 0;
5620 VChangeState_r(vp, VOL_STATE_ERROR);
5624 if ((flags & VOL_SALVAGE_NO_OFFLINE)) {
5625 /* Here, we free the header for the volume, but make sure to only
5626 * do this if VOL_SALVAGE_NO_OFFLINE is specified. The reason for
5627 * this requires a bit of explanation.
5629 * Normally, the volume header will be freed when the volume goes
5630 * goes offline. However, if VOL_SALVAGE_NO_OFFLINE has been
5631 * specified, the volume was in the process of being attached when
5632 * we discovered that it needed salvaging. Thus, the volume will
5633 * never go offline, since it never went fully online in the first
5634 * place. Specifically, we do not call VOfflineForSalvage_r above,
5635 * and we never get rid of the volume via VPutVolume_r; the volume
5636 * has not been initialized enough for those to work.
5638 * So instead, explicitly free the volume header here. If we do not
5639 * do this, we are wasting a header that some other volume could be
5640 * using, since the header remains attached to the volume. Also if
5641 * we do not free the header here, we end up with a volume where
5642 * nUsers == 0, but the volume has a header that is not on the
5643 * header LRU. Some code expects that all nUsers == 0 volumes have
5644 * their header on the header LRU (or have no header).
5646 * Also note that we must not free the volume header here if
5647 * VOL_SALVAGE_NO_OFFLINE is not set. Since, if
5648 * VOL_SALVAGE_NO_OFFLINE is not set, someone else may have a
5649 * reference to this volume, and they assume they can use the
5650 * volume's header. If we free the volume out from under them, they
5651 * can easily segfault.
5653 FreeVolumeHeader(vp);
5660 * update salvageserver scheduling priority for a volume.
5662 * @param[in] vp pointer to volume object
5664 * @return operation status
5666 * @retval 1 request denied, or SALVSYNC communications failure
5668 * @pre VOL_LOCK is held.
5670 * @post in-core salvage priority counter is incremented. if at least
5671 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5672 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5673 * to update its priority queue. if no salvage is scheduled,
5674 * this function is a no-op.
5676 * @note DAFS fileserver only
5678 * @note this should be called whenever a VGetVolume fails due to a
5679 * pending salvage request
5681 * @todo should set exclusive state and drop glock around salvsync call
5683 * @internal volume package internal use only.
5686 VUpdateSalvagePriority_r(Volume * vp)
5690 #ifdef SALVSYNC_BUILD_CLIENT
5695 now = FT_ApproxTime();
5697 /* update the salvageserver priority queue occasionally so that
5698 * frequently requested volumes get moved to the head of the queue
5700 if ((vp->salvage.scheduled) &&
5701 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5702 code = SALVSYNC_SalvageVolume(vp->hashid,
5703 VPartitionPath(vp->partition),
5708 vp->stats.last_salvage_req = now;
5709 if (code != SYNC_OK) {
5713 #endif /* SALVSYNC_BUILD_CLIENT */
5718 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5720 /* A couple of little helper functions. These return true if we tried to
5721 * use this mechanism to schedule a salvage, false if we haven't tried.
5722 * If we did try a salvage then the results are contained in code.
5726 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5727 #ifdef SALVSYNC_BUILD_CLIENT
5728 if (VCanUseSALVSYNC()) {
5729 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over SALVSYNC\n",
5730 afs_printable_VolumeId_lu(vp->hashid), partName);
5732 /* can't use V_id() since there's no guarantee
5733 * we have the disk data header at this point */
5734 *code = SALVSYNC_SalvageVolume(vp->hashid,
5747 try_FSSYNC(Volume *vp, char *partName, int *code) {
5748 #ifdef FSSYNC_BUILD_CLIENT
5749 if (VCanUseFSSYNC()) {
5750 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over FSSYNC\n",
5751 afs_printable_VolumeId_lu(vp->hashid), partName);
5754 * If we aren't the fileserver, tell the fileserver the volume
5755 * needs to be salvaged. We could directly tell the
5756 * salvageserver, but the fileserver keeps track of some stats
5757 * related to salvages, and handles some other salvage-related
5758 * complications for us.
5760 *code = FSYNC_VolOp(vp->hashid, partName,
5761 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5764 #endif /* FSSYNC_BUILD_CLIENT */
5769 * schedule a salvage with the salvage server or fileserver.
5771 * @param[in] vp pointer to volume object
5773 * @return operation status
5774 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5775 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5776 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5777 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5778 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5781 * @arg VOL_LOCK is held.
5782 * @arg nUsers and nWaiters should be zero.
5784 * @post salvageserver or fileserver is sent a salvage request
5786 * @note If we are the fileserver, the request will be sent to the salvage
5787 * server over SALVSYNC. If we are not the fileserver, the request will be
5788 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5790 * @note the caller must check if the volume needs to be freed after calling
5791 * this; the volume may not have any references or be on any lists after
5792 * we return, and we do not free it
5796 * @internal volume package internal use only.
5799 VScheduleSalvage_r(Volume * vp)
5801 int ret = VCHECK_SALVAGE_SCHEDULED;
5803 VolState state_save;
5804 VThreadOptions_t * thread_opts;
5807 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5809 if (vp->nWaiters || vp->nUsers) {
5810 return VCHECK_SALVAGE_ASYNC;
5813 /* prevent endless salvage,attach,salvage,attach,... loops */
5814 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5815 return VCHECK_SALVAGE_FAIL;
5819 * don't perform salvsync ops on certain threads
5821 thread_opts = pthread_getspecific(VThread_key);
5822 if (thread_opts == NULL) {
5823 thread_opts = &VThread_defaults;
5825 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5826 return VCHECK_SALVAGE_ASYNC;
5829 if (vp->salvage.scheduled) {
5830 return VCHECK_SALVAGE_SCHEDULED;
5833 VCreateReservation_r(vp);
5834 VWaitExclusiveState_r(vp);
5837 * XXX the scheduling process should really be done asynchronously
5838 * to avoid fssync deadlocks
5840 if (vp->salvage.scheduled) {
5841 ret = VCHECK_SALVAGE_SCHEDULED;
5843 /* if we haven't previously scheduled a salvage, do so now
5845 * set the volume to an exclusive state and drop the lock
5846 * around the SALVSYNC call
5848 strlcpy(partName, vp->partition->name, sizeof(partName));
5849 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5852 opr_Verify(try_SALVSYNC(vp, partName, &code)
5853 || try_FSSYNC(vp, partName, &code));
5856 VChangeState_r(vp, state_save);
5858 if (code == SYNC_OK) {
5859 ret = VCHECK_SALVAGE_SCHEDULED;
5860 vp->salvage.scheduled = 1;
5861 vp->stats.last_salvage_req = FT_ApproxTime();
5862 if (VCanUseSALVSYNC()) {
5863 /* don't record these stats for non-fileservers; let the
5864 * fileserver take care of these */
5865 vp->stats.salvages++;
5866 IncUInt64(&VStats.salvages);
5870 case SYNC_BAD_COMMAND:
5871 case SYNC_COM_ERROR:
5872 ret = VCHECK_SALVAGE_FAIL;
5875 ret = VCHECK_SALVAGE_DENIED;
5876 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5877 "denied\n", afs_printable_VolumeId_lu(vp->hashid));
5880 ret = VCHECK_SALVAGE_FAIL;
5881 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5882 "failed\n", afs_printable_VolumeId_lu(vp->hashid));
5885 ret = VCHECK_SALVAGE_FAIL;
5886 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5887 "received unknown protocol error %d\n",
5888 afs_printable_VolumeId_lu(vp->hashid), code);
5892 if (VCanUseFSSYNC()) {
5893 VChangeState_r(vp, VOL_STATE_ERROR);
5898 /* NB: this is cancelling the reservation we obtained above, but we do
5899 * not call VCancelReservation_r, since that may trigger the vp dtor,
5900 * possibly free'ing the vp. We need to keep the vp around after
5901 * this, as the caller may reference vp without any refs. Instead, it
5902 * is the duty of the caller to inspect 'vp' after we return to see if
5903 * needs to be freed. */
5904 opr_Verify(--vp->nWaiters >= 0);
5907 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5909 #ifdef SALVSYNC_BUILD_CLIENT
5912 * connect to the salvageserver SYNC service.
5914 * @return operation status
5918 * @post connection to salvageserver SYNC service established
5920 * @see VConnectSALV_r
5921 * @see VDisconnectSALV
5922 * @see VReconnectSALV
5929 retVal = VConnectSALV_r();
5935 * connect to the salvageserver SYNC service.
5937 * @return operation status
5941 * @pre VOL_LOCK is held.
5943 * @post connection to salvageserver SYNC service established
5946 * @see VDisconnectSALV_r
5947 * @see VReconnectSALV_r
5948 * @see SALVSYNC_clientInit
5950 * @internal volume package internal use only.
5953 VConnectSALV_r(void)
5955 return SALVSYNC_clientInit();
5959 * disconnect from the salvageserver SYNC service.
5961 * @return operation status
5964 * @pre client should have a live connection to the salvageserver
5966 * @post connection to salvageserver SYNC service destroyed
5968 * @see VDisconnectSALV_r
5970 * @see VReconnectSALV
5973 VDisconnectSALV(void)
5976 VDisconnectSALV_r();
5982 * disconnect from the salvageserver SYNC service.
5984 * @return operation status
5988 * @arg VOL_LOCK is held.
5989 * @arg client should have a live connection to the salvageserver.
5991 * @post connection to salvageserver SYNC service destroyed
5993 * @see VDisconnectSALV
5994 * @see VConnectSALV_r
5995 * @see VReconnectSALV_r
5996 * @see SALVSYNC_clientFinis
5998 * @internal volume package internal use only.
6001 VDisconnectSALV_r(void)
6003 return SALVSYNC_clientFinis();
6007 * disconnect and then re-connect to the salvageserver SYNC service.
6009 * @return operation status
6013 * @pre client should have a live connection to the salvageserver
6015 * @post old connection is dropped, and a new one is established
6018 * @see VDisconnectSALV
6019 * @see VReconnectSALV_r
6022 VReconnectSALV(void)
6026 retVal = VReconnectSALV_r();
6032 * disconnect and then re-connect to the salvageserver SYNC service.
6034 * @return operation status
6039 * @arg VOL_LOCK is held.
6040 * @arg client should have a live connection to the salvageserver.
6042 * @post old connection is dropped, and a new one is established
6044 * @see VConnectSALV_r
6045 * @see VDisconnectSALV
6046 * @see VReconnectSALV
6047 * @see SALVSYNC_clientReconnect
6049 * @internal volume package internal use only.
6052 VReconnectSALV_r(void)
6054 return SALVSYNC_clientReconnect();
6056 #endif /* SALVSYNC_BUILD_CLIENT */
6057 #endif /* AFS_DEMAND_ATTACH_FS */
6060 /***************************************************/
6061 /* FSSYNC routines */
6062 /***************************************************/
6064 /* This must be called by any volume utility which needs to run while the
6065 file server is also running. This is separated from VInitVolumePackage2 so
6066 that a utility can fork--and each of the children can independently
6067 initialize communication with the file server */
6068 #ifdef FSSYNC_BUILD_CLIENT
6070 * connect to the fileserver SYNC service.
6072 * @return operation status
6077 * @arg VInit must equal 2.
6078 * @arg Program Type must not be fileserver or salvager.
6080 * @post connection to fileserver SYNC service established
6083 * @see VDisconnectFS
6084 * @see VChildProcReconnectFS
6091 retVal = VConnectFS_r();
6097 * connect to the fileserver SYNC service.
6099 * @return operation status
6104 * @arg VInit must equal 2.
6105 * @arg Program Type must not be fileserver or salvager.
6106 * @arg VOL_LOCK is held.
6108 * @post connection to fileserver SYNC service established
6111 * @see VDisconnectFS_r
6112 * @see VChildProcReconnectFS_r
6114 * @internal volume package internal use only.
6120 opr_Assert((VInit == 2) &&
6121 (programType != fileServer) &&
6122 (programType != salvager));
6123 rc = FSYNC_clientInit();
6131 * disconnect from the fileserver SYNC service.
6134 * @arg client should have a live connection to the fileserver.
6135 * @arg VOL_LOCK is held.
6136 * @arg Program Type must not be fileserver or salvager.
6138 * @post connection to fileserver SYNC service destroyed
6140 * @see VDisconnectFS
6142 * @see VChildProcReconnectFS_r
6144 * @internal volume package internal use only.
6147 VDisconnectFS_r(void)
6149 opr_Assert((programType != fileServer) &&
6150 (programType != salvager));
6151 FSYNC_clientFinis();
6156 * disconnect from the fileserver SYNC service.
6159 * @arg client should have a live connection to the fileserver.
6160 * @arg Program Type must not be fileserver or salvager.
6162 * @post connection to fileserver SYNC service destroyed
6164 * @see VDisconnectFS_r
6166 * @see VChildProcReconnectFS
6177 * connect to the fileserver SYNC service from a child process following a fork.
6179 * @return operation status
6184 * @arg VOL_LOCK is held.
6185 * @arg current FSYNC handle is shared with a parent process
6187 * @post current FSYNC handle is discarded and a new connection to the
6188 * fileserver SYNC service is established
6190 * @see VChildProcReconnectFS
6192 * @see VDisconnectFS_r
6194 * @internal volume package internal use only.
6197 VChildProcReconnectFS_r(void)
6199 return FSYNC_clientChildProcReconnect();
6203 * connect to the fileserver SYNC service from a child process following a fork.
6205 * @return operation status
6209 * @pre current FSYNC handle is shared with a parent process
6211 * @post current FSYNC handle is discarded and a new connection to the
6212 * fileserver SYNC service is established
6214 * @see VChildProcReconnectFS_r
6216 * @see VDisconnectFS
6219 VChildProcReconnectFS(void)
6223 ret = VChildProcReconnectFS_r();
6227 #endif /* FSSYNC_BUILD_CLIENT */
6230 /***************************************************/
6231 /* volume bitmap routines */
6232 /***************************************************/
6235 * Grow the bitmap by the defined increment
6238 VGrowBitmap(struct vnodeIndex *index)
6242 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6243 osi_Assert(bp != NULL);
6245 bp += index->bitmapSize;
6246 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6247 index->bitmapOffset = index->bitmapSize;
6248 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6254 * allocate a vnode bitmap number for the vnode
6256 * @param[out] ec error code
6257 * @param[in] vp volume object pointer
6258 * @param[in] index vnode index number for the vnode
6259 * @param[in] flags flag values described in note
6261 * @note for DAFS, flags parameter controls locking behavior.
6262 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6263 * will create a reservation and block on any other exclusive
6264 * operations. Otherwise, this function assumes the caller
6265 * already has exclusive access to vp, and we just change the
6268 * @pre VOL_LOCK held
6270 * @return bit number allocated
6276 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6277 struct vnodeIndex *index, int flags)
6281 #ifdef AFS_DEMAND_ATTACH_FS
6282 VolState state_save;
6283 #endif /* AFS_DEMAND_ATTACH_FS */
6287 /* This test is probably redundant */
6288 if (!VolumeWriteable(vp)) {
6289 *ec = (bit32) VREADONLY;
6293 #ifdef AFS_DEMAND_ATTACH_FS
6294 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6295 VCreateReservation_r(vp);
6296 VWaitExclusiveState_r(vp);
6298 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6299 #endif /* AFS_DEMAND_ATTACH_FS */
6302 if ((programType == fileServer) && !index->bitmap) {
6304 #ifndef AFS_DEMAND_ATTACH_FS
6305 /* demand attach fs uses the volume state to avoid races.
6306 * specialStatus field is not used at all */
6308 if (vp->specialStatus == VBUSY) {
6309 if (vp->goingOffline) { /* vos dump waiting for the volume to
6310 * go offline. We probably come here
6311 * from AddNewReadableResidency */
6314 while (vp->specialStatus == VBUSY) {
6315 #ifdef AFS_PTHREAD_ENV
6319 #else /* !AFS_PTHREAD_ENV */
6321 #endif /* !AFS_PTHREAD_ENV */
6325 #endif /* !AFS_DEMAND_ATTACH_FS */
6327 if (!index->bitmap) {
6328 #ifndef AFS_DEMAND_ATTACH_FS
6329 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6330 #endif /* AFS_DEMAND_ATTACH_FS */
6331 for (i = 0; i < nVNODECLASSES; i++) {
6332 VGetBitmap_r(ec, vp, i);
6334 #ifdef AFS_DEMAND_ATTACH_FS
6335 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6336 #else /* AFS_DEMAND_ATTACH_FS */
6337 DeleteVolumeFromHashTable(vp);
6338 vp->shuttingDown = 1; /* Let who has it free it. */
6339 vp->specialStatus = 0;
6340 #endif /* AFS_DEMAND_ATTACH_FS */
6344 #ifndef AFS_DEMAND_ATTACH_FS
6346 vp->specialStatus = 0; /* Allow others to have access. */
6347 #endif /* AFS_DEMAND_ATTACH_FS */
6350 #endif /* BITMAP_LATER */
6352 #ifdef AFS_DEMAND_ATTACH_FS
6354 #endif /* AFS_DEMAND_ATTACH_FS */
6355 bp = index->bitmap + index->bitmapOffset;
6356 ep = index->bitmap + index->bitmapSize;
6358 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6360 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6363 o = opr_ffs(~*bp) - 1;
6365 ret = ((bp - index->bitmap) * 8 + o);
6366 #ifdef AFS_DEMAND_ATTACH_FS
6368 #endif /* AFS_DEMAND_ATTACH_FS */
6371 bp += sizeof(bit32) /* i.e. 4 */ ;
6373 /* No bit map entry--must grow bitmap */
6375 bp = index->bitmap + index->bitmapOffset;
6377 ret = index->bitmapOffset * 8;
6378 #ifdef AFS_DEMAND_ATTACH_FS
6380 #endif /* AFS_DEMAND_ATTACH_FS */
6383 #ifdef AFS_DEMAND_ATTACH_FS
6384 VChangeState_r(vp, state_save);
6385 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6386 VCancelReservation_r(vp);
6388 #endif /* AFS_DEMAND_ATTACH_FS */
6393 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6397 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6403 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6404 unsigned bitNumber, int flags)
6406 unsigned int offset;
6410 #ifdef AFS_DEMAND_ATTACH_FS
6411 if (flags & VOL_FREE_BITMAP_WAIT) {
6412 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6413 * state, so ensure we're not in an exclusive volume state when we update
6415 VCreateReservation_r(vp);
6416 VWaitExclusiveState_r(vp);
6423 #endif /* BITMAP_LATER */
6425 offset = bitNumber >> 3;
6426 if (offset >= index->bitmapSize) {
6430 if (offset < index->bitmapOffset)
6431 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6432 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6435 #ifdef AFS_DEMAND_ATTACH_FS
6436 if (flags & VOL_FREE_BITMAP_WAIT) {
6437 VCancelReservation_r(vp);
6440 return; /* make the compiler happy for non-DAFS */
6444 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6448 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6452 /* this function will drop the glock internally.
6453 * for old pthread fileservers, this is safe thanks to vbusy.
6455 * for demand attach fs, caller must have already called
6456 * VCreateReservation_r and VWaitExclusiveState_r */
6458 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6460 StreamHandle_t *file;
6461 afs_sfsize_t nVnodes, size;
6462 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6463 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6464 struct VnodeDiskObject *vnode;
6465 unsigned int unique = 0;
6469 #endif /* BITMAP_LATER */
6470 #ifdef AFS_DEMAND_ATTACH_FS
6471 VolState state_save;
6472 #endif /* AFS_DEMAND_ATTACH_FS */
6476 #ifdef AFS_DEMAND_ATTACH_FS
6477 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6478 #endif /* AFS_DEMAND_ATTACH_FS */
6481 fdP = IH_OPEN(vip->handle);
6482 opr_Assert(fdP != NULL);
6483 file = FDH_FDOPEN(fdP, "r");
6484 opr_Assert(file != NULL);
6485 vnode = malloc(vcp->diskSize);
6486 opr_Assert(vnode != NULL);
6487 size = FDH_SIZE(fdP);
6488 opr_Assert(size != -1);
6489 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6491 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6492 * a few files can be created in this volume,
6493 * the whole thing is rounded up to nearest 4
6494 * bytes, because the bit map allocator likes
6497 BitMap = (byte *) calloc(1, vip->bitmapSize);
6498 opr_Assert(BitMap != NULL);
6499 #else /* BITMAP_LATER */
6500 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6501 opr_Assert(vip->bitmap != NULL);
6502 vip->bitmapOffset = 0;
6503 #endif /* BITMAP_LATER */
6504 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6506 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6507 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6509 if (vnode->type != vNull) {
6510 if (vnode->vnodeMagic != vcp->magic) {
6511 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6516 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6517 #else /* BITMAP_LATER */
6518 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6519 #endif /* BITMAP_LATER */
6520 if (unique <= vnode->uniquifier)
6521 unique = vnode->uniquifier + 1;
6523 #ifndef AFS_PTHREAD_ENV
6524 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6527 #endif /* !AFS_PTHREAD_ENV */
6530 if (vp->nextVnodeUnique < unique) {
6531 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6534 /* Paranoia, partly justified--I think fclose after fdopen
6535 * doesn't seem to close fd. In any event, the documentation
6536 * doesn't specify, so it's safer to close it twice.
6544 /* There may have been a racing condition with some other thread, both
6545 * creating the bitmaps for this volume. If the other thread was faster
6546 * the pointer to bitmap should already be filled and we can free ours.
6548 if (vip->bitmap == NULL) {
6549 vip->bitmap = BitMap;
6550 vip->bitmapOffset = 0;
6553 #endif /* BITMAP_LATER */
6554 #ifdef AFS_DEMAND_ATTACH_FS
6555 VChangeState_r(vp, state_save);
6556 #endif /* AFS_DEMAND_ATTACH_FS */
6560 /***************************************************/
6561 /* Volume Path and Volume Number utility routines */
6562 /***************************************************/
6565 * find the first occurrence of a volume header file and return the path.
6567 * @param[out] ec outbound error code
6568 * @param[in] volumeId volume id to find
6569 * @param[out] partitionp pointer to disk partition path string
6570 * @param[out] namep pointer to volume header file name string
6572 * @post path to first occurrence of volume header is returned in partitionp
6573 * and namep, or ec is set accordingly.
6575 * @warning this function is NOT re-entrant -- partitionp and namep point to
6576 * static data segments
6578 * @note if a volume utility inadvertently leaves behind a stale volume header
6579 * on a vice partition, it is possible for callers to get the wrong one,
6580 * depending on the order of the disk partition linked list.
6584 VGetVolumePath(Error * ec, VolumeId volumeId, char **partitionp, char **namep)
6586 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6587 char path[VMAXPATHLEN];
6589 struct DiskPartition64 *dp;
6592 name[0] = OS_DIRSEPC;
6593 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6594 afs_printable_VolumeId_lu(volumeId));
6595 for (dp = DiskPartitionList; dp; dp = dp->next) {
6596 struct afs_stat_st status;
6597 strcpy(path, VPartitionPath(dp));
6599 if (afs_stat(path, &status) == 0) {
6600 strcpy(partition, dp->name);
6607 *partitionp = *namep = NULL;
6609 *partitionp = partition;
6615 * extract a volume number from a volume header filename string.
6617 * @param[in] name volume header filename string
6619 * @return volume number
6621 * @note the string must be of the form VFORMAT. the only permissible
6622 * deviation is a leading OS_DIRSEPC character.
6627 VolumeNumber(char *name)
6629 if (*name == OS_DIRSEPC)
6631 return strtoul(name + 1, NULL, 10);
6635 * compute the volume header filename.
6637 * @param[in] volumeId
6639 * @return volume header filename
6641 * @post volume header filename string is constructed
6643 * @warning this function is NOT re-entrant -- the returned string is
6644 * stored in a static char array. see VolumeExternalName_r
6645 * for a re-entrant equivalent.
6647 * @see VolumeExternalName_r
6649 * @deprecated due to the above re-entrancy warning, this interface should
6650 * be considered deprecated. Please use VolumeExternalName_r
6654 VolumeExternalName(VolumeId volumeId)
6656 static char name[VMAXPATHLEN];
6657 snprintf(name, sizeof name, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6662 * compute the volume header filename.
6664 * @param[in] volumeId
6665 * @param[inout] name array in which to store filename
6666 * @param[in] len length of name array
6668 * @return result code from afs_snprintf
6670 * @see VolumeExternalName
6673 * @note re-entrant equivalent of VolumeExternalName
6676 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6678 return snprintf(name, len, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6682 /***************************************************/
6683 /* Volume Usage Statistics routines */
6684 /***************************************************/
6686 #define OneDay (86400) /* 24 hours' worth of seconds */
6689 Midnight(time_t t) {
6690 struct tm local, *l;
6693 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6694 l = localtime_r(&t, &local);
6700 /* the following is strictly speaking problematic on the
6701 switching day to daylight saving time, after the switch,
6702 as tm_isdst does not match. Similarly, on the looong day when
6703 switching back the OneDay check will not do what naively expected!
6704 The effects are minor, though, and more a matter of interpreting
6706 #ifndef AFS_PTHREAD_ENV
6709 local.tm_hour = local.tm_min=local.tm_sec = 0;
6710 midnight = mktime(&local);
6711 if (midnight != (time_t) -1) return(midnight);
6713 return( (t/OneDay)*OneDay );
6717 /*------------------------------------------------------------------------
6718 * [export] VAdjustVolumeStatistics
6721 * If we've passed midnight, we need to update all the day use
6722 * statistics as well as zeroing the detailed volume statistics
6723 * (if we are implementing them).
6726 * vp : Pointer to the volume structure describing the lucky
6727 * volume being considered for update.
6733 * Nothing interesting.
6737 *------------------------------------------------------------------------*/
6740 VAdjustVolumeStatistics_r(Volume * vp)
6742 unsigned int now = FT_ApproxTime();
6744 if (now - V_dayUseDate(vp) > OneDay) {
6747 ndays = (now - V_dayUseDate(vp)) / OneDay;
6748 for (i = 6; i > ndays - 1; i--)
6749 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6750 for (i = 0; i < ndays - 1 && i < 7; i++)
6751 V_weekUse(vp)[i] = 0;
6753 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6755 V_dayUseDate(vp) = Midnight(now);
6758 * All we need to do is bzero the entire VOL_STATS_BYTES of
6759 * the detailed volume statistics area.
6761 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6764 /*It's been more than a day of collection */
6766 * Always return happily.
6769 } /*VAdjustVolumeStatistics */
6772 VAdjustVolumeStatistics(Volume * vp)
6776 retVal = VAdjustVolumeStatistics_r(vp);
6782 VBumpVolumeUsage_r(Volume * vp)
6784 unsigned int now = FT_ApproxTime();
6785 V_accessDate(vp) = now;
6786 if (now - V_dayUseDate(vp) > OneDay)
6787 VAdjustVolumeStatistics_r(vp);
6789 * Save the volume header image to disk after a threshold of bumps to dayUse,
6790 * at most every usage_rate_limit seconds.
6793 vp->usage_bumps_outstanding++;
6794 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6795 && vp->usage_bumps_next_write <= now) {
6797 vp->usage_bumps_outstanding = 0;
6798 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6799 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6804 VBumpVolumeUsage(Volume * vp)
6807 VBumpVolumeUsage_r(vp);
6812 VSetDiskUsage_r(void)
6814 #ifndef AFS_DEMAND_ATTACH_FS
6815 static int FifteenMinuteCounter = 0;
6819 /* NOTE: Don't attempt to access the partitions list until the
6820 * initialization level indicates that all volumes are attached,
6821 * which implies that all partitions are initialized. */
6822 #ifdef AFS_PTHREAD_ENV
6823 VOL_CV_WAIT(&vol_vinit_cond);
6824 #else /* AFS_PTHREAD_ENV */
6826 #endif /* AFS_PTHREAD_ENV */
6829 VResetDiskUsage_r();
6831 #ifndef AFS_DEMAND_ATTACH_FS
6832 if (++FifteenMinuteCounter == 3) {
6833 FifteenMinuteCounter = 0;
6836 #endif /* !AFS_DEMAND_ATTACH_FS */
6848 /***************************************************/
6849 /* Volume Update List routines */
6850 /***************************************************/
6852 /* The number of minutes that a volume hasn't been updated before the
6853 * "Dont salvage" flag in the volume header will be turned on */
6854 #define SALVAGE_INTERVAL (10*60)
6859 * volume update list functionality has been moved into the VLRU
6860 * the DONT_SALVAGE flag is now set during VLRU demotion
6863 #ifndef AFS_DEMAND_ATTACH_FS
6864 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6865 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6866 static int updateSize = 0; /* number of entries possible */
6867 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6868 #endif /* !AFS_DEMAND_ATTACH_FS */
6871 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6874 vp->updateTime = FT_ApproxTime();
6875 if (V_dontSalvage(vp) == 0)
6877 V_dontSalvage(vp) = 0;
6878 VSyncVolume_r(ec, vp, 0);
6879 #ifdef AFS_DEMAND_ATTACH_FS
6880 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6881 #else /* !AFS_DEMAND_ATTACH_FS */
6884 if (UpdateList == NULL) {
6885 updateSize = UPDATE_LIST_SIZE;
6886 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6888 if (nUpdatedVolumes == updateSize) {
6890 if (updateSize > 524288) {
6891 Log("warning: there is likely a bug in the volume update scanner\n");
6894 UpdateList = realloc(UpdateList,
6895 sizeof(VolumeId) * updateSize);
6898 opr_Assert(UpdateList != NULL);
6899 UpdateList[nUpdatedVolumes++] = V_id(vp);
6900 #endif /* !AFS_DEMAND_ATTACH_FS */
6903 #ifndef AFS_DEMAND_ATTACH_FS
6905 VScanUpdateList(void)
6910 afs_uint32 now = FT_ApproxTime();
6911 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6912 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6914 UpdateList[i - gap] = UpdateList[i];
6916 /* XXX this routine needlessly messes up the Volume LRU by
6917 * breaking the LRU temporal-locality assumptions.....
6918 * we should use a special volume header allocator here */
6919 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6922 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6923 V_dontSalvage(vp) = DONT_SALVAGE;
6924 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6932 #ifndef AFS_PTHREAD_ENV
6934 #endif /* !AFS_PTHREAD_ENV */
6936 nUpdatedVolumes -= gap;
6938 #endif /* !AFS_DEMAND_ATTACH_FS */
6941 /***************************************************/
6942 /* Volume LRU routines */
6943 /***************************************************/
6948 * with demand attach fs, we attempt to soft detach(1)
6949 * volumes which have not been accessed in a long time
6950 * in order to speed up fileserver shutdown
6952 * (1) by soft detach we mean a process very similar
6953 * to VOffline, except the final state of the
6954 * Volume will be VOL_STATE_PREATTACHED, instead
6955 * of the usual VOL_STATE_UNATTACHED
6957 #ifdef AFS_DEMAND_ATTACH_FS
6959 /* implementation is reminiscent of a generational GC
6961 * queue 0 is newly attached volumes. this queue is
6962 * sorted by attach timestamp
6964 * queue 1 is volumes that have been around a bit
6965 * longer than queue 0. this queue is sorted by
6968 * queue 2 is volumes tha have been around the longest.
6969 * this queue is unsorted
6971 * queue 3 is volumes that have been marked as
6972 * candidates for soft detachment. this queue is
6975 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6976 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6979 * definition of a VLRU queue.
6982 volatile struct rx_queue q;
6989 * main VLRU data structure.
6992 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6995 /** time interval (in seconds) between promotion passes for
6996 * each young generation queue. */
6997 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6999 /** time interval (in seconds) between soft detach candidate
7000 * scans for each generation queue.
7002 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
7003 * we perform a soft detach pass. */
7004 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
7006 /* scheduler state */
7007 int next_idx; /**< next queue to receive attention */
7008 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
7009 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
7011 int scanner_state; /**< state of scanner thread */
7012 pthread_cond_t cv; /**< state transition CV */
7015 /** global VLRU state */
7016 static struct VLRU volume_LRU;
7019 * defined states for VLRU scanner thread.
7022 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7023 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7024 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7025 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7026 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7027 } vlru_thread_state_t;
7029 /* vlru disk data header stuff */
7030 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7031 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7033 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7034 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7037 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7038 * soft detachment. */
7039 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7041 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7042 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7044 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7045 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7047 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7048 static afs_uint32 VLRU_enabled = 1;
7050 /* queue synchronization routines */
7051 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7052 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7053 static void VLRU_Wait_r(struct VLRU_q * q);
7056 * set VLRU subsystem tunable parameters.
7058 * @param[in] option tunable option to modify
7059 * @param[in] val new value for tunable parameter
7061 * @pre @c VInitVolumePackage2 has not yet been called.
7063 * @post tunable parameter is modified
7067 * @note valid option parameters are:
7068 * @arg @c VLRU_SET_THRESH
7069 * set the period of inactivity after which
7070 * volumes are eligible for soft detachment
7071 * @arg @c VLRU_SET_INTERVAL
7072 * set the time interval between calls
7073 * to the volume LRU "garbage collector"
7074 * @arg @c VLRU_SET_MAX
7075 * set the max number of volumes to deallocate
7079 VLRU_SetOptions(int option, afs_uint32 val)
7081 if (option == VLRU_SET_THRESH) {
7082 VLRU_offline_thresh = val;
7083 } else if (option == VLRU_SET_INTERVAL) {
7084 VLRU_offline_interval = val;
7085 } else if (option == VLRU_SET_MAX) {
7086 VLRU_offline_max = val;
7087 } else if (option == VLRU_SET_ENABLED) {
7090 VLRU_ComputeConstants();
7094 * compute VLRU internal timing parameters.
7096 * @post VLRU scanner thread internal timing parameters are computed
7098 * @note computes internal timing parameters based upon user-modifiable
7099 * tunable parameters.
7103 * @internal volume package internal use only.
7106 VLRU_ComputeConstants(void)
7108 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7110 /* compute the candidate scan interval */
7111 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7113 /* compute the promotion intervals */
7114 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7115 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7118 /* compute the gen 0 scan interval */
7119 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7121 /* compute the gen 0 scan interval */
7122 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7127 * initialize VLRU subsystem.
7129 * @pre this function has not yet been called
7131 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7135 * @internal volume package internal use only.
7141 pthread_attr_t attrs;
7144 if (!VLRU_enabled) {
7145 Log("VLRU: disabled\n");
7149 /* initialize each of the VLRU queues */
7150 for (i = 0; i < VLRU_QUEUES; i++) {
7151 queue_Init(&volume_LRU.q[i]);
7152 volume_LRU.q[i].len = 0;
7153 volume_LRU.q[i].busy = 0;
7154 opr_cv_init(&volume_LRU.q[i].cv);
7157 /* setup the timing constants */
7158 VLRU_ComputeConstants();
7160 /* XXX put inside log level check? */
7161 Log("VLRU: starting scanner with the following configuration parameters:\n");
7162 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7163 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7164 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7165 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7166 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7167 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7169 /* start up the VLRU scanner */
7170 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7171 if (programType == fileServer) {
7172 opr_cv_init(&volume_LRU.cv);
7173 opr_Verify(pthread_attr_init(&attrs) == 0);
7174 opr_Verify(pthread_attr_setdetachstate(&attrs,
7175 PTHREAD_CREATE_DETACHED) == 0);
7176 opr_Verify(pthread_create(&tid, &attrs,
7177 &VLRU_ScannerThread, NULL) == 0);
7182 * initialize the VLRU-related fields of a newly allocated volume object.
7184 * @param[in] vp pointer to volume object
7187 * @arg @c VOL_LOCK is held.
7188 * @arg volume object is not on a VLRU queue.
7190 * @post VLRU fields are initialized to indicate that volume object is not
7191 * currently registered with the VLRU subsystem
7195 * @internal volume package interal use only.
7198 VLRU_Init_Node_r(Volume * vp)
7203 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7204 vp->vlru.idx = VLRU_QUEUE_INVALID;
7208 * add a volume object to a VLRU queue.
7210 * @param[in] vp pointer to volume object
7213 * @arg @c VOL_LOCK is held.
7214 * @arg caller MUST hold a lightweight ref on @p vp.
7215 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7217 * @post the volume object is added to the appropriate VLRU queue
7219 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7220 * then the volume is added to that queue. Otherwise, the value
7221 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7222 * volume is added to the NEW generation queue.
7224 * @note @c VOL_LOCK may be dropped internally
7226 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7227 * during the add operation, and is restored to the previous
7228 * state prior to return.
7232 * @internal volume package internal use only.
7235 VLRU_Add_r(Volume * vp)
7238 VolState state_save;
7243 if (queue_IsOnQueue(&vp->vlru))
7246 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7249 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7250 idx = VLRU_QUEUE_NEW;
7253 VLRU_Wait_r(&volume_LRU.q[idx]);
7255 /* repeat check since VLRU_Wait_r may have dropped
7257 if (queue_IsNotOnQueue(&vp->vlru)) {
7259 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7260 volume_LRU.q[idx].len++;
7261 V_attachFlags(vp) |= VOL_ON_VLRU;
7262 vp->stats.last_promote = FT_ApproxTime();
7265 VChangeState_r(vp, state_save);
7269 * delete a volume object from a VLRU queue.
7271 * @param[in] vp pointer to volume object
7274 * @arg @c VOL_LOCK is held.
7275 * @arg caller MUST hold a lightweight ref on @p vp.
7276 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7278 * @post volume object is removed from the VLRU queue
7280 * @note @c VOL_LOCK may be dropped internally
7284 * @todo We should probably set volume state to something exlcusive
7285 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7287 * @internal volume package internal use only.
7290 VLRU_Delete_r(Volume * vp)
7297 if (queue_IsNotOnQueue(&vp->vlru))
7303 if (idx == VLRU_QUEUE_INVALID)
7305 VLRU_Wait_r(&volume_LRU.q[idx]);
7306 } while (idx != vp->vlru.idx);
7308 /* now remove from the VLRU and update
7309 * the appropriate counter */
7310 queue_Remove(&vp->vlru);
7311 volume_LRU.q[idx].len--;
7312 vp->vlru.idx = VLRU_QUEUE_INVALID;
7313 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7317 * tell the VLRU subsystem that a volume was just accessed.
7319 * @param[in] vp pointer to volume object
7322 * @arg @c VOL_LOCK is held
7323 * @arg caller MUST hold a lightweight ref on @p vp
7324 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7326 * @post volume VLRU access statistics are updated. If the volume was on
7327 * the VLRU soft detach candidate queue, it is moved to the NEW
7330 * @note @c VOL_LOCK may be dropped internally
7334 * @internal volume package internal use only.
7337 VLRU_UpdateAccess_r(Volume * vp)
7339 Volume * rvp = NULL;
7344 if (queue_IsNotOnQueue(&vp->vlru))
7347 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7349 /* update the access timestamp */
7350 vp->stats.last_get = FT_ApproxTime();
7353 * if the volume is on the soft detach candidate
7354 * list, we need to safely move it back to a
7355 * regular generation. this has to be done
7356 * carefully so we don't race against the scanner
7360 /* if this volume is on the soft detach candidate queue,
7361 * then grab exclusive access to the necessary queues */
7362 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7364 VCreateReservation_r(rvp);
7366 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7367 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7368 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7369 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7372 /* make sure multiple threads don't race to update */
7373 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7374 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7378 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7379 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7380 VCancelReservation_r(rvp);
7385 * switch a volume between two VLRU queues.
7387 * @param[in] vp pointer to volume object
7388 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7389 * @param[in] append controls whether the volume will be appended or
7390 * prepended to the queue. A nonzero value means it will
7391 * be appended; zero means it will be prepended.
7393 * @pre The new (and old, if applicable) queue(s) must either be owned
7394 * exclusively by the calling thread for asynchronous manipulation,
7395 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7396 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7397 * for further details of the queue asynchronous processing mechanism.
7399 * @post If the volume object was already on a VLRU queue, it is
7400 * removed from the queue. Depending on the value of the append
7401 * parameter, the volume object is either appended or prepended
7402 * to the VLRU queue referenced by the new_idx parameter.
7406 * @see VLRU_BeginExclusive_r
7407 * @see VLRU_EndExclusive_r
7410 * @internal volume package internal use only.
7413 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7415 if (queue_IsNotOnQueue(&vp->vlru))
7418 queue_Remove(&vp->vlru);
7419 volume_LRU.q[vp->vlru.idx].len--;
7421 /* put the volume back on the correct generational queue */
7423 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7425 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7428 volume_LRU.q[new_idx].len++;
7429 vp->vlru.idx = new_idx;
7433 * VLRU background thread.
7435 * The VLRU Scanner Thread is responsible for periodically scanning through
7436 * each VLRU queue looking for volumes which should be moved to another
7437 * queue, or soft detached.
7439 * @param[in] args unused thread arguments parameter
7441 * @return unused thread return value
7442 * @retval NULL always
7444 * @internal volume package internal use only.
7447 VLRU_ScannerThread(void * args)
7449 afs_uint32 now, min_delay, delay;
7450 int i, min_idx, min_op, overdue, state;
7452 /* set t=0 for promotion cycle to be
7453 * fileserver startup */
7454 now = FT_ApproxTime();
7455 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7456 volume_LRU.last_promotion[i] = now;
7459 /* don't start the scanner until VLRU_offline_thresh
7460 * plus a small delay for VInitVolumePackage2 to finish
7463 sleep(VLRU_offline_thresh + 60);
7465 /* set t=0 for scan cycle to be now */
7466 now = FT_ApproxTime();
7467 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7468 volume_LRU.last_scan[i] = now;
7472 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7473 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7476 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7477 /* check to see if we've been asked to pause */
7478 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7479 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7480 opr_cv_broadcast(&volume_LRU.cv);
7482 VOL_CV_WAIT(&volume_LRU.cv);
7483 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7486 /* scheduling can happen outside the glock */
7489 /* figure out what is next on the schedule */
7491 /* figure out a potential schedule for the new generation first */
7493 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7496 if (min_delay > volume_LRU.scan_interval[0]) {
7497 /* unsigned overflow -- we're overdue to run this scan */
7502 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7504 i = VLRU_QUEUE_CANDIDATE;
7505 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7506 if (delay < min_delay) {
7510 if (delay > volume_LRU.scan_interval[i]) {
7511 /* unsigned overflow -- we're overdue to run this scan */
7518 /* if we're still not overdue for something, figure out schedules for promotions */
7519 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7520 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7521 if (delay < min_delay) {
7526 if (delay > volume_LRU.promotion_interval[i]) {
7527 /* unsigned overflow -- we're overdue to run this promotion */
7536 /* sleep as needed */
7541 /* do whatever is next */
7544 VLRU_Promote_r(min_idx);
7545 VLRU_Demote_r(min_idx+1);
7547 VLRU_Scan_r(min_idx);
7549 now = FT_ApproxTime();
7552 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7554 /* signal that scanner is down */
7555 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7556 opr_cv_broadcast(&volume_LRU.cv);
7562 * promote volumes from one VLRU generation to the next.
7564 * This routine scans a VLRU generation looking for volumes which are
7565 * eligible to be promoted to the next generation. All volumes which
7566 * meet the eligibility requirement are promoted.
7568 * Promotion eligibility is based upon meeting both of the following
7571 * @arg The volume has been accessed since the last promotion:
7572 * @c (vp->stats.last_get >= vp->stats.last_promote)
7573 * @arg The last promotion occurred at least
7574 * @c volume_LRU.promotion_interval[idx] seconds ago
7576 * As a performance optimization, promotions are "globbed". In other
7577 * words, we promote arbitrarily large contiguous sublists of elements
7580 * @param[in] idx VLRU queue index to scan
7584 * @internal VLRU internal use only.
7587 VLRU_Promote_r(int idx)
7589 int len, chaining, promote;
7590 afs_uint32 now, thresh;
7591 struct rx_queue *qp, *nqp;
7592 Volume * vp, *start = NULL, *end = NULL;
7594 /* get exclusive access to two chains, and drop the glock */
7595 VLRU_Wait_r(&volume_LRU.q[idx]);
7596 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7597 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7598 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7601 thresh = volume_LRU.promotion_interval[idx];
7602 now = FT_ApproxTime();
7605 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7606 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7607 promote = (((vp->stats.last_promote + thresh) <= now) &&
7608 (vp->stats.last_get >= vp->stats.last_promote));
7616 /* promote and prepend chain */
7617 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7631 /* promote and prepend */
7632 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7636 volume_LRU.q[idx].len -= len;
7637 volume_LRU.q[idx+1].len += len;
7640 /* release exclusive access to the two chains */
7642 volume_LRU.last_promotion[idx] = now;
7643 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7644 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7647 /* run the demotions */
7649 VLRU_Demote_r(int idx)
7652 int len, chaining, demote;
7653 afs_uint32 now, thresh;
7654 struct rx_queue *qp, *nqp;
7655 Volume * vp, *start = NULL, *end = NULL;
7656 Volume ** salv_flag_vec = NULL;
7657 int salv_vec_offset = 0;
7659 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7661 /* get exclusive access to two chains, and drop the glock */
7662 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7663 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7664 VLRU_Wait_r(&volume_LRU.q[idx]);
7665 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7668 /* no big deal if this allocation fails */
7669 if (volume_LRU.q[idx].len) {
7670 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7673 now = FT_ApproxTime();
7674 thresh = volume_LRU.promotion_interval[idx-1];
7677 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7678 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7679 demote = (((vp->stats.last_promote + thresh) <= now) &&
7680 (vp->stats.last_get < (now - thresh)));
7682 /* we now do volume update list DONT_SALVAGE flag setting during
7683 * demotion passes */
7684 if (salv_flag_vec &&
7685 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7687 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7688 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7689 salv_flag_vec[salv_vec_offset++] = vp;
7690 VCreateReservation_r(vp);
7699 /* demote and append chain */
7700 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7714 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7718 volume_LRU.q[idx].len -= len;
7719 volume_LRU.q[idx-1].len += len;
7722 /* release exclusive access to the two chains */
7724 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7725 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7727 /* now go back and set the DONT_SALVAGE flags as appropriate */
7728 if (salv_flag_vec) {
7730 for (i = 0; i < salv_vec_offset; i++) {
7731 vp = salv_flag_vec[i];
7732 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7733 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7734 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7737 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7738 V_dontSalvage(vp) = DONT_SALVAGE;
7739 VUpdateVolume_r(&ec, vp, 0);
7743 VCancelReservation_r(vp);
7745 free(salv_flag_vec);
7749 /* run a pass of the VLRU GC scanner */
7751 VLRU_Scan_r(int idx)
7753 afs_uint32 now, thresh;
7754 struct rx_queue *qp, *nqp;
7758 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7760 /* gain exclusive access to the idx VLRU */
7761 VLRU_Wait_r(&volume_LRU.q[idx]);
7762 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7764 if (idx != VLRU_QUEUE_CANDIDATE) {
7765 /* gain exclusive access to the candidate VLRU */
7766 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7767 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7770 now = FT_ApproxTime();
7771 thresh = now - VLRU_offline_thresh;
7773 /* perform candidate selection and soft detaching */
7774 if (idx == VLRU_QUEUE_CANDIDATE) {
7775 /* soft detach some volumes from the candidate pool */
7779 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7780 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7781 if (i >= VLRU_offline_max) {
7784 /* check timestamp to see if it's a candidate for soft detaching */
7785 if (vp->stats.last_get <= thresh) {
7787 if (VCheckSoftDetach(vp, thresh))
7793 /* scan for volumes to become soft detach candidates */
7794 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7795 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7797 /* check timestamp to see if it's a candidate for soft detaching */
7798 if (vp->stats.last_get <= thresh) {
7799 VCheckSoftDetachCandidate(vp, thresh);
7802 if (!(i&0x7f)) { /* lock coarsening optimization */
7810 /* relinquish exclusive access to the VLRU chains */
7814 volume_LRU.last_scan[idx] = now;
7815 if (idx != VLRU_QUEUE_CANDIDATE) {
7816 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7818 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7821 /* check whether volume is safe to soft detach
7822 * caller MUST NOT hold a ref count on vp */
7824 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7828 if (vp->nUsers || vp->nWaiters)
7831 if (vp->stats.last_get <= thresh) {
7832 ret = VSoftDetachVolume_r(vp, thresh);
7838 /* check whether volume should be made a
7839 * soft detach candidate */
7841 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7844 if (vp->nUsers || vp->nWaiters)
7849 opr_Assert(idx == VLRU_QUEUE_NEW);
7851 if (vp->stats.last_get <= thresh) {
7852 /* move to candidate pool */
7853 queue_Remove(&vp->vlru);
7854 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7855 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7856 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7857 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7865 /* begin exclusive access on VLRU */
7867 VLRU_BeginExclusive_r(struct VLRU_q * q)
7869 opr_Assert(q->busy == 0);
7873 /* end exclusive access on VLRU */
7875 VLRU_EndExclusive_r(struct VLRU_q * q)
7877 opr_Assert(q->busy);
7879 opr_cv_broadcast(&q->cv);
7882 /* wait for another thread to end exclusive access on VLRU */
7884 VLRU_Wait_r(struct VLRU_q * q)
7887 VOL_CV_WAIT(&q->cv);
7892 * volume soft detach
7894 * caller MUST NOT hold a ref count on vp */
7896 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7901 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7903 ts_save = vp->stats.last_get;
7904 if (ts_save > thresh)
7907 if (vp->nUsers || vp->nWaiters)
7910 if (VIsExclusiveState(V_attachState(vp))) {
7914 switch (V_attachState(vp)) {
7915 case VOL_STATE_UNATTACHED:
7916 case VOL_STATE_PREATTACHED:
7917 case VOL_STATE_ERROR:
7918 case VOL_STATE_GOING_OFFLINE:
7919 case VOL_STATE_SHUTTING_DOWN:
7920 case VOL_STATE_SALVAGING:
7921 case VOL_STATE_DELETED:
7922 volume_LRU.q[vp->vlru.idx].len--;
7924 /* create and cancel a reservation to
7925 * give the volume an opportunity to
7927 VCreateReservation_r(vp);
7928 queue_Remove(&vp->vlru);
7929 vp->vlru.idx = VLRU_QUEUE_INVALID;
7930 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7931 VCancelReservation_r(vp);
7937 /* hold the volume and take it offline.
7938 * no need for reservations, as VHold_r
7939 * takes care of that internally. */
7940 if (VHold_r(vp) == 0) {
7941 /* vhold drops the glock, so now we should
7942 * check to make sure we aren't racing against
7943 * other threads. if we are racing, offlining vp
7944 * would be wasteful, and block the scanner for a while
7948 (vp->shuttingDown) ||
7949 (vp->goingOffline) ||
7950 (vp->stats.last_get != ts_save)) {
7951 /* looks like we're racing someone else. bail */
7955 /* pull it off the VLRU */
7956 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7957 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7958 queue_Remove(&vp->vlru);
7959 vp->vlru.idx = VLRU_QUEUE_INVALID;
7960 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7962 /* take if offline */
7963 VOffline_r(vp, "volume has been soft detached");
7965 /* invalidate the volume header cache */
7966 FreeVolumeHeader(vp);
7969 IncUInt64(&VStats.soft_detaches);
7970 vp->stats.soft_detaches++;
7972 /* put in pre-attached state so demand
7973 * attacher can work on it */
7974 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7980 #endif /* AFS_DEMAND_ATTACH_FS */
7983 /***************************************************/
7984 /* Volume Header Cache routines */
7985 /***************************************************/
7988 * volume header cache.
7990 struct volume_hdr_LRU_t volume_hdr_LRU;
7993 * initialize the volume header cache.
7995 * @param[in] howMany number of header cache entries to preallocate
7997 * @pre VOL_LOCK held. Function has never been called before.
7999 * @post howMany cache entries are allocated, initialized, and added
8000 * to the LRU list. Header cache statistics are initialized.
8002 * @note only applicable to fileServer program type. Should only be
8003 * called once during volume package initialization.
8005 * @internal volume package internal use only.
8008 VInitVolumeHeaderCache(afs_uint32 howMany)
8010 struct volHeader *hp;
8011 if (programType != fileServer)
8013 queue_Init(&volume_hdr_LRU);
8014 volume_hdr_LRU.stats.free = 0;
8015 volume_hdr_LRU.stats.used = howMany;
8016 volume_hdr_LRU.stats.attached = 0;
8017 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8018 opr_Assert(hp != NULL);
8021 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8022 * to ensure they have the right values
8024 ReleaseVolumeHeader(hp++);
8027 /* get a volume header off of the volume header LRU.
8029 * @return volume header
8030 * @retval NULL no usable volume header is available on the LRU
8032 * @pre VOL_LOCK held
8034 * @post for DAFS, if the returned header is associated with a volume, that
8035 * volume is NOT in an exclusive state
8037 * @internal volume package internal use only.
8039 #ifdef AFS_DEMAND_ATTACH_FS
8040 static struct volHeader*
8041 GetVolHeaderFromLRU(void)
8043 struct volHeader *hd = NULL, *qh, *nqh;
8044 /* Usually, a volume in an exclusive state will not have its header on
8045 * the LRU. However, it is possible for this to occur when a salvage
8046 * request is received over FSSYNC, and possibly in other corner cases.
8047 * So just skip over headers whose volumes are in an exclusive state. We
8048 * could VWaitExclusiveState_r instead, but not waiting is faster and
8050 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8051 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8059 #else /* AFS_DEMAND_ATTACH_FS */
8060 static struct volHeader*
8061 GetVolHeaderFromLRU(void)
8063 struct volHeader *hd = NULL;
8064 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8065 hd = queue_First(&volume_hdr_LRU, volHeader);
8070 #endif /* !AFS_DEMAND_ATTACH_FS */
8073 * get a volume header and attach it to the volume object.
8075 * @param[in] vp pointer to volume object
8077 * @return cache entry status
8078 * @retval 0 volume header was newly attached; cache data is invalid
8079 * @retval 1 volume header was previously attached; cache data is valid
8081 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8083 * @post volume header attached to volume object. if necessary, header cache
8084 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8086 * @note VOL_LOCK may be dropped
8088 * @warning this interface does not load header data from disk. it merely
8089 * attaches a header object to the volume object, and may sync the old
8090 * header cache data out to disk in the process.
8092 * @internal volume package internal use only.
8095 GetVolumeHeader(Volume * vp)
8098 struct volHeader *hd;
8100 static int everLogged = 0;
8102 #ifdef AFS_DEMAND_ATTACH_FS
8103 VolState vp_save = 0, back_save = 0;
8105 /* XXX debug 9/19/05 we've apparently got
8106 * a ref counting bug somewhere that's
8107 * breaking the nUsers == 0 => header on LRU
8109 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8110 Log("nUsers == 0, but header not on LRU\n");
8115 old = (vp->header != NULL); /* old == volume already has a header */
8117 if (programType != fileServer) {
8118 /* for volume utilities, we allocate volHeaders as needed */
8120 hd = calloc(1, sizeof(*vp->header));
8121 opr_Assert(hd != NULL);
8124 #ifdef AFS_DEMAND_ATTACH_FS
8125 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8129 /* for the fileserver, we keep a volume header cache */
8131 /* the header we previously dropped in the lru is
8132 * still available. pull it off the lru and return */
8135 opr_Assert(hd->back == vp);
8136 #ifdef AFS_DEMAND_ATTACH_FS
8137 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8140 hd = GetVolHeaderFromLRU();
8142 /* LRU is empty, so allocate a new volHeader
8143 * this is probably indicative of a leak, so let the user know */
8144 hd = calloc(1, sizeof(struct volHeader));
8145 opr_Assert(hd != NULL);
8147 Log("****Allocated more volume headers, probably leak****\n");
8150 volume_hdr_LRU.stats.free++;
8153 /* this header used to belong to someone else.
8154 * we'll need to check if the header needs to
8155 * be sync'd out to disk */
8157 #ifdef AFS_DEMAND_ATTACH_FS
8158 /* GetVolHeaderFromLRU had better not give us back a header
8159 * with a volume in exclusive state... */
8160 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8163 if (hd->diskstuff.inUse) {
8164 /* volume was in use, so we'll need to sync
8165 * its header to disk */
8167 #ifdef AFS_DEMAND_ATTACH_FS
8168 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8169 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8170 VCreateReservation_r(hd->back);
8174 WriteVolumeHeader_r(&error, hd->back);
8175 /* Ignore errors; catch them later */
8177 #ifdef AFS_DEMAND_ATTACH_FS
8182 hd->back->header = NULL;
8183 #ifdef AFS_DEMAND_ATTACH_FS
8184 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8186 if (hd->diskstuff.inUse) {
8187 VChangeState_r(hd->back, back_save);
8188 VCancelReservation_r(hd->back);
8189 VChangeState_r(vp, vp_save);
8193 volume_hdr_LRU.stats.attached++;
8197 #ifdef AFS_DEMAND_ATTACH_FS
8198 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8201 volume_hdr_LRU.stats.free--;
8202 volume_hdr_LRU.stats.used++;
8204 IncUInt64(&VStats.hdr_gets);
8205 #ifdef AFS_DEMAND_ATTACH_FS
8206 IncUInt64(&vp->stats.hdr_gets);
8207 vp->stats.last_hdr_get = FT_ApproxTime();
8214 * make sure volume header is attached and contains valid cache data.
8216 * @param[out] ec outbound error code
8217 * @param[in] vp pointer to volume object
8219 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8221 * @post header cache entry attached, and loaded with valid data, or
8222 * *ec is nonzero, and the header is released back into the LRU.
8224 * @internal volume package internal use only.
8227 LoadVolumeHeader(Error * ec, Volume * vp)
8229 #ifdef AFS_DEMAND_ATTACH_FS
8230 VolState state_save;
8234 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8235 IncUInt64(&VStats.hdr_loads);
8236 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8239 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8240 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8242 IncUInt64(&vp->stats.hdr_loads);
8243 now = FT_ApproxTime();
8247 V_attachFlags(vp) |= VOL_HDR_LOADED;
8248 vp->stats.last_hdr_load = now;
8250 VChangeState_r(vp, state_save);
8252 #else /* AFS_DEMAND_ATTACH_FS */
8254 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8255 IncUInt64(&VStats.hdr_loads);
8257 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8258 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8261 #endif /* AFS_DEMAND_ATTACH_FS */
8263 /* maintain (nUsers==0) => header in LRU invariant */
8264 FreeVolumeHeader(vp);
8269 * release a header cache entry back into the LRU list.
8271 * @param[in] hd pointer to volume header cache object
8273 * @pre VOL_LOCK held.
8275 * @post header cache object appended onto end of LRU list.
8277 * @note only applicable to fileServer program type.
8279 * @note used to place a header cache entry back into the
8280 * LRU pool without invalidating it as a cache entry.
8282 * @internal volume package internal use only.
8285 ReleaseVolumeHeader(struct volHeader *hd)
8287 if (programType != fileServer)
8289 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8291 queue_Append(&volume_hdr_LRU, hd);
8292 #ifdef AFS_DEMAND_ATTACH_FS
8294 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8297 volume_hdr_LRU.stats.free++;
8298 volume_hdr_LRU.stats.used--;
8302 * free/invalidate a volume header cache entry.
8304 * @param[in] vp pointer to volume object
8306 * @pre VOL_LOCK is held.
8308 * @post For fileserver, header cache entry is returned to LRU, and it is
8309 * invalidated as a cache entry. For volume utilities, the header
8310 * cache entry is freed.
8312 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8313 * whenever it is necessary to invalidate the header cache entry.
8315 * @see ReleaseVolumeHeader
8317 * @internal volume package internal use only.
8320 FreeVolumeHeader(Volume * vp)
8322 struct volHeader *hd = vp->header;
8325 if (programType == fileServer) {
8326 ReleaseVolumeHeader(hd);
8331 #ifdef AFS_DEMAND_ATTACH_FS
8332 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8334 volume_hdr_LRU.stats.attached--;
8339 /***************************************************/
8340 /* Volume Hash Table routines */
8341 /***************************************************/
8344 * set size of volume object hash table.
8346 * @param[in] logsize log(2) of desired hash table size
8348 * @return operation status
8350 * @retval -1 failure
8352 * @pre MUST be called prior to VInitVolumePackage2
8354 * @post Volume Hash Table will have 2^logsize buckets
8357 VSetVolHashSize(int logsize)
8359 /* 64 to 268435456 hash buckets seems like a reasonable range */
8360 if ((logsize < 6 ) || (logsize > 28)) {
8365 VolumeHashTable.Size = opr_jhash_size(logsize);
8366 VolumeHashTable.Mask = opr_jhash_mask(logsize);
8368 /* we can't yet support runtime modification of this
8369 * parameter. we'll need a configuration rwlock to
8370 * make runtime modification feasible.... */
8377 * initialize dynamic data structures for volume hash table.
8379 * @post hash table is allocated, and fields are initialized.
8381 * @internal volume package internal use only.
8384 VInitVolumeHash(void)
8388 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8389 sizeof(VolumeHashChainHead));
8390 opr_Assert(VolumeHashTable.Table != NULL);
8392 for (i=0; i < VolumeHashTable.Size; i++) {
8393 queue_Init(&VolumeHashTable.Table[i]);
8394 #ifdef AFS_DEMAND_ATTACH_FS
8395 opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8396 #endif /* AFS_DEMAND_ATTACH_FS */
8401 * add a volume object to the hash table.
8403 * @param[in] vp pointer to volume object
8404 * @param[in] hashid hash of volume id
8406 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8409 * @post volume is added to hash chain.
8411 * @internal volume package internal use only.
8413 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8414 * asynchronous hash chain reordering to finish.
8417 AddVolumeToHashTable(Volume * vp, VolumeId hashid)
8419 VolumeHashChainHead * head;
8421 if (queue_IsOnQueue(vp))
8424 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8426 #ifdef AFS_DEMAND_ATTACH_FS
8427 /* wait for the hash chain to become available */
8430 V_attachFlags(vp) |= VOL_IN_HASH;
8431 vp->chainCacheCheck = ++head->cacheCheck;
8432 #endif /* AFS_DEMAND_ATTACH_FS */
8435 vp->hashid = hashid;
8436 queue_Append(head, vp);
8440 * delete a volume object from the hash table.
8442 * @param[in] vp pointer to volume object
8444 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8447 * @post volume is removed from hash chain.
8449 * @internal volume package internal use only.
8451 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8452 * asynchronous hash chain reordering to finish.
8455 DeleteVolumeFromHashTable(Volume * vp)
8457 VolumeHashChainHead * head;
8459 if (!queue_IsOnQueue(vp))
8462 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8464 #ifdef AFS_DEMAND_ATTACH_FS
8465 /* wait for the hash chain to become available */
8468 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8470 #endif /* AFS_DEMAND_ATTACH_FS */
8474 /* do NOT reset hashid to zero, as the online
8475 * salvager package may need to know the volume id
8476 * after the volume is removed from the hash */
8480 * lookup a volume object in the hash table given a volume id.
8482 * @param[out] ec error code return
8483 * @param[in] volumeId volume id
8484 * @param[in] hint volume object which we believe could be the correct
8487 * @return volume object pointer
8488 * @retval NULL no such volume id is registered with the hash table.
8490 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8493 * @post volume object with the given id is returned. volume object and
8494 * hash chain access statistics are updated. hash chain may have
8497 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8498 * asynchronous hash chain reordering operation to finish, or
8499 * in order for us to perform an asynchronous chain reordering.
8501 * @note Hash chain reorderings occur when the access count for the
8502 * volume object being looked up exceeds the sum of the previous
8503 * node's (the node ahead of it in the hash chain linked list)
8504 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8506 * @note For DAFS, the hint parameter allows us to short-circuit if the
8507 * cacheCheck fields match between the hash chain head and the
8508 * hint volume object.
8511 VLookupVolume_r(Error * ec, VolumeId volumeId, Volume * hint)
8515 #ifdef AFS_DEMAND_ATTACH_FS
8518 VolumeHashChainHead * head;
8521 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8523 #ifdef AFS_DEMAND_ATTACH_FS
8524 /* wait for the hash chain to become available */
8527 /* check to see if we can short circuit without walking the hash chain */
8528 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8529 IncUInt64(&hint->stats.hash_short_circuits);
8532 #endif /* AFS_DEMAND_ATTACH_FS */
8534 /* someday we need to either do per-chain locks, RWlocks,
8535 * or both for volhash access.
8536 * (and move to a data structure with better cache locality) */
8538 /* search the chain for this volume id */
8539 for(queue_Scan(head, vp, np, Volume)) {
8541 if (vp->hashid == volumeId) {
8546 if (queue_IsEnd(head, vp)) {
8550 #ifdef AFS_DEMAND_ATTACH_FS
8551 /* update hash chain statistics */
8554 FillInt64(lks, 0, looks);
8555 AddUInt64(head->looks, lks, &head->looks);
8556 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8557 IncUInt64(&head->gets);
8562 IncUInt64(&vp->stats.hash_lookups);
8564 /* for demand attach fileserver, we permit occasional hash chain reordering
8565 * so that frequently looked up volumes move towards the head of the chain */
8566 pp = queue_Prev(vp, Volume);
8567 if (!queue_IsEnd(head, pp)) {
8568 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8569 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8570 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8571 VReorderHash_r(head, pp, vp);
8575 /* update the short-circuit cache check */
8576 vp->chainCacheCheck = head->cacheCheck;
8578 #endif /* AFS_DEMAND_ATTACH_FS */
8583 #ifdef AFS_DEMAND_ATTACH_FS
8584 /* perform volume hash chain reordering.
8586 * advance a subchain beginning at vp ahead of
8587 * the adjacent subchain ending at pp */
8589 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8591 Volume *tp, *np, *lp;
8592 afs_uint64 move_thresh;
8594 /* this should never be called if the chain is already busy, so
8595 * no need to wait for other exclusive chain ops to finish */
8597 /* this is a rather heavy set of operations,
8598 * so let's set the chain busy flag and drop
8600 VHashBeginExclusive_r(head);
8603 /* scan forward in the chain from vp looking for the last element
8604 * in the chain we want to advance */
8605 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8606 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8607 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8608 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8612 lp = queue_Prev(tp, Volume);
8614 /* scan backwards from pp to determine where to splice and
8615 * insert the subchain we're advancing */
8616 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8617 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8621 tp = queue_Next(tp, Volume);
8623 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8624 queue_MoveChainBefore(tp,vp,lp);
8627 IncUInt64(&VStats.hash_reorders);
8629 IncUInt64(&head->reorders);
8631 /* wake up any threads waiting for the hash chain */
8632 VHashEndExclusive_r(head);
8636 /* demand-attach fs volume hash
8637 * asynchronous exclusive operations */
8640 * begin an asynchronous exclusive operation on a volume hash chain.
8642 * @param[in] head pointer to volume hash chain head object
8644 * @pre VOL_LOCK held. hash chain is quiescent.
8646 * @post hash chain marked busy.
8648 * @note this interface is used in conjunction with VHashEndExclusive_r and
8649 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8650 * volume hash chain. Its main use case is hash chain reordering, which
8651 * has the potential to be a highly latent operation.
8653 * @see VHashEndExclusive_r
8658 * @internal volume package internal use only.
8661 VHashBeginExclusive_r(VolumeHashChainHead * head)
8663 opr_Assert(head->busy == 0);
8668 * relinquish exclusive ownership of a volume hash chain.
8670 * @param[in] head pointer to volume hash chain head object
8672 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8674 * @post hash chain is marked quiescent. threads awaiting use of
8675 * chain are awakened.
8677 * @see VHashBeginExclusive_r
8682 * @internal volume package internal use only.
8685 VHashEndExclusive_r(VolumeHashChainHead * head)
8687 opr_Assert(head->busy);
8689 opr_cv_broadcast(&head->chain_busy_cv);
8693 * wait for all asynchronous operations on a hash chain to complete.
8695 * @param[in] head pointer to volume hash chain head object
8697 * @pre VOL_LOCK held.
8699 * @post hash chain object is quiescent.
8701 * @see VHashBeginExclusive_r
8702 * @see VHashEndExclusive_r
8706 * @note This interface should be called before any attempt to
8707 * traverse the hash chain. It is permissible for a thread
8708 * to gain exclusive access to the chain, and then perform
8709 * latent operations on the chain asynchronously wrt the
8712 * @warning if waiting is necessary, VOL_LOCK is dropped
8714 * @internal volume package internal use only.
8717 VHashWait_r(VolumeHashChainHead * head)
8719 while (head->busy) {
8720 VOL_CV_WAIT(&head->chain_busy_cv);
8723 #endif /* AFS_DEMAND_ATTACH_FS */
8726 /***************************************************/
8727 /* Volume by Partition List routines */
8728 /***************************************************/
8731 * demand attach fileserver adds a
8732 * linked list of volumes to each
8733 * partition object, thus allowing
8734 * for quick enumeration of all
8735 * volumes on a partition
8738 #ifdef AFS_DEMAND_ATTACH_FS
8740 * add a volume to its disk partition VByPList.
8742 * @param[in] vp pointer to volume object
8744 * @pre either the disk partition VByPList is owned exclusively
8745 * by the calling thread, or the list is quiescent and
8748 * @post volume is added to disk partition VByPList
8752 * @warning it is the caller's responsibility to ensure list
8755 * @see VVByPListWait_r
8756 * @see VVByPListBeginExclusive_r
8757 * @see VVByPListEndExclusive_r
8759 * @internal volume package internal use only.
8762 AddVolumeToVByPList_r(Volume * vp)
8764 if (queue_IsNotOnQueue(&vp->vol_list)) {
8765 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8766 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8767 vp->partition->vol_list.len++;
8772 * delete a volume from its disk partition VByPList.
8774 * @param[in] vp pointer to volume object
8776 * @pre either the disk partition VByPList is owned exclusively
8777 * by the calling thread, or the list is quiescent and
8780 * @post volume is removed from the disk partition VByPList
8784 * @warning it is the caller's responsibility to ensure list
8787 * @see VVByPListWait_r
8788 * @see VVByPListBeginExclusive_r
8789 * @see VVByPListEndExclusive_r
8791 * @internal volume package internal use only.
8794 DeleteVolumeFromVByPList_r(Volume * vp)
8796 if (queue_IsOnQueue(&vp->vol_list)) {
8797 queue_Remove(&vp->vol_list);
8798 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8799 vp->partition->vol_list.len--;
8804 * begin an asynchronous exclusive operation on a VByPList.
8806 * @param[in] dp pointer to disk partition object
8808 * @pre VOL_LOCK held. VByPList is quiescent.
8810 * @post VByPList marked busy.
8812 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8813 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8816 * @see VVByPListEndExclusive_r
8817 * @see VVByPListWait_r
8821 * @internal volume package internal use only.
8823 /* take exclusive control over the list */
8825 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8827 opr_Assert(dp->vol_list.busy == 0);
8828 dp->vol_list.busy = 1;
8832 * relinquish exclusive ownership of a VByPList.
8834 * @param[in] dp pointer to disk partition object
8836 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8838 * @post VByPList is marked quiescent. threads awaiting use of
8839 * the list are awakened.
8841 * @see VVByPListBeginExclusive_r
8842 * @see VVByPListWait_r
8846 * @internal volume package internal use only.
8849 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8851 opr_Assert(dp->vol_list.busy);
8852 dp->vol_list.busy = 0;
8853 opr_cv_broadcast(&dp->vol_list.cv);
8857 * wait for all asynchronous operations on a VByPList to complete.
8859 * @param[in] dp pointer to disk partition object
8861 * @pre VOL_LOCK is held.
8863 * @post disk partition's VByP list is quiescent
8867 * @note This interface should be called before any attempt to
8868 * traverse the VByPList. It is permissible for a thread
8869 * to gain exclusive access to the list, and then perform
8870 * latent operations on the list asynchronously wrt the
8873 * @warning if waiting is necessary, VOL_LOCK is dropped
8875 * @see VVByPListEndExclusive_r
8876 * @see VVByPListBeginExclusive_r
8878 * @internal volume package internal use only.
8881 VVByPListWait_r(struct DiskPartition64 * dp)
8883 while (dp->vol_list.busy) {
8884 VOL_CV_WAIT(&dp->vol_list.cv);
8887 #endif /* AFS_DEMAND_ATTACH_FS */
8889 /***************************************************/
8890 /* Volume Cache Statistics routines */
8891 /***************************************************/
8894 VPrintCacheStats_r(void)
8896 struct VnodeClassInfo *vcp;
8897 vcp = &VnodeClassInfo[vLarge];
8898 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);
8899 vcp = &VnodeClassInfo[vSmall];
8900 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);
8901 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8902 "%"AFS_INT64_FMT" replacements\n",
8903 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8907 VPrintCacheStats(void)
8910 VPrintCacheStats_r();
8914 #ifdef AFS_DEMAND_ATTACH_FS
8916 UInt64ToDouble(afs_uint64 * x)
8918 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8920 SplitInt64(*x, h, l);
8921 return (((double)h) * c32) + ((double) l);
8925 DoubleToPrintable(double x, char * buf, int len)
8927 static double billion = 1000000000.0;
8930 y[0] = (afs_uint32) (x / (billion * billion));
8931 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8932 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8935 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8937 snprintf(buf, len, "%d%09d", y[1], y[2]);
8939 snprintf(buf, len, "%d", y[2]);
8945 struct VLRUExtStatsEntry {
8949 struct VLRUExtStats {
8955 } queue_info[VLRU_QUEUE_INVALID];
8956 struct VLRUExtStatsEntry * vec;
8960 * add a 256-entry fudge factor onto the vector in case state changes
8961 * out from under us.
8963 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8966 * collect extended statistics for the VLRU subsystem.
8968 * @param[out] stats pointer to stats structure to be populated
8969 * @param[in] nvols number of volumes currently known to exist
8971 * @pre VOL_LOCK held
8973 * @post stats->vec allocated and populated
8975 * @return operation status
8980 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8982 afs_uint32 cur, idx, len;
8983 struct rx_queue * qp, * nqp;
8985 struct VLRUExtStatsEntry * vec;
8987 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8988 vec = stats->vec = calloc(len,
8989 sizeof(struct VLRUExtStatsEntry));
8995 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8996 VLRU_Wait_r(&volume_LRU.q[idx]);
8997 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
9000 stats->queue_info[idx].start = cur;
9002 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
9004 /* out of space in vec */
9007 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
9008 vec[cur].volid = vp->hashid;
9012 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9015 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9023 #define ENUMTOSTRING(en) #en
9024 #define ENUMCASE(en) \
9025 case en: return ENUMTOSTRING(en)
9028 vlru_idx_to_string(int idx)
9031 ENUMCASE(VLRU_QUEUE_NEW);
9032 ENUMCASE(VLRU_QUEUE_MID);
9033 ENUMCASE(VLRU_QUEUE_OLD);
9034 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9035 ENUMCASE(VLRU_QUEUE_HELD);
9036 ENUMCASE(VLRU_QUEUE_INVALID);
9038 return "**UNKNOWN**";
9043 VPrintExtendedCacheStats_r(int flags)
9046 afs_uint32 vol_sum = 0;
9053 struct stats looks, gets, reorders, len;
9054 struct stats ch_looks, ch_gets, ch_reorders;
9056 VolumeHashChainHead *head;
9058 struct VLRUExtStats vlru_stats;
9060 /* zero out stats */
9061 memset(&looks, 0, sizeof(struct stats));
9062 memset(&gets, 0, sizeof(struct stats));
9063 memset(&reorders, 0, sizeof(struct stats));
9064 memset(&len, 0, sizeof(struct stats));
9065 memset(&ch_looks, 0, sizeof(struct stats));
9066 memset(&ch_gets, 0, sizeof(struct stats));
9067 memset(&ch_reorders, 0, sizeof(struct stats));
9069 for (i = 0; i < VolumeHashTable.Size; i++) {
9070 head = &VolumeHashTable.Table[i];
9073 VHashBeginExclusive_r(head);
9076 ch_looks.sum = UInt64ToDouble(&head->looks);
9077 ch_gets.sum = UInt64ToDouble(&head->gets);
9078 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9080 /* update global statistics */
9082 looks.sum += ch_looks.sum;
9083 gets.sum += ch_gets.sum;
9084 reorders.sum += ch_reorders.sum;
9085 len.sum += (double)head->len;
9086 vol_sum += head->len;
9089 len.min = (double) head->len;
9090 len.max = (double) head->len;
9091 looks.min = ch_looks.sum;
9092 looks.max = ch_looks.sum;
9093 gets.min = ch_gets.sum;
9094 gets.max = ch_gets.sum;
9095 reorders.min = ch_reorders.sum;
9096 reorders.max = ch_reorders.sum;
9098 if (((double)head->len) < len.min)
9099 len.min = (double) head->len;
9100 if (((double)head->len) > len.max)
9101 len.max = (double) head->len;
9102 if (ch_looks.sum < looks.min)
9103 looks.min = ch_looks.sum;
9104 else if (ch_looks.sum > looks.max)
9105 looks.max = ch_looks.sum;
9106 if (ch_gets.sum < gets.min)
9107 gets.min = ch_gets.sum;
9108 else if (ch_gets.sum > gets.max)
9109 gets.max = ch_gets.sum;
9110 if (ch_reorders.sum < reorders.min)
9111 reorders.min = ch_reorders.sum;
9112 else if (ch_reorders.sum > reorders.max)
9113 reorders.max = ch_reorders.sum;
9117 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9118 /* compute detailed per-chain stats */
9119 struct stats hdr_loads, hdr_gets;
9120 double v_looks, v_loads, v_gets;
9122 /* initialize stats with data from first element in chain */
9123 vp = queue_First(head, Volume);
9124 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9125 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9126 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9127 ch_gets.min = ch_gets.max = v_looks;
9128 hdr_loads.min = hdr_loads.max = v_loads;
9129 hdr_gets.min = hdr_gets.max = v_gets;
9130 hdr_loads.sum = hdr_gets.sum = 0;
9132 vp = queue_Next(vp, Volume);
9134 /* pull in stats from remaining elements in chain */
9135 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9136 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9137 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9138 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9140 hdr_loads.sum += v_loads;
9141 hdr_gets.sum += v_gets;
9143 if (v_looks < ch_gets.min)
9144 ch_gets.min = v_looks;
9145 else if (v_looks > ch_gets.max)
9146 ch_gets.max = v_looks;
9148 if (v_loads < hdr_loads.min)
9149 hdr_loads.min = v_loads;
9150 else if (v_loads > hdr_loads.max)
9151 hdr_loads.max = v_loads;
9153 if (v_gets < hdr_gets.min)
9154 hdr_gets.min = v_gets;
9155 else if (v_gets > hdr_gets.max)
9156 hdr_gets.max = v_gets;
9159 /* compute per-chain averages */
9160 ch_gets.avg = ch_gets.sum / ((double)head->len);
9161 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9162 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9164 /* dump per-chain stats */
9165 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9167 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9168 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9169 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9170 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9171 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9172 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9173 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9174 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9175 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9176 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9177 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9178 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9179 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9180 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9181 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9182 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9183 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9184 } else if (flags & VOL_STATS_PER_CHAIN) {
9185 /* dump simple per-chain stats */
9186 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9188 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9189 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9190 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9194 VHashEndExclusive_r(head);
9199 /* compute global averages */
9200 len.avg = len.sum / ((double)VolumeHashTable.Size);
9201 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9202 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9203 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9205 /* dump global stats */
9206 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9207 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9208 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9209 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9210 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9211 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9212 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9213 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9214 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9215 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9216 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9217 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9218 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9219 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9220 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9221 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9222 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9223 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9224 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9225 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9226 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9228 /* print extended disk related statistics */
9230 struct DiskPartition64 * diskP;
9231 afs_uint32 vol_count[VOLMAXPARTS+1];
9232 byte part_exists[VOLMAXPARTS+1];
9236 memset(vol_count, 0, sizeof(vol_count));
9237 memset(part_exists, 0, sizeof(part_exists));
9241 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9243 vol_count[id] = diskP->vol_list.len;
9244 part_exists[id] = 1;
9248 for (i = 0; i <= VOLMAXPARTS; i++) {
9249 if (part_exists[i]) {
9250 /* XXX while this is currently safe, it is a violation
9251 * of the VGetPartitionById_r interface contract. */
9252 diskP = VGetPartitionById_r(i, 0);
9254 Log("Partition %s has %d online volumes\n",
9255 VPartitionPath(diskP), diskP->vol_list.len);
9262 /* print extended VLRU statistics */
9263 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9264 afs_uint32 idx, cur, lpos;
9269 Log("VLRU State Dump:\n\n");
9271 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9272 Log("\t%s:\n", vlru_idx_to_string(idx));
9275 for (cur = vlru_stats.queue_info[idx].start;
9276 cur < vlru_stats.queue_info[idx].len;
9278 line[lpos++] = vlru_stats.vec[cur].volid;
9280 Log("\t\t%u, %u, %u, %u, %u,\n",
9281 line[0], line[1], line[2], line[3], line[4]);
9290 Log("\t\t%u, %u, %u, %u, %u\n",
9291 line[0], line[1], line[2], line[3], line[4]);
9296 free(vlru_stats.vec);
9303 VPrintExtendedCacheStats(int flags)
9306 VPrintExtendedCacheStats_r(flags);
9309 #endif /* AFS_DEMAND_ATTACH_FS */
9312 VCanScheduleSalvage(void)
9314 return vol_opts.canScheduleSalvage;
9320 return vol_opts.canUseFSSYNC;
9324 VCanUseSALVSYNC(void)
9326 return vol_opts.canUseSALVSYNC;
9330 VCanUnsafeAttach(void)
9332 return vol_opts.unsafe_attach;