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 opts->nLargeVnodes = opts->nSmallVnodes = 5;
462 opts->canScheduleSalvage = 0;
463 opts->canUseFSSYNC = 0;
464 opts->canUseSALVSYNC = 0;
466 opts->interrupt_rxcall = NULL;
467 opts->offline_timeout = -1;
468 opts->offline_shutdown_timeout = -1;
469 opts->usage_threshold = 128;
470 opts->usage_rate_limit = 5;
473 opts->unsafe_attach = 1;
474 #else /* !FAST_RESTART */
475 opts->unsafe_attach = 0;
476 #endif /* !FAST_RESTART */
480 opts->canScheduleSalvage = 1;
481 opts->canUseSALVSYNC = 1;
485 opts->canUseFSSYNC = 1;
489 opts->nLargeVnodes = 0;
490 opts->nSmallVnodes = 0;
492 opts->canScheduleSalvage = 1;
493 opts->canUseFSSYNC = 1;
503 * Set VInit to a certain value, and signal waiters.
505 * @param[in] value the value to set VInit to
510 VSetVInit_r(int value)
513 opr_cv_broadcast(&vol_vinit_cond);
517 VLogOfflineTimeout(const char *type, afs_int32 timeout)
523 Log("VInitVolumePackage: Interrupting clients accessing %s "
524 "immediately\n", type);
526 Log("VInitVolumePackage: Interrupting clients accessing %s "
527 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
532 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
534 int errors = 0; /* Number of errors while finding vice partitions. */
539 #ifndef AFS_PTHREAD_ENV
540 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
541 Log("VInitVolumePackage: offline_timeout and/or "
542 "offline_shutdown_timeout was specified, but the volume package "
543 "does not support these for LWP builds\n");
547 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
548 VLogOfflineTimeout("volumes going offline during shutdown",
549 opts->offline_shutdown_timeout);
551 memset(&VStats, 0, sizeof(VStats));
552 VStats.hdr_cache_size = 200;
554 VInitPartitionPackage();
556 #ifdef AFS_DEMAND_ATTACH_FS
557 if (programType == fileServer) {
560 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
562 opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
565 opr_mutex_init(&vol_glock_mutex);
566 opr_mutex_init(&vol_trans_mutex);
567 opr_cv_init(&vol_put_volume_cond);
568 opr_cv_init(&vol_sleep_cond);
569 opr_cv_init(&vol_init_attach_cond);
570 opr_cv_init(&vol_vinit_cond);
571 #ifndef AFS_PTHREAD_ENV
573 #endif /* AFS_PTHREAD_ENV */
574 Lock_Init(&vol_listLock);
576 srandom(time(0)); /* For VGetVolumeInfo */
578 #ifdef AFS_DEMAND_ATTACH_FS
579 opr_mutex_init(&vol_salvsync_mutex);
580 #endif /* AFS_DEMAND_ATTACH_FS */
582 /* Ok, we have done enough initialization that fileserver can
583 * start accepting calls, even though the volumes may not be
584 * available just yet.
588 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
589 if (programType == salvageServer) {
592 #endif /* AFS_DEMAND_ATTACH_FS */
593 #ifdef FSSYNC_BUILD_SERVER
594 if (programType == fileServer) {
598 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
599 if (VCanUseSALVSYNC()) {
600 /* establish a connection to the salvager at this point */
601 opr_Verify(VConnectSALV() != 0);
603 #endif /* AFS_DEMAND_ATTACH_FS */
605 if (opts->volcache > VStats.hdr_cache_size)
606 VStats.hdr_cache_size = opts->volcache;
607 VInitVolumeHeaderCache(VStats.hdr_cache_size);
609 VInitVnodes(vLarge, opts->nLargeVnodes);
610 VInitVnodes(vSmall, opts->nSmallVnodes);
613 errors = VAttachPartitions();
617 if (programType != fileServer) {
618 errors = VInitAttachVolumes(programType);
624 #ifdef FSSYNC_BUILD_CLIENT
625 if (VCanUseFSSYNC()) {
627 #ifdef AFS_DEMAND_ATTACH_FS
628 if (programType == salvageServer) {
629 Log("Unable to connect to file server; aborted\n");
632 #endif /* AFS_DEMAND_ATTACH_FS */
633 Log("Unable to connect to file server; will retry at need\n");
636 #endif /* FSSYNC_BUILD_CLIENT */
641 #if !defined(AFS_PTHREAD_ENV)
643 * Attach volumes in vice partitions
645 * @param[in] pt calling program type
648 * @note This is the original, non-threaded version of attach parititions.
650 * @post VInit state is 2
653 VInitAttachVolumes(ProgramType pt)
655 opr_Assert(VInit==1);
656 if (pt == fileServer) {
657 struct DiskPartition64 *diskP;
658 /* Attach all the volumes in this partition */
659 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
660 int nAttached = 0, nUnattached = 0;
661 opr_Verify(VAttachVolumesByPartition(diskP,
662 &nAttached, &nUnattached)
667 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
668 LWP_NoYieldSignal(VInitAttachVolumes);
672 #endif /* !AFS_PTHREAD_ENV */
674 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
676 * Attach volumes in vice partitions
678 * @param[in] pt calling program type
681 * @note Threaded version of attach parititions.
683 * @post VInit state is 2
686 VInitAttachVolumes(ProgramType pt)
688 opr_Assert(VInit==1);
689 if (pt == fileServer) {
690 struct DiskPartition64 *diskP;
691 struct vinitvolumepackage_thread_t params;
692 struct diskpartition_queue_t * dpq;
693 int i, threads, parts;
695 pthread_attr_t attrs;
697 opr_cv_init(¶ms.thread_done_cv);
699 params.n_threads_complete = 0;
701 /* create partition work queue */
702 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
703 dpq = malloc(sizeof(struct diskpartition_queue_t));
704 opr_Assert(dpq != NULL);
706 queue_Append(¶ms,dpq);
709 threads = min(parts, vol_attach_threads);
712 /* spawn off a bunch of initialization threads */
713 opr_Verify(pthread_attr_init(&attrs) == 0);
714 opr_Verify(pthread_attr_setdetachstate(&attrs,
715 PTHREAD_CREATE_DETACHED)
718 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
719 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
723 for (i=0; i < threads; i++) {
726 opr_Verify(pthread_create(&tid, &attrs,
727 &VInitVolumePackageThread,
729 AFS_SIGSET_RESTORE();
732 while(params.n_threads_complete < threads) {
733 VOL_CV_WAIT(¶ms.thread_done_cv);
737 opr_Verify(pthread_attr_destroy(&attrs) == 0);
739 /* if we're only going to run one init thread, don't bother creating
741 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
742 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
745 VInitVolumePackageThread(¶ms);
748 opr_cv_destroy(¶ms.thread_done_cv);
751 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
752 opr_cv_broadcast(&vol_init_attach_cond);
758 VInitVolumePackageThread(void * args) {
760 struct DiskPartition64 *diskP;
761 struct vinitvolumepackage_thread_t * params;
762 struct diskpartition_queue_t * dpq;
764 params = (vinitvolumepackage_thread_t *) args;
768 /* Attach all the volumes in this partition */
769 while (queue_IsNotEmpty(params)) {
770 int nAttached = 0, nUnattached = 0;
772 if (vinit_attach_abort) {
773 Log("Aborting initialization\n");
777 dpq = queue_First(params,diskpartition_queue_t);
783 opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
790 params->n_threads_complete++;
791 opr_cv_signal(¶ms->thread_done_cv);
795 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
797 #if defined(AFS_DEMAND_ATTACH_FS)
799 * Attach volumes in vice partitions
801 * @param[in] pt calling program type
804 * @note Threaded version of attach partitions.
806 * @post VInit state is 2
809 VInitAttachVolumes(ProgramType pt)
811 opr_Assert(VInit==1);
812 if (pt == fileServer) {
814 struct DiskPartition64 *diskP;
815 struct partition_queue pq;
816 struct volume_init_queue vq;
818 int i, threads, parts;
820 pthread_attr_t attrs;
822 /* create partition work queue */
825 opr_mutex_init(&pq.mutex);
826 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
827 struct diskpartition_queue_t *dp;
828 dp = malloc(sizeof(struct diskpartition_queue_t));
829 opr_Assert(dp != NULL);
831 queue_Append(&pq, dp);
834 /* number of worker threads; at least one, not to exceed the number of partitions */
835 threads = min(parts, vol_attach_threads);
837 /* create volume work queue */
840 opr_mutex_init(&vq.mutex);
842 opr_Verify(pthread_attr_init(&attrs) == 0);
843 opr_Verify(pthread_attr_setdetachstate(&attrs,
844 PTHREAD_CREATE_DETACHED) == 0);
846 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
847 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
850 /* create threads to scan disk partitions. */
851 for (i=0; i < threads; i++) {
852 struct vinitvolumepackage_thread_param *params;
855 params = malloc(sizeof(struct vinitvolumepackage_thread_param));
859 params->nthreads = threads;
860 params->thread = i+1;
863 opr_Verify(pthread_create(&tid, &attrs,
864 &VInitVolumePackageThread,
865 (void*)params) == 0);
866 AFS_SIGSET_RESTORE();
869 VInitPreAttachVolumes(threads, &vq);
871 opr_Verify(pthread_attr_destroy(&attrs) == 0);
872 opr_cv_destroy(&pq.cv);
873 opr_mutex_destroy(&pq.mutex);
874 opr_cv_destroy(&vq.cv);
875 opr_mutex_destroy(&vq.mutex);
879 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
880 opr_cv_broadcast(&vol_init_attach_cond);
887 * Volume package initialization worker thread. Scan partitions for volume
888 * header files. Gather batches of volume ids and dispatch them to
889 * the main thread to be preattached. The volume preattachement is done
890 * in the main thread to avoid global volume lock contention.
893 VInitVolumePackageThread(void *args)
895 struct vinitvolumepackage_thread_param *params;
896 struct DiskPartition64 *partition;
897 struct partition_queue *pq;
898 struct volume_init_queue *vq;
899 struct volume_init_batch *vb;
902 params = (struct vinitvolumepackage_thread_param *)args;
908 vb = malloc(sizeof(struct volume_init_batch));
910 vb->thread = params->thread;
914 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
915 while((partition = VInitNextPartition(pq))) {
919 Log("Partition %s: pre-attaching volumes\n", partition->name);
920 dirp = opendir(VPartitionPath(partition));
922 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
925 while ((vid = VInitNextVolumeId(dirp))) {
926 Volume *vp = calloc(1, sizeof(Volume));
928 vp->device = partition->device;
929 vp->partition = partition;
931 queue_Init(&vp->vnode_list);
932 queue_Init(&vp->rx_call_list);
933 opr_cv_init(&V_attachCV(vp));
935 vb->batch[vb->size++] = vp;
936 if (vb->size == VINIT_BATCH_MAX_SIZE) {
937 opr_mutex_enter(&vq->mutex);
938 queue_Append(vq, vb);
939 opr_cv_broadcast(&vq->cv);
940 opr_mutex_exit(&vq->mutex);
942 vb = malloc(sizeof(struct volume_init_batch));
944 vb->thread = params->thread;
953 opr_mutex_enter(&vq->mutex);
954 queue_Append(vq, vb);
955 opr_cv_broadcast(&vq->cv);
956 opr_mutex_exit(&vq->mutex);
958 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
964 * Read next element from the pre-populated partition list.
966 static struct DiskPartition64*
967 VInitNextPartition(struct partition_queue *pq)
969 struct DiskPartition64 *partition;
970 struct diskpartition_queue_t *dp; /* queue element */
972 if (vinit_attach_abort) {
973 Log("Aborting volume preattach thread.\n");
977 /* get next partition to scan */
978 opr_mutex_enter(&pq->mutex);
979 if (queue_IsEmpty(pq)) {
980 opr_mutex_exit(&pq->mutex);
983 dp = queue_First(pq, diskpartition_queue_t);
985 opr_mutex_exit(&pq->mutex);
988 opr_Assert(dp->diskP);
990 partition = dp->diskP;
996 * Find next volume id on the partition.
999 VInitNextVolumeId(DIR *dirp)
1005 while((d = readdir(dirp))) {
1006 if (vinit_attach_abort) {
1007 Log("Aborting volume preattach thread.\n");
1010 ext = strrchr(d->d_name, '.');
1011 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1012 vid = VolumeNumber(d->d_name);
1016 Log("Warning: bogus volume header file: %s\n", d->d_name);
1023 * Preattach volumes in batches to avoid lock contention.
1026 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1028 struct volume_init_batch *vb;
1032 /* dequeue next volume */
1033 opr_mutex_enter(&vq->mutex);
1034 if (queue_IsEmpty(vq)) {
1035 opr_cv_wait(&vq->cv, &vq->mutex);
1037 vb = queue_First(vq, volume_init_batch);
1039 opr_mutex_exit(&vq->mutex);
1043 for (i = 0; i<vb->size; i++) {
1049 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1051 Log("Error looking up volume, code=%d\n", ec);
1054 Log("Warning: Duplicate volume id %" AFS_VOLID_FMT " detected.\n", afs_printable_VolumeId_lu(vp->hashid));
1057 /* put pre-attached volume onto the hash table
1058 * and bring it up to the pre-attached state */
1059 AddVolumeToHashTable(vp, vp->hashid);
1060 AddVolumeToVByPList_r(vp);
1061 VLRU_Init_Node_r(vp);
1062 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1075 #endif /* AFS_DEMAND_ATTACH_FS */
1077 #if !defined(AFS_DEMAND_ATTACH_FS)
1079 * attach all volumes on a given disk partition
1082 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1088 Log("Partition %s: attaching volumes\n", diskP->name);
1089 dirp = opendir(VPartitionPath(diskP));
1091 Log("opendir on Partition %s failed!\n", diskP->name);
1095 while ((dp = readdir(dirp))) {
1097 p = strrchr(dp->d_name, '.');
1099 if (vinit_attach_abort) {
1100 Log("Partition %s: abort attach volumes\n", diskP->name);
1104 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1107 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1109 (*(vp ? nAttached : nUnattached))++;
1110 if (error == VOFFLINE)
1111 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1112 else if (GetLogLevel() >= 5) {
1113 Log("Partition %s: attached volume %d (%s)\n",
1114 diskP->name, VolumeNumber(dp->d_name),
1123 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1128 #endif /* !AFS_DEMAND_ATTACH_FS */
1130 /***************************************************/
1131 /* Shutdown routines */
1132 /***************************************************/
1136 * highly multithreaded volume package shutdown
1138 * with the demand attach fileserver extensions,
1139 * VShutdown has been modified to be multithreaded.
1140 * In order to achieve optimal use of many threads,
1141 * the shutdown code involves one control thread and
1142 * n shutdown worker threads. The control thread
1143 * periodically examines the number of volumes available
1144 * for shutdown on each partition, and produces a worker
1145 * thread allocation schedule. The idea is to eliminate
1146 * redundant scheduling computation on the workers by
1147 * having a single master scheduler.
1149 * The scheduler's objectives are:
1151 * each partition with volumes remaining gets allocated
1152 * at least 1 thread (assuming sufficient threads)
1154 * threads are allocated proportional to the number of
1155 * volumes remaining to be offlined. This ensures that
1156 * the OS I/O scheduler has many requests to elevator
1157 * seek on partitions that will (presumably) take the
1158 * longest amount of time (from now) to finish shutdown
1159 * (3) keep threads busy
1160 * when there are extra threads, they are assigned to
1161 * partitions using a simple round-robin algorithm
1163 * In the future, we may wish to add the ability to adapt
1164 * to the relative performance patterns of each disk
1169 * multi-step shutdown process
1171 * demand attach shutdown is a four-step process. Each
1172 * shutdown "pass" shuts down increasingly more difficult
1173 * volumes. The main purpose is to achieve better cache
1174 * utilization during shutdown.
1177 * shutdown volumes in the unattached, pre-attached
1180 * shutdown attached volumes with cached volume headers
1182 * shutdown all volumes in non-exclusive states
1184 * shutdown all remaining volumes
1187 #ifdef AFS_DEMAND_ATTACH_FS
1193 struct DiskPartition64 * diskP;
1194 struct diskpartition_queue_t * dpq;
1195 vshutdown_thread_t params;
1197 pthread_attr_t attrs;
1199 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1202 Log("VShutdown: aborting attach volumes\n");
1203 vinit_attach_abort = 1;
1204 VOL_CV_WAIT(&vol_init_attach_cond);
1207 for (params.n_parts=0, diskP = DiskPartitionList;
1208 diskP; diskP = diskP->next, params.n_parts++);
1210 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1211 params.n_parts, params.n_parts > 1 ? "s" : "");
1213 vol_shutting_down = 1;
1215 if (vol_attach_threads > 1) {
1216 /* prepare for parallel shutdown */
1217 params.n_threads = vol_attach_threads;
1218 opr_mutex_init(¶ms.lock);
1219 opr_cv_init(¶ms.cv);
1220 opr_cv_init(¶ms.master_cv);
1221 opr_Verify(pthread_attr_init(&attrs) == 0);
1222 opr_Verify(pthread_attr_setdetachstate(&attrs,
1223 PTHREAD_CREATE_DETACHED) == 0);
1224 queue_Init(¶ms);
1226 /* setup the basic partition information structures for
1227 * parallel shutdown */
1228 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1230 struct rx_queue * qp, * nqp;
1234 VVByPListWait_r(diskP);
1235 VVByPListBeginExclusive_r(diskP);
1238 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1239 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1243 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1244 VPartitionPath(diskP), count);
1247 /* build up the pass 0 shutdown work queue */
1248 dpq = malloc(sizeof(struct diskpartition_queue_t));
1249 opr_Assert(dpq != NULL);
1251 queue_Prepend(¶ms, dpq);
1253 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1256 Log("VShutdown: beginning parallel fileserver shutdown\n");
1257 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1258 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1260 /* do pass 0 shutdown */
1261 opr_mutex_enter(¶ms.lock);
1262 for (i=0; i < params.n_threads; i++) {
1263 opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1267 /* wait for all the pass 0 shutdowns to complete */
1268 while (params.n_threads_complete < params.n_threads) {
1269 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1271 params.n_threads_complete = 0;
1273 opr_cv_broadcast(¶ms.cv);
1274 opr_mutex_exit(¶ms.lock);
1276 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1277 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1279 /* run the parallel shutdown scheduler. it will drop the glock internally */
1280 ShutdownController(¶ms);
1282 /* wait for all the workers to finish pass 3 and terminate */
1283 while (params.pass < 4) {
1284 VOL_CV_WAIT(¶ms.cv);
1287 opr_Verify(pthread_attr_destroy(&attrs) == 0);
1288 opr_cv_destroy(¶ms.cv);
1289 opr_cv_destroy(¶ms.master_cv);
1290 opr_mutex_destroy(¶ms.lock);
1292 /* drop the VByPList exclusive reservations */
1293 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1294 VVByPListEndExclusive_r(diskP);
1295 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1296 VPartitionPath(diskP),
1297 params.stats[0][diskP->index],
1298 params.stats[1][diskP->index],
1299 params.stats[2][diskP->index],
1300 params.stats[3][diskP->index]);
1303 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1305 /* if we're only going to run one shutdown thread, don't bother creating
1307 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1309 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1310 VShutdownByPartition_r(diskP);
1314 Log("VShutdown: complete.\n");
1317 #else /* AFS_DEMAND_ATTACH_FS */
1327 Log("VShutdown: aborting attach volumes\n");
1328 vinit_attach_abort = 1;
1329 #ifdef AFS_PTHREAD_ENV
1330 VOL_CV_WAIT(&vol_init_attach_cond);
1332 LWP_WaitProcess(VInitAttachVolumes);
1333 #endif /* AFS_PTHREAD_ENV */
1336 Log("VShutdown: shutting down on-line volumes...\n");
1337 vol_shutting_down = 1;
1338 for (i = 0; i < VolumeHashTable.Size; i++) {
1339 /* try to hold first volume in the hash table */
1340 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1343 if (GetLogLevel() >= 5)
1344 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1345 afs_printable_VolumeId_lu(vp->hashid));
1347 /* next, take the volume offline (drops reference count) */
1348 VOffline_r(vp, "File server was shut down");
1352 Log("VShutdown: complete.\n");
1354 #endif /* AFS_DEMAND_ATTACH_FS */
1360 opr_Assert(VInit>0);
1367 * stop new activity (e.g. SALVSYNC) from occurring
1369 * Use this to make the volume package less busy; for example, during
1370 * shutdown. This doesn't actually shutdown/detach anything in the
1371 * volume package, but prevents certain processes from ocurring. For
1372 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1373 * could also use this to prevent new volume attachment, or prevent
1374 * other programs from checking out volumes, etc.
1379 #ifdef AFS_DEMAND_ATTACH_FS
1380 /* make sure we don't try to contact the salvageserver, since it may
1381 * not be around anymore */
1382 vol_disallow_salvsync = 1;
1386 #ifdef AFS_DEMAND_ATTACH_FS
1389 * shutdown control thread
1392 ShutdownController(vshutdown_thread_t * params)
1395 struct DiskPartition64 * diskP;
1397 vshutdown_thread_t shadow;
1399 ShutdownCreateSchedule(params);
1401 while ((params->pass < 4) &&
1402 (params->n_threads_complete < params->n_threads)) {
1403 /* recompute schedule once per second */
1405 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1409 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1410 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1411 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1412 shadow.n_threads_complete, shadow.n_parts_done_pass);
1413 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1415 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1417 diskP->vol_list.len,
1418 shadow.part_thread_target[id],
1419 shadow.part_done_pass[id],
1420 shadow.part_pass_head[id]);
1426 ShutdownCreateSchedule(params);
1430 /* create the shutdown thread work schedule.
1431 * this scheduler tries to implement fairness
1432 * by allocating at least 1 thread to each
1433 * partition with volumes to be shutdown,
1434 * and then it attempts to allocate remaining
1435 * threads based upon the amount of work left
1438 ShutdownCreateSchedule(vshutdown_thread_t * params)
1440 struct DiskPartition64 * diskP;
1441 int sum, thr_workload, thr_left;
1442 int part_residue[VOLMAXPARTS+1];
1445 /* compute the total number of outstanding volumes */
1447 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1448 sum += diskP->vol_list.len;
1451 params->schedule_version++;
1452 params->vol_remaining = sum;
1457 /* compute average per-thread workload */
1458 thr_workload = sum / params->n_threads;
1459 if (sum % params->n_threads)
1462 thr_left = params->n_threads;
1463 memset(&part_residue, 0, sizeof(part_residue));
1465 /* for fairness, give every partition with volumes remaining
1466 * at least one thread */
1467 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1469 if (diskP->vol_list.len) {
1470 params->part_thread_target[id] = 1;
1473 params->part_thread_target[id] = 0;
1477 if (thr_left && thr_workload) {
1478 /* compute length-weighted workloads */
1481 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1483 delta = (diskP->vol_list.len / thr_workload) -
1484 params->part_thread_target[id];
1488 if (delta < thr_left) {
1489 params->part_thread_target[id] += delta;
1492 params->part_thread_target[id] += thr_left;
1500 /* try to assign any leftover threads to partitions that
1501 * had volume lengths closer to needing thread_target+1 */
1502 int max_residue, max_id = 0;
1504 /* compute the residues */
1505 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1507 part_residue[id] = diskP->vol_list.len -
1508 (params->part_thread_target[id] * thr_workload);
1511 /* now try to allocate remaining threads to partitions with the
1512 * highest residues */
1515 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1517 if (part_residue[id] > max_residue) {
1518 max_residue = part_residue[id];
1527 params->part_thread_target[max_id]++;
1529 part_residue[max_id] = 0;
1534 /* punt and give any remaining threads equally to each partition */
1536 if (thr_left >= params->n_parts) {
1537 alloc = thr_left / params->n_parts;
1538 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1540 params->part_thread_target[id] += alloc;
1545 /* finish off the last of the threads */
1546 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1548 params->part_thread_target[id]++;
1554 /* worker thread for parallel shutdown */
1556 VShutdownThread(void * args)
1558 vshutdown_thread_t * params;
1559 int found, pass, schedule_version_save, count;
1560 struct DiskPartition64 *diskP;
1561 struct diskpartition_queue_t * dpq;
1564 params = (vshutdown_thread_t *) args;
1566 /* acquire the shutdown pass 0 lock */
1567 opr_mutex_enter(¶ms->lock);
1569 /* if there's still pass 0 work to be done,
1570 * get a work entry, and do a pass 0 shutdown */
1571 if (queue_IsNotEmpty(params)) {
1572 dpq = queue_First(params, diskpartition_queue_t);
1574 opr_mutex_exit(¶ms->lock);
1580 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1582 params->stats[0][diskP->index] = count;
1583 opr_mutex_enter(¶ms->lock);
1586 params->n_threads_complete++;
1587 if (params->n_threads_complete == params->n_threads) {
1588 /* notify control thread that all workers have completed pass 0 */
1589 opr_cv_signal(¶ms->master_cv);
1591 while (params->pass == 0) {
1592 opr_cv_wait(¶ms->cv, ¶ms->lock);
1596 opr_mutex_exit(¶ms->lock);
1599 pass = params->pass;
1600 opr_Assert(pass > 0);
1602 /* now escalate through the more complicated shutdowns */
1604 schedule_version_save = params->schedule_version;
1606 /* find a disk partition to work on */
1607 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1609 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1610 params->part_thread_target[id]--;
1617 /* hmm. for some reason the controller thread couldn't find anything for
1618 * us to do. let's see if there's anything we can do */
1619 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1621 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1624 } else if (!params->part_done_pass[id]) {
1625 params->part_done_pass[id] = 1;
1626 params->n_parts_done_pass++;
1628 Log("VShutdown: done shutting down volumes on partition %s.\n",
1629 VPartitionPath(diskP));
1635 /* do work on this partition until either the controller
1636 * creates a new schedule, or we run out of things to do
1637 * on this partition */
1640 while (!params->part_done_pass[id] &&
1641 (schedule_version_save == params->schedule_version)) {
1642 /* ShutdownVolumeWalk_r will drop the glock internally */
1643 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1644 if (!params->part_done_pass[id]) {
1645 params->part_done_pass[id] = 1;
1646 params->n_parts_done_pass++;
1648 Log("VShutdown: done shutting down volumes on partition %s.\n",
1649 VPartitionPath(diskP));
1657 params->stats[pass][id] += count;
1659 /* ok, everyone is done this pass, proceed */
1662 params->n_threads_complete++;
1663 while (params->pass == pass) {
1664 if (params->n_threads_complete == params->n_threads) {
1665 /* we are the last thread to complete, so we will
1666 * reinitialize worker pool state for the next pass */
1667 params->n_threads_complete = 0;
1668 params->n_parts_done_pass = 0;
1670 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1672 params->part_done_pass[id] = 0;
1673 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1676 /* compute a new thread schedule before releasing all the workers */
1677 ShutdownCreateSchedule(params);
1679 /* wake up all the workers */
1680 opr_cv_broadcast(¶ms->cv);
1683 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1684 pass, params->n_threads, params->n_parts);
1687 VOL_CV_WAIT(¶ms->cv);
1690 pass = params->pass;
1704 /* shut down all volumes on a given disk partition
1706 * note that this function will not allow mp-fast
1707 * shutdown of a partition */
1709 VShutdownByPartition_r(struct DiskPartition64 * dp)
1715 /* wait for other exclusive ops to finish */
1716 VVByPListWait_r(dp);
1718 /* begin exclusive access */
1719 VVByPListBeginExclusive_r(dp);
1721 /* pick the low-hanging fruit first,
1722 * then do the complicated ones last
1723 * (has the advantage of keeping
1724 * in-use volumes up until the bitter end) */
1725 for (pass = 0, total=0; pass < 4; pass++) {
1726 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1727 total += pass_stats[pass];
1730 /* end exclusive access */
1731 VVByPListEndExclusive_r(dp);
1733 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1734 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1739 /* internal shutdown functionality
1741 * for multi-pass shutdown:
1742 * 0 to only "shutdown" {pre,un}attached and error state volumes
1743 * 1 to also shutdown attached volumes w/ volume header loaded
1744 * 2 to also shutdown attached volumes w/o volume header loaded
1745 * 3 to also shutdown exclusive state volumes
1747 * caller MUST hold exclusive access on the hash chain
1748 * because we drop vol_glock_mutex internally
1750 * this function is reentrant for passes 1--3
1751 * (e.g. multiple threads can cooperate to
1752 * shutdown a partition mp-fast)
1754 * pass 0 is not scaleable because the volume state data is
1755 * synchronized by vol_glock mutex, and the locking overhead
1756 * is too high to drop the lock long enough to do linked list
1760 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1762 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1764 const char *pass_strs[4] = {"{un/pre}attached vols", "vols w/ vol header loaded", "vols w/o vol header loaded", "vols with exclusive state"};
1766 while (ShutdownVolumeWalk_r(dp, pass, &q)) {
1769 Log("VShutdownByPartition: ... shut down %d volumes on %s in pass %d (%s)\n", i, VPartitionPath(dp), pass, pass_strs[pass]);
1776 /* conditionally shutdown one volume on partition dp
1777 * returns 1 if a volume was shutdown in this pass,
1780 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1781 struct rx_queue ** idx)
1783 struct rx_queue *qp, *nqp;
1788 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1789 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1793 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1794 (V_attachState(vp) != VOL_STATE_ERROR) &&
1795 (V_attachState(vp) != VOL_STATE_DELETED) &&
1796 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1801 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1802 (vp->header == NULL)) {
1807 if (VIsExclusiveState(V_attachState(vp))) {
1813 DeleteVolumeFromVByPList_r(vp);
1814 VShutdownVolume_r(vp);
1824 * shutdown a specific volume
1826 /* caller MUST NOT hold a heavyweight ref on vp */
1828 VShutdownVolume_r(Volume * vp)
1832 VCreateReservation_r(vp);
1834 if (GetLogLevel() >= 5) {
1835 Log("VShutdownVolume_r: vid=%" AFS_VOLID_FMT ", device=%d, state=%u\n",
1836 afs_printable_VolumeId_lu(vp->hashid), vp->partition->device,
1837 (unsigned int) V_attachState(vp));
1840 /* wait for other blocking ops to finish */
1841 VWaitExclusiveState_r(vp);
1843 opr_Assert(VIsValidState(V_attachState(vp)));
1845 switch(V_attachState(vp)) {
1846 case VOL_STATE_SALVAGING:
1847 /* Leave salvaging volumes alone. Any in-progress salvages will
1848 * continue working after viced shuts down. This is intentional.
1851 case VOL_STATE_PREATTACHED:
1852 case VOL_STATE_ERROR:
1853 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1854 case VOL_STATE_UNATTACHED:
1855 case VOL_STATE_DELETED:
1857 case VOL_STATE_GOING_OFFLINE:
1858 case VOL_STATE_SHUTTING_DOWN:
1859 case VOL_STATE_ATTACHED:
1862 if (GetLogLevel() >= 5)
1863 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1864 afs_printable_VolumeId_lu(vp->hashid));
1866 /* take the volume offline (drops reference count) */
1867 VOffline_r(vp, "File server was shut down");
1874 VCancelReservation_r(vp);
1878 #endif /* AFS_DEMAND_ATTACH_FS */
1881 /***************************************************/
1882 /* Header I/O routines */
1883 /***************************************************/
1886 HeaderName(bit32 magic)
1889 case VOLUMEINFOMAGIC:
1890 return "volume info";
1891 case SMALLINDEXMAGIC:
1892 return "small index";
1893 case LARGEINDEXMAGIC:
1894 return "large index";
1895 case LINKTABLEMAGIC:
1896 return "link table";
1901 /* open a descriptor for the inode (h),
1902 * read in an on-disk structure into buffer (to) of size (size),
1903 * verify versionstamp in structure has magic (magic) and
1904 * optionally verify version (version) if (version) is nonzero
1907 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1910 struct versionStamp *vsn;
1912 afs_sfsize_t nbytes;
1917 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1925 Log("ReadHeader: Failed to open %s header file "
1926 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1927 PrintInode(stmp, h->ih_ino), errno);
1932 vsn = (struct versionStamp *)to;
1933 nbytes = FDH_PREAD(fdP, to, size, 0);
1935 Log("ReadHeader: Failed to read %s header file "
1936 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1937 PrintInode(stmp, h->ih_ino), errno);
1939 FDH_REALLYCLOSE(fdP);
1942 if (nbytes != size) {
1943 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1944 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%d, read=%d\n",
1945 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1946 PrintInode(stmp, h->ih_ino), size, (int)nbytes);
1948 FDH_REALLYCLOSE(fdP);
1951 if (vsn->magic != magic) {
1952 Log("ReadHeader: Incorrect magic for %s header file "
1953 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=0x%x, read=0x%x\n",
1954 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1955 PrintInode(stmp, h->ih_ino), magic, vsn->magic);
1957 FDH_REALLYCLOSE(fdP);
1963 /* Check is conditional, in case caller wants to inspect version himself */
1964 if (version && vsn->version != version) {
1965 Log("ReadHeader: Incorrect version for %s header file "
1966 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%x, read=%x\n",
1967 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid), PrintInode(stmp, h->ih_ino),
1968 version, vsn->version);
1974 WriteVolumeHeader_r(Error * ec, Volume * vp)
1976 IHandle_t *h = V_diskDataHandle(vp);
1986 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1987 != sizeof(V_disk(vp))) {
1989 FDH_REALLYCLOSE(fdP);
1995 /* VolumeHeaderToDisk
1996 * Allows for storing 64 bit inode numbers in on-disk volume header
1999 /* convert in-memory representation of a volume header to the
2000 * on-disk representation of a volume header */
2002 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2005 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2006 dh->stamp = h->stamp;
2008 dh->parent = h->parent;
2010 #ifdef AFS_64BIT_IOPS_ENV
2011 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2012 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2013 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2014 dh->smallVnodeIndex_hi =
2015 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2016 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2017 dh->largeVnodeIndex_hi =
2018 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2019 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2020 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2022 dh->volumeInfo_lo = h->volumeInfo;
2023 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2024 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2025 dh->linkTable_lo = h->linkTable;
2029 /* DiskToVolumeHeader
2030 * Converts an on-disk representation of a volume header to
2031 * the in-memory representation of a volume header.
2033 * Makes the assumption that AFS has *always*
2034 * zero'd the volume header file so that high parts of inode
2035 * numbers are 0 in older (SGI EFS) volume header files.
2038 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2040 memset(h, 0, sizeof(VolumeHeader_t));
2041 h->stamp = dh->stamp;
2043 h->parent = dh->parent;
2045 #ifdef AFS_64BIT_IOPS_ENV
2047 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2049 h->smallVnodeIndex =
2050 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2051 smallVnodeIndex_hi << 32);
2053 h->largeVnodeIndex =
2054 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2055 largeVnodeIndex_hi << 32);
2057 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2059 h->volumeInfo = dh->volumeInfo_lo;
2060 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2061 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2062 h->linkTable = dh->linkTable_lo;
2067 /***************************************************/
2068 /* Volume Attachment routines */
2069 /***************************************************/
2071 #ifdef AFS_DEMAND_ATTACH_FS
2073 * pre-attach a volume given its path.
2075 * @param[out] ec outbound error code
2076 * @param[in] partition partition path string
2077 * @param[in] name volume id string
2079 * @return volume object pointer
2081 * @note A pre-attached volume will only have its partition
2082 * and hashid fields initialized. At first call to
2083 * VGetVolume, the volume will be fully attached.
2087 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2091 vp = VPreAttachVolumeByName_r(ec, partition, name);
2097 * pre-attach a volume given its path.
2099 * @param[out] ec outbound error code
2100 * @param[in] partition path to vice partition
2101 * @param[in] name volume id string
2103 * @return volume object pointer
2105 * @pre VOL_LOCK held
2107 * @internal volume package internal use only.
2110 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2112 return VPreAttachVolumeById_r(ec,
2114 VolumeNumber(name));
2118 * pre-attach a volume given its path and numeric volume id.
2120 * @param[out] ec error code return
2121 * @param[in] partition path to vice partition
2122 * @param[in] volumeId numeric volume id
2124 * @return volume object pointer
2126 * @pre VOL_LOCK held
2128 * @internal volume package internal use only.
2131 VPreAttachVolumeById_r(Error * ec,
2136 struct DiskPartition64 *partp;
2140 opr_Assert(programType == fileServer);
2142 if (!(partp = VGetPartition_r(partition, 0))) {
2144 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2148 /* ensure that any vp we pass to VPreAttachVolumeByVp_r
2149 * is NOT in exclusive state.
2152 vp = VLookupVolume_r(ec, volumeId, NULL);
2158 if (vp && VIsExclusiveState(V_attachState(vp))) {
2159 VCreateReservation_r(vp);
2160 VWaitExclusiveState_r(vp);
2161 VCancelReservation_r(vp);
2163 goto retry; /* look up volume again */
2166 /* vp == NULL or vp not exclusive both OK */
2168 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2172 * preattach a volume.
2174 * @param[out] ec outbound error code
2175 * @param[in] partp pointer to partition object
2176 * @param[in] vp pointer to volume object
2177 * @param[in] vid volume id
2179 * @return volume object pointer
2181 * @pre VOL_LOCK is held.
2183 * @pre vp (if specified) must not be in exclusive state.
2185 * @warning Returned volume object pointer does not have to
2186 * equal the pointer passed in as argument vp. There
2187 * are potential race conditions which can result in
2188 * the pointers having different values. It is up to
2189 * the caller to make sure that references are handled
2190 * properly in this case.
2192 * @note If there is already a volume object registered with
2193 * the same volume id, its pointer MUST be passed as
2194 * argument vp. Failure to do so will result in a silent
2195 * failure to preattach.
2197 * @internal volume package internal use only.
2200 VPreAttachVolumeByVp_r(Error * ec,
2201 struct DiskPartition64 * partp,
2209 /* don't proceed unless it's safe */
2211 opr_Assert(!VIsExclusiveState(V_attachState(vp)));
2214 /* check to see if pre-attach already happened */
2216 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2217 (V_attachState(vp) != VOL_STATE_DELETED) &&
2218 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2219 !VIsErrorState(V_attachState(vp))) {
2221 * pre-attach is a no-op in all but the following cases:
2223 * - volume is unattached
2224 * - volume is in an error state
2225 * - volume is pre-attached
2227 Log("VPreattachVolumeByVp_r: volume %" AFS_VOLID_FMT " not in quiescent state (state %u flags 0x%x)\n",
2228 afs_printable_VolumeId_lu(vid), V_attachState(vp),
2232 /* we're re-attaching a volume; clear out some old state */
2233 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2235 if (V_partition(vp) != partp) {
2236 /* XXX potential race */
2237 DeleteVolumeFromVByPList_r(vp);
2240 /* if we need to allocate a new Volume struct,
2241 * go ahead and drop the vol glock, otherwise
2242 * do the basic setup synchronised, as it's
2243 * probably not worth dropping the lock */
2246 /* allocate the volume structure */
2247 vp = nvp = calloc(1, sizeof(Volume));
2248 opr_Assert(vp != NULL);
2249 queue_Init(&vp->vnode_list);
2250 queue_Init(&vp->rx_call_list);
2251 opr_cv_init(&V_attachCV(vp));
2254 /* link the volume with its associated vice partition */
2255 vp->device = partp->device;
2256 vp->partition = partp;
2259 vp->specialStatus = 0;
2261 /* if we dropped the lock, reacquire the lock,
2262 * check for pre-attach races, and then add
2263 * the volume to the hash table */
2266 nvp = VLookupVolume_r(ec, vid, NULL);
2271 } else if (nvp) { /* race detected */
2276 /* hack to make up for VChangeState_r() decrementing
2277 * the old state counter */
2278 VStats.state_levels[0]++;
2282 /* put pre-attached volume onto the hash table
2283 * and bring it up to the pre-attached state */
2284 AddVolumeToHashTable(vp, vp->hashid);
2285 AddVolumeToVByPList_r(vp);
2286 VLRU_Init_Node_r(vp);
2287 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2289 if (GetLogLevel() >= 5)
2290 Log("VPreAttachVolumeByVp_r: volume %" AFS_VOLID_FMT " pre-attached\n", afs_printable_VolumeId_lu(vp->hashid));
2298 #endif /* AFS_DEMAND_ATTACH_FS */
2300 /* Attach an existing volume, given its pathname, and return a
2301 pointer to the volume header information. The volume also
2302 normally goes online at this time. An offline volume
2303 must be reattached to make it go online */
2305 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2309 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2315 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2318 struct DiskPartition64 *partp;
2323 #ifdef AFS_DEMAND_ATTACH_FS
2324 VolumeStats stats_save;
2326 #endif /* AFS_DEMAND_ATTACH_FS */
2330 volumeId = VolumeNumber(name);
2332 if (!(partp = VGetPartition_r(partition, 0))) {
2334 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2338 if (VRequiresPartLock()) {
2339 opr_Assert(VInit == 3);
2340 VLockPartition_r(partition);
2341 } else if (programType == fileServer) {
2342 #ifdef AFS_DEMAND_ATTACH_FS
2343 /* lookup the volume in the hash table */
2344 vp = VLookupVolume_r(ec, volumeId, NULL);
2350 /* save any counters that are supposed to
2351 * be monotonically increasing over the
2352 * lifetime of the fileserver */
2353 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2355 memset(&stats_save, 0, sizeof(VolumeStats));
2358 /* if there's something in the hash table, and it's not
2359 * in the pre-attach state, then we may need to detach
2360 * it before proceeding */
2361 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2362 VCreateReservation_r(vp);
2363 VWaitExclusiveState_r(vp);
2365 /* at this point state must be one of:
2375 if (vp->specialStatus == VBUSY)
2378 /* if it's already attached, see if we can return it */
2379 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2380 VGetVolumeByVp_r(ec, vp);
2381 if (V_inUse(vp) == fileServer) {
2382 VCancelReservation_r(vp);
2386 /* otherwise, we need to detach, and attempt to re-attach */
2387 VDetachVolume_r(ec, vp);
2389 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2392 /* if it isn't fully attached, delete from the hash tables,
2393 and let the refcounter handle the rest */
2394 DeleteVolumeFromHashTable(vp);
2395 DeleteVolumeFromVByPList_r(vp);
2398 VCancelReservation_r(vp);
2402 /* pre-attach volume if it hasn't been done yet */
2404 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2405 (V_attachState(vp) == VOL_STATE_DELETED) ||
2406 (V_attachState(vp) == VOL_STATE_ERROR)) {
2408 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2414 opr_Assert(vp != NULL);
2416 /* handle pre-attach races
2418 * multiple threads can race to pre-attach a volume,
2419 * but we can't let them race beyond that
2421 * our solution is to let the first thread to bring
2422 * the volume into an exclusive state win; the other
2423 * threads just wait until it finishes bringing the
2424 * volume online, and then they do a vgetvolumebyvp
2426 if (svp && (svp != vp)) {
2427 /* wait for other exclusive ops to finish */
2428 VCreateReservation_r(vp);
2429 VWaitExclusiveState_r(vp);
2431 /* get a heavyweight ref, kill the lightweight ref, and return */
2432 VGetVolumeByVp_r(ec, vp);
2433 VCancelReservation_r(vp);
2437 /* at this point, we are chosen as the thread to do
2438 * demand attachment for this volume. all other threads
2439 * doing a getvolume on vp->hashid will block until we finish */
2441 /* make sure any old header cache entries are invalidated
2442 * before proceeding */
2443 FreeVolumeHeader(vp);
2445 VChangeState_r(vp, VOL_STATE_ATTACHING);
2447 /* restore any saved counters */
2448 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2449 #else /* AFS_DEMAND_ATTACH_FS */
2450 vp = VGetVolume_r(ec, volumeId);
2452 if (V_inUse(vp) == fileServer)
2454 if (vp->specialStatus == VBUSY)
2456 VDetachVolume_r(ec, vp);
2458 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2462 #endif /* AFS_DEMAND_ATTACH_FS */
2466 strcpy(path, VPartitionPath(partp));
2470 strcat(path, OS_DIRSEP);
2474 vp = (Volume *) calloc(1, sizeof(Volume));
2475 opr_Assert(vp != NULL);
2476 vp->hashid = volumeId;
2477 vp->device = partp->device;
2478 vp->partition = partp;
2479 queue_Init(&vp->vnode_list);
2480 queue_Init(&vp->rx_call_list);
2481 #ifdef AFS_DEMAND_ATTACH_FS
2482 opr_cv_init(&V_attachCV(vp));
2483 #endif /* AFS_DEMAND_ATTACH_FS */
2486 /* attach2 is entered without any locks, and returns
2487 * with vol_glock_mutex held */
2488 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2490 if (VCanUseFSSYNC() && vp) {
2491 #ifdef AFS_DEMAND_ATTACH_FS
2492 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2493 /* mark volume header as in use so that volser crashes lead to a
2494 * salvage attempt */
2495 VUpdateVolume_r(ec, vp, 0);
2497 /* for dafs, we should tell the fileserver, except for V_PEEK
2498 * where we know it is not necessary */
2499 if (mode == V_PEEK) {
2500 vp->needsPutBack = 0;
2502 vp->needsPutBack = VOL_PUTBACK;
2504 #else /* !AFS_DEMAND_ATTACH_FS */
2505 /* duplicate computation in fssync.c about whether the server
2506 * takes the volume offline or not. If the volume isn't
2507 * offline, we must not return it when we detach the volume,
2508 * or the server will abort */
2509 if (mode == V_READONLY || mode == V_PEEK
2510 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2511 vp->needsPutBack = 0;
2513 vp->needsPutBack = VOL_PUTBACK;
2514 #endif /* !AFS_DEMAND_ATTACH_FS */
2516 #ifdef FSSYNC_BUILD_CLIENT
2517 /* Only give back the vol to the fileserver if we checked it out; attach2
2518 * will set checkedOut only if we successfully checked it out from the
2520 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2522 #ifdef AFS_DEMAND_ATTACH_FS
2523 /* If we couldn't attach but we scheduled a salvage, we already
2524 * notified the fileserver; don't online it now */
2525 if (*ec != VSALVAGING)
2526 #endif /* AFS_DEMAND_ATTACH_FS */
2527 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2530 if (programType == fileServer && vp) {
2531 #ifdef AFS_DEMAND_ATTACH_FS
2533 * we can get here in cases where we don't "own"
2534 * the volume (e.g. volume owned by a utility).
2535 * short circuit around potential disk header races.
2537 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2541 VUpdateVolume_r(ec, vp, 0);
2543 Log("VAttachVolume: Error updating volume\n");
2548 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2549 #ifndef AFS_DEMAND_ATTACH_FS
2550 /* This is a hack: by temporarily setting the incore
2551 * dontSalvage flag ON, the volume will be put back on the
2552 * Update list (with dontSalvage OFF again). It will then
2553 * come back in N minutes with DONT_SALVAGE eventually
2554 * set. This is the way that volumes that have never had
2555 * it set get it set; or that volumes that have been
2556 * offline without DONT SALVAGE having been set also
2557 * eventually get it set */
2558 V_dontSalvage(vp) = DONT_SALVAGE;
2559 #endif /* !AFS_DEMAND_ATTACH_FS */
2560 VAddToVolumeUpdateList_r(ec, vp);
2562 Log("VAttachVolume: Error adding volume to update list\n");
2568 if (GetLogLevel() != 0)
2569 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n", afs_printable_VolumeId_lu(V_id(vp)),
2574 if (VRequiresPartLock()) {
2575 VUnlockPartition_r(partition);
2578 #ifdef AFS_DEMAND_ATTACH_FS
2579 /* attach failed; make sure we're in error state */
2580 if (vp && !VIsErrorState(V_attachState(vp))) {
2581 VChangeState_r(vp, VOL_STATE_ERROR);
2583 #endif /* AFS_DEMAND_ATTACH_FS */
2590 #ifdef AFS_DEMAND_ATTACH_FS
2591 /* VAttachVolumeByVp_r
2593 * finish attaching a volume that is
2594 * in a less than fully attached state
2596 /* caller MUST hold a ref count on vp */
2598 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2600 char name[VMAXPATHLEN];
2602 struct DiskPartition64 *partp;
2606 Volume * nvp = NULL;
2607 VolumeStats stats_save;
2611 /* volume utility should never call AttachByVp */
2612 opr_Assert(programType == fileServer);
2614 volumeId = vp->hashid;
2615 partp = vp->partition;
2616 VolumeExternalName_r(volumeId, name, sizeof(name));
2619 /* if another thread is performing a blocking op, wait */
2620 VWaitExclusiveState_r(vp);
2622 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2624 /* if it's already attached, see if we can return it */
2625 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2626 VGetVolumeByVp_r(ec, vp);
2627 if (V_inUse(vp) == fileServer) {
2630 if (vp->specialStatus == VBUSY)
2632 VDetachVolume_r(ec, vp);
2634 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2640 /* pre-attach volume if it hasn't been done yet */
2642 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2643 (V_attachState(vp) == VOL_STATE_DELETED) ||
2644 (V_attachState(vp) == VOL_STATE_ERROR)) {
2645 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2651 VCreateReservation_r(nvp);
2656 opr_Assert(vp != NULL);
2657 VChangeState_r(vp, VOL_STATE_ATTACHING);
2659 /* restore monotonically increasing stats */
2660 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2664 /* compute path to disk header */
2665 strcpy(path, VPartitionPath(partp));
2669 strcat(path, OS_DIRSEP);
2674 * NOTE: attach2 is entered without any locks, and returns
2675 * with vol_glock_mutex held */
2676 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2679 * the event that an error was encountered, or
2680 * the volume was not brought to an attached state
2681 * for any reason, skip to the end. We cannot
2682 * safely call VUpdateVolume unless we "own" it.
2686 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2690 VUpdateVolume_r(ec, vp, 0);
2692 Log("VAttachVolume: Error updating volume %" AFS_VOLID_FMT "\n",
2693 afs_printable_VolumeId_lu(vp->hashid));
2697 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2698 #ifndef AFS_DEMAND_ATTACH_FS
2699 /* This is a hack: by temporarily setting the incore
2700 * dontSalvage flag ON, the volume will be put back on the
2701 * Update list (with dontSalvage OFF again). It will then
2702 * come back in N minutes with DONT_SALVAGE eventually
2703 * set. This is the way that volumes that have never had
2704 * it set get it set; or that volumes that have been
2705 * offline without DONT SALVAGE having been set also
2706 * eventually get it set */
2707 V_dontSalvage(vp) = DONT_SALVAGE;
2708 #endif /* !AFS_DEMAND_ATTACH_FS */
2709 VAddToVolumeUpdateList_r(ec, vp);
2711 Log("VAttachVolume: Error adding volume %" AFS_VOLID_FMT " to update list\n",
2712 afs_printable_VolumeId_lu(vp->hashid));
2718 if (GetLogLevel() != 0)
2719 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n",
2720 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
2723 VCancelReservation_r(nvp);
2726 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2727 if (vp && !VIsErrorState(V_attachState(vp))) {
2728 VChangeState_r(vp, VOL_STATE_ERROR);
2737 * lock a volume on disk (non-blocking).
2739 * @param[in] vp The volume to lock
2740 * @param[in] locktype READ_LOCK or WRITE_LOCK
2742 * @return operation status
2743 * @retval 0 success, lock was obtained
2744 * @retval EBUSY a conflicting lock was held by another process
2745 * @retval EIO error acquiring lock
2747 * @pre If we're in the fileserver, vp is in an exclusive state
2749 * @pre vp is not already locked
2752 VLockVolumeNB(Volume *vp, int locktype)
2756 opr_Assert(programType != fileServer
2757 || VIsExclusiveState(V_attachState(vp)));
2758 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2760 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2762 V_attachFlags(vp) |= VOL_LOCKED;
2769 * unlock a volume on disk that was locked with VLockVolumeNB.
2771 * @param[in] vp volume to unlock
2773 * @pre If we're in the fileserver, vp is in an exclusive state
2775 * @pre vp has already been locked
2778 VUnlockVolume(Volume *vp)
2780 opr_Assert(programType != fileServer
2781 || VIsExclusiveState(V_attachState(vp)));
2782 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2784 VUnlockVolumeById(vp->hashid, vp->partition);
2786 V_attachFlags(vp) &= ~VOL_LOCKED;
2788 #endif /* AFS_DEMAND_ATTACH_FS */
2791 * read in a vol header, possibly lock the vol header, and possibly check out
2792 * the vol header from the fileserver, as part of volume attachment.
2794 * @param[out] ec error code
2795 * @param[in] vp volume pointer object
2796 * @param[in] partp disk partition object of the attaching partition
2797 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2799 * @param[in] peek 1 to just try to read in the volume header and make sure
2800 * we don't try to lock the vol, or check it out from
2801 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2803 * @param[out] acheckedOut If we successfully checked-out the volume from
2804 * the fileserver (if we needed to), this is set
2805 * to 1, otherwise it is untouched.
2807 * @note As part of DAFS volume attachment, the volume header may be either
2808 * read- or write-locked to ensure mutual exclusion of certain volume
2809 * operations. In some cases in order to determine whether we need to
2810 * read- or write-lock the header, we need to read in the header to see
2811 * if the volume is RW or not. So, if we read in the header under a
2812 * read-lock and determine that we actually need a write-lock on the
2813 * volume header, this function will drop the read lock, acquire a write
2814 * lock, and read the header in again.
2817 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2818 int mode, int peek, int *acheckedOut)
2820 struct VolumeDiskHeader diskHeader;
2821 struct VolumeHeader header;
2824 int lock_tries = 0, checkout_tries = 0;
2826 VolumeId volid = vp->hashid;
2827 #ifdef FSSYNC_BUILD_CLIENT
2828 int checkout, done_checkout = 0;
2829 #endif /* FSSYNC_BUILD_CLIENT */
2830 #ifdef AFS_DEMAND_ATTACH_FS
2831 int locktype = 0, use_locktype = -1;
2832 #endif /* AFS_DEMAND_ATTACH_FS */
2838 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2839 Log("VAttachVolume: retried too many times trying to lock header for "
2840 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2841 VPartitionPath(partp));
2845 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2846 Log("VAttachVolume: retried too many times trying to checkout "
2847 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2848 VPartitionPath(partp));
2853 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2854 /* short-circuit the 'volume does not exist' case */
2859 #ifdef FSSYNC_BUILD_CLIENT
2860 checkout = !done_checkout;
2862 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2864 memset(&res, 0, sizeof(res));
2866 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2869 if (res.hdr.reason == FSYNC_SALVAGE) {
2870 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2871 afs_printable_uint32_lu(volid));
2874 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2875 afs_printable_uint32_lu(volid));
2876 *ec = VNOVOL; /* XXXX */
2884 #ifdef AFS_DEMAND_ATTACH_FS
2885 if (use_locktype < 0) {
2886 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2887 * if it turns out to be RW */
2888 locktype = VVolLockType(mode, 0);
2891 /* a previous try says we should use use_locktype to lock the volume,
2893 locktype = use_locktype;
2896 if (!peek && locktype) {
2897 code = VLockVolumeNB(vp, locktype);
2899 if (code == EBUSY) {
2900 Log("VAttachVolume: another program has vol %lu locked\n",
2901 afs_printable_uint32_lu(volid));
2903 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2904 code, afs_printable_uint32_lu(volid));
2911 #endif /* AFS_DEMAND_ATTACH_FS */
2913 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2923 DiskToVolumeHeader(&header, &diskHeader);
2925 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2926 header.largeVnodeIndex);
2927 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2928 header.smallVnodeIndex);
2929 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2931 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2934 /* only need to do this once */
2936 GetVolumeHeader(vp);
2940 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2941 /* demand attach changes the V_PEEK mechanism
2943 * we can now suck the current disk data structure over
2944 * the fssync interface without going to disk
2946 * (technically, we don't need to restrict this feature
2947 * to demand attach fileservers. However, I'm trying
2948 * to limit the number of common code changes)
2950 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2952 res.payload.len = sizeof(VolumeDiskData);
2953 res.payload.buf = &(V_disk(vp));
2955 if (FSYNC_VolOp(vp->hashid,
2957 FSYNC_VOL_QUERY_HDR,
2960 goto disk_header_loaded;
2963 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2964 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2965 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2967 #ifdef AFS_DEMAND_ATTACH_FS
2970 IncUInt64(&VStats.hdr_loads);
2971 IncUInt64(&vp->stats.hdr_loads);
2973 #endif /* AFS_DEMAND_ATTACH_FS */
2976 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2977 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2981 #ifdef AFS_DEMAND_ATTACH_FS
2982 # ifdef FSSYNC_BUILD_CLIENT
2984 # endif /* FSSYNC_BUILD_CLIENT */
2986 /* if the lock type we actually used to lock the volume is different than
2987 * the lock type we should have used, retry with the lock type we should
2989 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2990 if (locktype != use_locktype) {
2994 #endif /* AFS_DEMAND_ATTACH_FS */
2999 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
3000 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
3002 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
3004 if (code == SYNC_DENIED) {
3005 /* must retry checkout; fileserver no longer thinks we have
3011 } else if (code != SYNC_OK) {
3015 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3018 /* either we are going to be called again for a second pass, or we
3019 * encountered an error; clean up in either case */
3021 #ifdef AFS_DEMAND_ATTACH_FS
3022 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3025 #endif /* AFS_DEMAND_ATTACH_FS */
3026 if (vp->linkHandle) {
3027 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3028 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3029 IH_RELEASE(vp->diskDataHandle);
3030 IH_RELEASE(vp->linkHandle);
3036 FreeVolumeHeader(vp);
3046 #ifdef AFS_DEMAND_ATTACH_FS
3048 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3049 Volume *vp, int *acheckedOut)
3053 if (vp->pending_vol_op) {
3057 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3059 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3061 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3062 } else if (code == 0) {
3063 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3066 /* we need the vol header to determine if the volume can be
3067 * left online for the vop, so... get the header */
3071 /* attach header with peek=1 to avoid checking out the volume
3072 * or locking it; we just want the header info, we're not
3073 * messing with the volume itself at all */
3074 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3081 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3082 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3084 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3087 /* make sure we grab a new vol header and re-open stuff on
3088 * actual attachment; we can't keep the data we grabbed, since
3089 * it was not done under a lock and thus not safe */
3090 FreeVolumeHeader(vp);
3091 VReleaseVolumeHandles_r(vp);
3094 /* see if the pending volume op requires exclusive access */
3095 switch (vp->pending_vol_op->vol_op_state) {
3096 case FSSYNC_VolOpPending:
3097 /* this should never happen */
3098 opr_Assert(vp->pending_vol_op->vol_op_state
3099 != FSSYNC_VolOpPending);
3102 case FSSYNC_VolOpRunningUnknown:
3103 /* this should never happen; we resolved 'unknown' above */
3104 opr_Assert(vp->pending_vol_op->vol_op_state
3105 != FSSYNC_VolOpRunningUnknown);
3108 case FSSYNC_VolOpRunningOffline:
3109 /* mark the volume down */
3111 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3113 /* do not set V_offlineMessage here; we don't have ownership of
3114 * the volume (and probably do not have the header loaded), so we
3115 * can't alter the disk header */
3117 /* check to see if we should set the specialStatus flag */
3118 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3119 /* don't overwrite specialStatus if it was already set to
3120 * something else (e.g. VMOVED) */
3121 if (!vp->specialStatus) {
3122 vp->specialStatus = VBUSY;
3134 #endif /* AFS_DEMAND_ATTACH_FS */
3137 * volume attachment helper function.
3139 * @param[out] ec error code
3140 * @param[in] volumeId volume ID of the attaching volume
3141 * @param[in] path full path to the volume header .vol file
3142 * @param[in] partp disk partition object for the attaching partition
3143 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3144 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3145 * DAFS) should already be initialized
3146 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3147 * if there is a volume operation running for this volume
3148 * that should set the volume to VBUSY during its run. 0
3149 * otherwise. (see VVolOpSetVBusy_r)
3150 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3152 * @param[out] acheckedOut If we successfully checked-out the volume from
3153 * the fileserver (if we needed to), this is set
3154 * to 1, otherwise it is 0.
3156 * @return pointer to the semi-attached volume pointer
3157 * @retval NULL an error occurred (check value of *ec)
3158 * @retval vp volume successfully attaching
3160 * @pre no locks held
3162 * @post VOL_LOCK held
3165 attach2(Error * ec, VolumeId volumeId, char *path, struct DiskPartition64 *partp,
3166 Volume * vp, int isbusy, int mode, int *acheckedOut)
3168 /* have we read in the header successfully? */
3169 int read_header = 0;
3171 #ifdef AFS_DEMAND_ATTACH_FS
3172 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3176 /* in the case of an error, to what state should the volume be
3178 VolState error_state = VOL_STATE_ERROR;
3179 #endif /* AFS_DEMAND_ATTACH_FS */
3183 vp->vnodeIndex[vLarge].handle = NULL;
3184 vp->vnodeIndex[vSmall].handle = NULL;
3185 vp->diskDataHandle = NULL;
3186 vp->linkHandle = NULL;
3190 #ifdef AFS_DEMAND_ATTACH_FS
3191 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3193 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3196 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3197 #endif /* !AFS_DEMAND_ATTACH_FS */
3199 if (*ec == VNOVOL) {
3200 /* if the volume doesn't exist, skip straight to 'error' so we don't
3201 * request a salvage */
3202 goto unlocked_error;
3208 /* ensure that we don't override specialStatus if it was set to
3209 * something else (e.g. VMOVED) */
3210 if (isbusy && !vp->specialStatus) {
3211 vp->specialStatus = VBUSY;
3213 vp->shuttingDown = 0;
3214 vp->goingOffline = 0;
3216 #ifdef AFS_DEMAND_ATTACH_FS
3217 vp->stats.last_attach = FT_ApproxTime();
3218 vp->stats.attaches++;
3222 IncUInt64(&VStats.attaches);
3223 vp->cacheCheck = ++VolumeCacheCheck;
3224 /* just in case this ever rolls over */
3225 if (!vp->cacheCheck)
3226 vp->cacheCheck = ++VolumeCacheCheck;
3229 #ifdef AFS_DEMAND_ATTACH_FS
3230 V_attachFlags(vp) |= VOL_HDR_LOADED;
3231 vp->stats.last_hdr_load = vp->stats.last_attach;
3232 #endif /* AFS_DEMAND_ATTACH_FS */
3236 struct IndexFileHeader iHead;
3239 * We just read in the diskstuff part of the header. If the detailed
3240 * volume stats area has not yet been initialized, we should bzero the
3241 * area and mark it as initialized.
3243 if (!(V_stat_initialized(vp))) {
3244 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3245 V_stat_initialized(vp) = 1;
3248 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3249 (char *)&iHead, sizeof(iHead),
3250 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3253 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3258 struct IndexFileHeader iHead;
3260 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3261 (char *)&iHead, sizeof(iHead),
3262 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3265 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3269 #ifdef AFS_NAMEI_ENV
3271 struct versionStamp stamp;
3273 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3274 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3277 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3280 #endif /* AFS_NAMEI_ENV */
3282 #if defined(AFS_DEMAND_ATTACH_FS)
3283 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3285 if (!VCanScheduleSalvage()) {
3286 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3288 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3293 /* volume operation in progress */
3295 /* we have already transitioned the vp away from ATTACHING state, so we
3296 * can go right to the end of attach2, and we do not need to transition
3298 goto error_notbroken;
3300 #else /* AFS_DEMAND_ATTACH_FS */
3302 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3303 goto unlocked_error;
3305 #endif /* AFS_DEMAND_ATTACH_FS */
3307 if (V_needsSalvaged(vp)) {
3308 if (vp->specialStatus)
3309 vp->specialStatus = 0;
3311 #if defined(AFS_DEMAND_ATTACH_FS)
3312 if (!VCanScheduleSalvage()) {
3313 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3315 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3318 #else /* AFS_DEMAND_ATTACH_FS */
3320 #endif /* AFS_DEMAND_ATTACH_FS */
3326 vp->nextVnodeUnique = V_uniquifier(vp);
3328 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3329 if (!V_needsSalvaged(vp)) {
3330 V_needsSalvaged(vp) = 1;
3331 VUpdateVolume_r(ec, vp, 0);
3333 #if defined(AFS_DEMAND_ATTACH_FS)
3334 if (!VCanScheduleSalvage()) {
3335 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3337 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3340 #else /* AFS_DEMAND_ATTACH_FS */
3341 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3343 #endif /* AFS_DEMAND_ATTACH_FS */
3348 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3349 /* Only check destroyMe if we are the fileserver, since the
3350 * volserver et al sometimes need to work with volumes with
3351 * destroyMe set. Examples are 'temporary' volumes the
3352 * volserver creates, and when we create a volume (destroyMe
3353 * is set on creation; sometimes a separate volserver
3354 * transaction is created to clear destroyMe).
3357 #if defined(AFS_DEMAND_ATTACH_FS)
3358 /* schedule a salvage so the volume goes away on disk */
3359 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3360 VChangeState_r(vp, VOL_STATE_ERROR);
3363 #endif /* AFS_DEMAND_ATTACH_FS */
3364 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3369 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3370 #ifndef BITMAP_LATER
3371 if (programType == fileServer && VolumeWriteable(vp)) {
3373 for (i = 0; i < nVNODECLASSES; i++) {
3374 VGetBitmap_r(ec, vp, i);
3376 #ifdef AFS_DEMAND_ATTACH_FS
3377 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3379 #endif /* AFS_DEMAND_ATTACH_FS */
3380 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3386 #endif /* BITMAP_LATER */
3388 if (VInit >= 2 && V_needsCallback(vp)) {
3389 if (V_BreakVolumeCallbacks) {
3390 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3391 afs_printable_uint32_lu(V_id(vp)));
3392 V_needsCallback(vp) = 0;
3394 (*V_BreakVolumeCallbacks) (V_id(vp));
3397 VUpdateVolume_r(ec, vp, 0);
3399 #ifdef FSSYNC_BUILD_CLIENT
3400 else if (VCanUseFSSYNC()) {
3401 afs_int32 fsync_code;
3403 V_needsCallback(vp) = 0;
3405 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3409 V_needsCallback(vp) = 1;
3410 Log("Error trying to tell the fileserver to break callbacks for "
3411 "changed volume %lu; error code %ld\n",
3412 afs_printable_uint32_lu(V_id(vp)),
3413 afs_printable_int32_ld(fsync_code));
3415 VUpdateVolume_r(ec, vp, 0);
3418 #endif /* FSSYNC_BUILD_CLIENT */
3421 Log("VAttachVolume: error %d clearing needsCallback on volume "
3422 "%lu; needs salvage\n", (int)*ec,
3423 afs_printable_uint32_lu(V_id(vp)));
3424 #ifdef AFS_DEMAND_ATTACH_FS
3425 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3427 #else /* !AFS_DEMAND_ATTACH_FS */
3429 #endif /* !AFS_DEMAND_ATTACh_FS */
3434 if (programType == fileServer) {
3435 if (vp->specialStatus)
3436 vp->specialStatus = 0;
3437 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3438 V_inUse(vp) = fileServer;
3439 V_offlineMessage(vp)[0] = '\0';
3441 #ifdef AFS_DEMAND_ATTACH_FS
3442 /* check if the volume is actually usable. only do this for DAFS; for
3443 * non-DAFS, volumes that are not inService/blessed can still be
3444 * attached, even if clients cannot access them. this is relevant
3445 * because for non-DAFS, we try to attach the volume when e.g.
3446 * volserver gives us back then vol when its done with it, but
3447 * volserver may give us back a volume that is not inService/blessed. */
3451 /* Put the vol into PREATTACHED state, so if someone tries to
3452 * access it again, we try to attach, see that we're not blessed,
3453 * and give a VNOVOL error again. Putting it into UNATTACHED state
3454 * would result in a VOFFLINE error instead. */
3455 error_state = VOL_STATE_PREATTACHED;
3457 /* mimic e.g. GetVolume errors */
3458 if (!V_blessed(vp)) {
3459 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3460 FreeVolumeHeader(vp);
3461 } else if (!V_inService(vp)) {
3462 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3463 /* the volume is offline and should be unattached */
3465 error_state = VOL_STATE_UNATTACHED;
3466 FreeVolumeHeader(vp);
3468 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3470 error_state = VOL_STATE_ERROR;
3471 /* see if we can recover */
3472 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3477 #endif /* AFS_DEMAND_ATTACH_FS */
3479 #ifdef AFS_DEMAND_ATTACH_FS
3480 if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3481 V_inUse(vp) = programType;
3482 #endif /* AFS_DEMAND_ATTACH_FS */
3483 V_checkoutMode(vp) = mode;
3486 AddVolumeToHashTable(vp, vp->hashid);
3487 #ifdef AFS_DEMAND_ATTACH_FS
3488 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3491 if ((programType != fileServer) ||
3492 (V_inUse(vp) == fileServer)) {
3493 AddVolumeToVByPList_r(vp);
3495 VChangeState_r(vp, VOL_STATE_ATTACHED);
3497 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3506 #ifdef AFS_DEMAND_ATTACH_FS
3507 if (!VIsErrorState(V_attachState(vp))) {
3508 if (programType != fileServer && *ec == VNOVOL) {
3509 /* do not log anything in this case; it is common for
3510 * non-fileserver programs to fail here with VNOVOL, since that
3511 * is what happens when they simply try to use a volume, but that
3512 * volume doesn't exist. */
3514 } else if (VIsErrorState(error_state)) {
3515 Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3516 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3517 V_attachFlags(vp), *ec);
3519 VChangeState_r(vp, error_state);
3521 #endif /* AFS_DEMAND_ATTACH_FS */
3524 VReleaseVolumeHandles_r(vp);
3527 #ifdef AFS_DEMAND_ATTACH_FS
3529 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3530 /* The salvage could not be scheduled with the salvage server
3531 * due to a hard error. Reset the error code to prevent retry loops by
3533 if (*ec == VSALVAGING) {
3542 #else /* !AFS_DEMAND_ATTACH_FS */
3544 #endif /* !AFS_DEMAND_ATTACH_FS */
3548 /* Attach an existing volume.
3549 The volume also normally goes online at this time.
3550 An offline volume must be reattached to make it go online.
3554 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3558 retVal = VAttachVolume_r(ec, volumeId, mode);
3564 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3567 VGetVolumePath(ec, volumeId, &part, &name);
3571 vp = VGetVolume_r(&error, volumeId);
3573 opr_Assert(V_inUse(vp) == 0);
3574 VDetachVolume_r(ec, vp);
3578 return VAttachVolumeByName_r(ec, part, name, mode);
3581 /* Increment a reference count to a volume, sans context swaps. Requires
3582 * possibly reading the volume header in from the disk, since there's
3583 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3585 * N.B. This call can fail if we can't read in the header!! In this case
3586 * we still guarantee we won't context swap, but the ref count won't be
3587 * incremented (otherwise we'd violate the invariant).
3589 /* NOTE: with the demand attach fileserver extensions, the global lock
3590 * is dropped within VHold */
3591 #ifdef AFS_DEMAND_ATTACH_FS
3593 VHold_r(Volume * vp)
3597 VCreateReservation_r(vp);
3598 VWaitExclusiveState_r(vp);
3600 LoadVolumeHeader(&error, vp);
3602 VCancelReservation_r(vp);
3606 VCancelReservation_r(vp);
3609 #else /* AFS_DEMAND_ATTACH_FS */
3611 VHold_r(Volume * vp)
3615 LoadVolumeHeader(&error, vp);
3621 #endif /* AFS_DEMAND_ATTACH_FS */
3623 /**** volume timeout-related stuff ****/
3625 #ifdef AFS_PTHREAD_ENV
3627 static struct timespec *shutdown_timeout;
3628 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3631 VTimedOut(const struct timespec *ts)
3636 if (ts->tv_sec == 0) {
3637 /* short-circuit; this will have always timed out */
3641 code = gettimeofday(&tv, NULL);
3643 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3644 /* assume no timeout; failure mode is we just wait longer than normal
3645 * instead of returning errors when we shouldn't */
3649 if (tv.tv_sec < ts->tv_sec ||
3650 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3659 * Calculate an absolute timeout.
3661 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3662 * NULL, the memory is not touched
3663 * @param[in] timeout How long the timeout should be from now
3665 * @return timeout to use
3666 * @retval NULL no timeout; wait forever
3667 * @retval non-NULL the given value for "ts"
3671 static struct timespec *
3672 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3682 ts->tv_sec = ts->tv_nsec = 0;
3686 code = gettimeofday(&now, NULL);
3688 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3692 ts->tv_sec = now.tv_sec + timeout;
3693 ts->tv_nsec = now.tv_usec * 1000;
3699 * Initialize the shutdown_timeout global.
3702 VShutdownTimeoutInit(void)
3704 struct timespec *ts;
3706 ts = malloc(sizeof(*ts));
3708 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3710 if (!shutdown_timeout) {
3716 * Figure out the timeout that should be used for waiting for offline volumes.
3718 * @param[out] ats Storage space for a local timeout value if needed
3720 * @return The timeout value that should be used
3721 * @retval NULL No timeout; wait forever for offlining volumes
3722 * @retval non-NULL A pointer to the absolute time that should be used as
3723 * the deadline for waiting for offlining volumes.
3725 * @note If we return non-NULL, the pointer we return may or may not be the
3728 static const struct timespec *
3729 VOfflineTimeout(struct timespec *ats)
3731 if (vol_shutting_down) {
3732 opr_Verify(pthread_once(&shutdown_timeout_once,
3733 VShutdownTimeoutInit) == 0);
3734 return shutdown_timeout;
3736 return VCalcTimeout(ats, vol_opts.offline_timeout);
3740 #else /* AFS_PTHREAD_ENV */
3742 /* Waiting a certain amount of time for offlining volumes is not supported
3743 * for LWP due to a lack of primitives. So, we never time out */
3744 # define VTimedOut(x) (0)
3745 # define VOfflineTimeout(x) (NULL)
3747 #endif /* !AFS_PTHREAD_ENV */
3750 VIsGoingOffline_r(struct Volume *vp)
3754 if (vp->goingOffline) {
3755 if (vp->specialStatus) {
3756 code = vp->specialStatus;
3757 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3768 * Tell the caller if a volume is waiting to go offline.
3770 * @param[in] vp The volume we want to know about
3772 * @return volume status
3773 * @retval 0 volume is not waiting to go offline, go ahead and use it
3774 * @retval nonzero volume is waiting to offline, and give the returned code
3775 * as an error to anyone accessing the volume
3777 * @pre VOL_LOCK is NOT held
3778 * @pre caller holds a heavyweight reference on vp
3781 VIsGoingOffline(struct Volume *vp)
3786 code = VIsGoingOffline_r(vp);
3793 * Register an RX call with a volume.
3795 * @param[inout] ec Error code; if unset when passed in, may be set if
3796 * the volume starts going offline
3797 * @param[out] client_ec @see GetVolume
3798 * @param[in] vp Volume struct
3799 * @param[in] cbv VCallByVol struct containing the RX call to register
3801 * @pre VOL_LOCK held
3802 * @pre caller holds heavy ref on vp
3807 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3810 #ifdef AFS_DEMAND_ATTACH_FS
3812 /* just in case the volume started going offline after we got the
3813 * reference to it... otherwise, if the volume started going
3814 * offline right at the end of GetVolume(), we might race with the
3815 * RX call scanner, and return success and add our cbv to the
3816 * rx_call_list _after_ the scanner has scanned the list. */
3817 *ec = VIsGoingOffline_r(vp);
3823 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3824 VWaitStateChange_r(vp);
3826 #endif /* AFS_DEMAND_ATTACH_FS */
3828 queue_Prepend(&vp->rx_call_list, cbv);
3833 * Deregister an RX call with a volume.
3835 * @param[in] vp Volume struct
3836 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3838 * @pre VOL_LOCK held
3839 * @pre caller holds heavy ref on vp
3844 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3846 if (cbv && queue_IsOnQueue(cbv)) {
3847 #ifdef AFS_DEMAND_ATTACH_FS
3848 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3849 VWaitStateChange_r(vp);
3851 #endif /* AFS_DEMAND_ATTACH_FS */
3857 /***************************************************/
3858 /* get and put volume routines */
3859 /***************************************************/
3862 * put back a heavyweight reference to a volume object.
3864 * @param[in] vp volume object pointer
3866 * @pre VOL_LOCK held
3868 * @post heavyweight volume reference put back.
3869 * depending on state, volume may have been taken offline,
3870 * detached, salvaged, freed, etc.
3872 * @internal volume package internal use only
3875 VPutVolume_r(Volume * vp)
3877 opr_Verify(--vp->nUsers >= 0);
3878 if (vp->nUsers == 0) {
3880 ReleaseVolumeHeader(vp->header);
3881 #ifdef AFS_DEMAND_ATTACH_FS
3882 if (!VCheckDetach(vp)) {
3886 #else /* AFS_DEMAND_ATTACH_FS */
3888 #endif /* AFS_DEMAND_ATTACH_FS */
3893 VPutVolume(Volume * vp)
3901 * Puts a volume reference obtained with VGetVolumeWithCall.
3903 * @param[in] vp Volume struct
3904 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3906 * @pre VOL_LOCK is NOT held
3909 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3912 VDeregisterCall_r(vp, cbv);
3917 /* Get a pointer to an attached volume. The pointer is returned regardless
3918 of whether or not the volume is in service or on/off line. An error
3919 code, however, is returned with an indication of the volume's status */
3921 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3925 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3931 * Get a volume reference associated with an RX call.
3933 * @param[out] ec @see GetVolume
3934 * @param[out] client_ec @see GetVolume
3935 * @param[in] volumeId @see GetVolume
3936 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3937 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3938 * with an error if the volume is going offline.
3939 * @param[in] cbv Contains an RX call to be associated with this volume
3940 * reference. This call may be interrupted if the volume is
3941 * requested to go offline while we hold a ref on it. Give NULL
3942 * to not associate an RX call with this reference.
3944 * @return @see GetVolume
3946 * @note for LWP builds, ts must be NULL
3948 * @note A reference obtained with this function MUST be put back with
3949 * VPutVolumeWithCall
3952 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3953 const struct timespec *ts, struct VCallByVol *cbv)
3957 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3958 VRegisterCall_r(ec, client_ec, retVal, cbv);
3964 VGetVolume_r(Error * ec, VolumeId volumeId)
3966 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3969 /* try to get a volume we've previously looked up */
3970 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3972 VGetVolumeByVp_r(Error * ec, Volume * vp)
3974 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3978 * private interface for getting a volume handle
3980 * @param[out] ec error code (0 if no error)
3981 * @param[out] client_ec wire error code to be given to clients
3982 * @param[in] volumeId ID of the volume we want
3983 * @param[in] hint optional hint for hash lookups, or NULL
3984 * @param[in] timeout absolute deadline for waiting for the volume to go
3985 * offline, if it is going offline. NULL to wait forever.
3987 * @return a volume handle for the specified volume
3988 * @retval NULL an error occurred, or the volume is in such a state that
3989 * we cannot load a header or return any volume struct
3991 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3993 * @note 'timeout' is only checked if the volume is actually going offline; so
3994 * if you pass timeout->tv_sec = 0, this will exhibit typical
3995 * nonblocking behavior.
3997 * @note for LWP builds, 'timeout' must be NULL
4000 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
4001 const struct timespec *timeout)
4004 #ifdef AFS_DEMAND_ATTACH_FS
4005 Volume *avp, * rvp = hint;
4009 * if VInit is zero, the volume package dynamic
4010 * data structures have not been initialized yet,
4011 * and we must immediately return an error
4017 *client_ec = VOFFLINE;
4022 #ifdef AFS_DEMAND_ATTACH_FS
4024 VCreateReservation_r(rvp);
4026 #endif /* AFS_DEMAND_ATTACH_FS */
4033 vp = VLookupVolume_r(ec, volumeId, vp);
4039 #ifdef AFS_DEMAND_ATTACH_FS
4040 if (rvp && (rvp != vp)) {
4041 /* break reservation on old vp */
4042 VCancelReservation_r(rvp);
4045 #endif /* AFS_DEMAND_ATTACH_FS */
4049 /* Until we have reached an initialization level of 2
4050 * we don't know whether this volume exists or not.
4051 * We can't sleep and retry later because before a volume
4052 * is attached, the caller tries to get it first. Just
4053 * return VOFFLINE and the caller can choose whether to
4054 * retry the command or not. */
4063 IncUInt64(&VStats.hdr_gets);
4065 #ifdef AFS_DEMAND_ATTACH_FS
4066 /* block if someone else is performing an exclusive op on this volume */
4069 VCreateReservation_r(rvp);
4071 VWaitExclusiveState_r(vp);
4073 /* short circuit with VNOVOL in the following circumstances:
4076 * - VOL_STATE_SHUTTING_DOWN
4078 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4079 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4086 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4087 * VNOVOL for VOL_STATE_DELETED
4089 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4090 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4091 (V_attachState(vp) == VOL_STATE_DELETED)) {
4092 if (vp->specialStatus) {
4093 *ec = vp->specialStatus;
4094 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4103 /* allowable states:
4110 if (vp->salvage.requested) {
4111 VUpdateSalvagePriority_r(vp);
4114 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4115 if (vp->specialStatus) {
4116 *ec = vp->specialStatus;
4120 avp = VAttachVolumeByVp_r(ec, vp, 0);
4123 /* VAttachVolumeByVp_r can return a pointer
4124 * != the vp passed to it under certain
4125 * conditions; make sure we don't leak
4126 * reservations if that happens */
4128 VCancelReservation_r(rvp);
4130 VCreateReservation_r(rvp);
4141 if (vp->specialStatus) {
4142 *ec = vp->specialStatus;
4147 if (vp->specialStatus) {
4148 *ec = vp->specialStatus;
4161 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4163 /* see CheckVnode() in afsfileprocs.c for an explanation
4164 * of this error code logic */
4165 afs_uint32 now = FT_ApproxTime();
4166 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4169 *client_ec = VRESTARTING;
4177 if (VIsErrorState(V_attachState(vp))) {
4178 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4179 * it, or transition it out of that state */
4188 * this test MUST happen after VAttachVolymeByVp, so we have no
4189 * conflicting vol op. (attach2 would have errored out if we had one;
4190 * specifically attach_check_vop must have detected a conflicting vop)
4192 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4194 #endif /* AFS_DEMAND_ATTACH_FS */
4196 LoadVolumeHeader(ec, vp);
4198 /* Only log the error if it was a totally unexpected error. Simply
4199 * a missing inode is likely to be caused by the volume being deleted */
4200 if (errno != ENXIO || GetLogLevel() != 0)
4201 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4202 afs_printable_VolumeId_lu(vp->hashid));
4203 #ifdef AFS_DEMAND_ATTACH_FS
4204 if (VCanScheduleSalvage()) {
4205 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4210 #else /* AFS_DEMAND_ATTACH_FS */
4213 #endif /* AFS_DEMAND_ATTACH_FS */
4217 if (vp->shuttingDown) {
4223 if (programType == fileServer) {
4224 if (vp->goingOffline) {
4225 if (timeout && VTimedOut(timeout)) {
4226 /* we've timed out; don't wait for the vol */
4228 #ifdef AFS_DEMAND_ATTACH_FS
4229 /* wait for the volume to go offline */
4230 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4231 VTimedWaitStateChange_r(vp, timeout, NULL);
4233 #elif defined(AFS_PTHREAD_ENV)
4234 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4235 #else /* AFS_PTHREAD_ENV */
4236 /* LWP has no timed wait, so the caller better not be
4238 opr_Assert(!timeout);
4239 LWP_WaitProcess(VPutVolume);
4240 #endif /* AFS_PTHREAD_ENV */
4244 if (vp->specialStatus) {
4245 *ec = vp->specialStatus;
4246 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4248 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4255 #ifdef AFS_DEMAND_ATTACH_FS
4256 /* if no error, bump nUsers */
4259 VLRU_UpdateAccess_r(vp);
4262 VCancelReservation_r(rvp);
4265 if (client_ec && !*client_ec) {
4268 #else /* AFS_DEMAND_ATTACH_FS */
4269 /* if no error, bump nUsers */
4276 #endif /* AFS_DEMAND_ATTACH_FS */
4279 opr_Assert(vp || *ec);
4284 /***************************************************/
4285 /* Volume offline/detach routines */
4286 /***************************************************/
4288 /* caller MUST hold a heavyweight ref on vp */
4289 #ifdef AFS_DEMAND_ATTACH_FS
4291 VTakeOffline_r(Volume * vp)
4295 opr_Assert(vp->nUsers > 0);
4296 opr_Assert(programType == fileServer);
4298 VCreateReservation_r(vp);
4299 VWaitExclusiveState_r(vp);
4301 vp->goingOffline = 1;
4302 V_needsSalvaged(vp) = 1;
4304 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4305 VCancelReservation_r(vp);
4307 #else /* AFS_DEMAND_ATTACH_FS */
4309 VTakeOffline_r(Volume * vp)
4311 opr_Assert(vp->nUsers > 0);
4312 opr_Assert(programType == fileServer);
4314 vp->goingOffline = 1;
4315 V_needsSalvaged(vp) = 1;
4317 #endif /* AFS_DEMAND_ATTACH_FS */
4320 VTakeOffline(Volume * vp)
4328 * force a volume offline.
4330 * @param[in] vp volume object pointer
4331 * @param[in] flags flags (see note below)
4333 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4334 * used when VUpdateVolume_r needs to call VForceOffline_r
4335 * (which in turn would normally call VUpdateVolume_r)
4337 * @see VUpdateVolume_r
4339 * @pre VOL_LOCK must be held.
4340 * for DAFS, caller must hold ref.
4342 * @note for DAFS, it _is safe_ to call this function from an
4345 * @post needsSalvaged flag is set.
4346 * for DAFS, salvage is requested.
4347 * no further references to the volume through the volume
4348 * package will be honored.
4349 * all file descriptor and vnode caches are invalidated.
4351 * @warning this is a heavy-handed interface. it results in
4352 * a volume going offline regardless of the current
4353 * reference count state.
4355 * @internal volume package internal use only
4358 VForceOffline_r(Volume * vp, int flags)
4362 #ifdef AFS_DEMAND_ATTACH_FS
4363 VChangeState_r(vp, VOL_STATE_ERROR);
4368 strcpy(V_offlineMessage(vp),
4369 "Forced offline due to internal error: volume needs to be salvaged");
4370 Log("Volume %" AFS_VOLID_FMT " forced offline: it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4373 vp->goingOffline = 0;
4374 V_needsSalvaged(vp) = 1;
4375 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4376 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4379 #ifdef AFS_DEMAND_ATTACH_FS
4380 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4381 #endif /* AFS_DEMAND_ATTACH_FS */
4383 #ifdef AFS_PTHREAD_ENV
4384 opr_cv_broadcast(&vol_put_volume_cond);
4385 #else /* AFS_PTHREAD_ENV */
4386 LWP_NoYieldSignal(VPutVolume);
4387 #endif /* AFS_PTHREAD_ENV */
4389 VReleaseVolumeHandles_r(vp);
4393 * force a volume offline.
4395 * @param[in] vp volume object pointer
4397 * @see VForceOffline_r
4400 VForceOffline(Volume * vp)
4403 VForceOffline_r(vp, 0);
4408 * Iterate over the RX calls associated with a volume, and interrupt them.
4410 * @param[in] vp The volume whose RX calls we want to scan
4412 * @pre VOL_LOCK held
4415 VScanCalls_r(struct Volume *vp)
4417 struct VCallByVol *cbv, *ncbv;
4419 #ifdef AFS_DEMAND_ATTACH_FS
4420 VolState state_save;
4423 if (queue_IsEmpty(&vp->rx_call_list))
4424 return; /* no calls to interrupt */
4425 if (!vol_opts.interrupt_rxcall)
4426 return; /* we have no function with which to interrupt calls */
4427 err = VIsGoingOffline_r(vp);
4429 return; /* we're not going offline anymore */
4431 #ifdef AFS_DEMAND_ATTACH_FS
4432 VWaitExclusiveState_r(vp);
4433 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4435 #endif /* AFS_DEMAND_ATTACH_FS */
4437 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4438 if (GetLogLevel() != 0) {
4439 struct rx_peer *peer;
4441 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4443 Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4444 "from it; kicking client off with error %ld\n",
4445 afs_printable_VolumeId_lu(vp->hashid),
4446 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4447 (unsigned) ntohs(rx_PortOf(peer)),
4450 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4453 #ifdef AFS_DEMAND_ATTACH_FS
4455 VChangeState_r(vp, state_save);
4456 #endif /* AFS_DEMAND_ATTACH_FS */
4459 #ifdef AFS_DEMAND_ATTACH_FS
4461 * Wait for a vp to go offline.
4463 * @param[out] ec 1 if a salvage on the volume has been requested and
4464 * salvok == 0, 0 otherwise
4465 * @param[in] vp The volume to wait for
4466 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4467 * has been requested to salvage. Otherwise we keep waiting
4468 * until the volume has gone offline.
4470 * @pre VOL_LOCK held
4471 * @pre caller holds a lightweight ref on vp
4476 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4478 struct timespec timeout_ts;
4479 const struct timespec *ts;
4482 ts = VOfflineTimeout(&timeout_ts);
4486 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4487 if (!salvok && vp->salvage.requested) {
4491 VTimedWaitStateChange_r(vp, ts, &timedout);
4494 /* we didn't time out, so the volume must be offline, so we're done */
4498 /* If we got here, we timed out waiting for the volume to go offline.
4499 * Kick off the accessing RX calls and wait again */
4503 while (!VIsOfflineState(V_attachState(vp))) {
4504 if (!salvok && vp->salvage.requested) {
4509 VWaitStateChange_r(vp);
4513 #else /* AFS_DEMAND_ATTACH_FS */
4516 * Wait for a volume to go offline.
4518 * @pre VOL_LOCK held
4520 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4523 VWaitForOffline_r(Error *ec, VolumeId volid)
4526 const struct timespec *ts;
4527 #ifdef AFS_PTHREAD_ENV
4528 struct timespec timeout_ts;
4531 ts = VOfflineTimeout(&timeout_ts);
4533 vp = GetVolume(ec, NULL, volid, NULL, ts);
4535 /* error occurred so bad that we can't even get a vp; we have no
4536 * information on the vol so we don't know whether to wait, so just
4540 if (!VIsGoingOffline_r(vp)) {
4541 /* volume is no longer going offline, so we're done */
4546 /* If we got here, we timed out waiting for the volume to go offline.
4547 * Kick off the accessing RX calls and wait again */
4553 vp = VGetVolume_r(ec, volid);
4555 /* In case it was reattached... */
4559 #endif /* !AFS_DEMAND_ATTACH_FS */
4561 /* The opposite of VAttachVolume. The volume header is written to disk, with
4562 the inUse bit turned off. A copy of the header is maintained in memory,
4563 however (which is why this is VOffline, not VDetach).
4566 VOffline_r(Volume * vp, char *message)
4569 #ifndef AFS_DEMAND_ATTACH_FS
4570 VolumeId vid = V_id(vp);
4573 opr_Assert(programType != volumeUtility && programType != volumeServer);
4578 if (V_offlineMessage(vp)[0] == '\0')
4579 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4580 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4582 vp->goingOffline = 1;
4583 #ifdef AFS_DEMAND_ATTACH_FS
4584 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4585 VCreateReservation_r(vp);
4587 VWaitForOfflineByVp_r(&error, vp, 1);
4588 VCancelReservation_r(vp);
4589 #else /* AFS_DEMAND_ATTACH_FS */
4591 VWaitForOffline_r(&error, vid);
4592 #endif /* AFS_DEMAND_ATTACH_FS */
4595 #ifdef AFS_DEMAND_ATTACH_FS
4597 * Take a volume offline in order to perform a volume operation.
4599 * @param[inout] ec address in which to store error code
4600 * @param[in] vp volume object pointer
4601 * @param[in] message volume offline status message
4604 * - VOL_LOCK is held
4605 * - caller MUST hold a heavyweight ref on vp
4608 * - volume is taken offline
4609 * - if possible, volume operation is promoted to running state
4610 * - on failure, *ec is set to nonzero
4612 * @note Although this function does not return any value, it may
4613 * still fail to promote our pending volume operation to
4614 * a running state. Any caller MUST check the value of *ec,
4615 * and MUST NOT blindly assume success.
4617 * @warning if the caller does not hold a lightweight ref on vp,
4618 * then it MUST NOT reference vp after this function
4619 * returns to the caller.
4621 * @internal volume package internal use only
4624 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4627 opr_Assert(vp->pending_vol_op);
4633 if (V_offlineMessage(vp)[0] == '\0')
4634 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4635 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4637 vp->goingOffline = 1;
4638 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4639 VCreateReservation_r(vp);
4642 if (vp->pending_vol_op->com.programType != salvageServer) {
4643 /* do not give corrupted volumes to the volserver */
4648 VWaitForOfflineByVp_r(ec, vp, salvok);
4650 VCancelReservation_r(vp);
4652 #endif /* AFS_DEMAND_ATTACH_FS */
4655 VOffline(Volume * vp, char *message)
4658 VOffline_r(vp, message);
4662 /* This gets used for the most part by utility routines that don't want
4663 * to keep all the volume headers around. Generally, the file server won't
4664 * call this routine, because then the offline message in the volume header
4665 * (or other information) won't be available to clients. For NAMEI, also
4666 * close the file handles. However, the fileserver does call this during
4667 * an attach following a volume operation.
4670 VDetachVolume_r(Error * ec, Volume * vp)
4672 #ifdef FSSYNC_BUILD_CLIENT
4674 struct DiskPartition64 *tpartp;
4675 int notifyServer = 0;
4676 int useDone = FSYNC_VOL_ON;
4678 if (VCanUseFSSYNC()) {
4679 notifyServer = vp->needsPutBack;
4680 if (V_destroyMe(vp) == DESTROY_ME)
4681 useDone = FSYNC_VOL_LEAVE_OFF;
4682 # ifdef AFS_DEMAND_ATTACH_FS
4683 else if (!V_blessed(vp) || !V_inService(vp))
4684 useDone = FSYNC_VOL_LEAVE_OFF;
4687 # ifdef AFS_DEMAND_ATTACH_FS
4688 if (V_needsSalvaged(vp)) {
4690 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4693 tpartp = vp->partition;
4695 #endif /* FSSYNC_BUILD_CLIENT */
4697 *ec = 0; /* always "succeeds" */
4698 DeleteVolumeFromHashTable(vp);
4699 vp->shuttingDown = 1;
4700 #ifdef AFS_DEMAND_ATTACH_FS
4701 DeleteVolumeFromVByPList_r(vp);
4703 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4705 if (programType != fileServer)
4707 #endif /* AFS_DEMAND_ATTACH_FS */
4709 /* Will be detached sometime in the future--this is OK since volume is offline */
4711 /* XXX the following code should really be moved to VCheckDetach() since the volume
4712 * is not technically detached until the refcounts reach zero
4714 #ifdef FSSYNC_BUILD_CLIENT
4715 if (VCanUseFSSYNC() && notifyServer) {
4716 if (notifyServer == VOL_PUTBACK_DELETE) {
4717 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4718 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4719 * to signify a deleted volume. */
4720 useDone = FSYNC_VOL_DONE;
4723 * Note: The server is not notified in the case of a bogus volume
4724 * explicitly to make it possible to create a volume, do a partial
4725 * restore, then abort the operation without ever putting the volume
4726 * online. This is essential in the case of a volume move operation
4727 * between two partitions on the same server. In that case, there
4728 * would be two instances of the same volume, one of them bogus,
4729 * which the file server would attempt to put on line
4731 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4733 #endif /* FSSYNC_BUILD_CLIENT */
4737 VDetachVolume(Error * ec, Volume * vp)
4740 VDetachVolume_r(ec, vp);
4745 /***************************************************/
4746 /* Volume fd/inode handle closing routines */
4747 /***************************************************/
4749 /* For VDetachVolume, we close all cached file descriptors, but keep
4750 * the Inode handles in case we need to read from a busy volume.
4752 /* for demand attach, caller MUST hold ref count on vp */
4754 VCloseVolumeHandles_r(Volume * vp)
4756 #ifdef AFS_DEMAND_ATTACH_FS
4757 VolState state_save;
4759 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4764 DFlushVolume(vp->hashid);
4766 #ifdef AFS_DEMAND_ATTACH_FS
4770 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4771 VCloseVnodeFiles_r(vp);
4773 #ifdef AFS_DEMAND_ATTACH_FS
4777 /* Too time consuming and unnecessary for the volserver */
4778 if (programType == fileServer) {
4779 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4780 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4781 IH_CONDSYNC(vp->diskDataHandle);
4782 #ifdef AFS_NAMEI_ENV
4783 IH_CONDSYNC(vp->linkHandle);
4784 #endif /* AFS_NAMEI_ENV */
4787 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4788 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4789 IH_REALLYCLOSE(vp->diskDataHandle);
4790 IH_REALLYCLOSE(vp->linkHandle);
4792 #ifdef AFS_DEMAND_ATTACH_FS
4793 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4798 VChangeState_r(vp, state_save);
4802 /* For both VForceOffline and VOffline, we close all relevant handles.
4803 * For VOffline, if we re-attach the volume, the files may possible be
4804 * different than before.
4806 /* for demand attach, caller MUST hold a ref count on vp */
4808 VReleaseVolumeHandles_r(Volume * vp)
4810 #ifdef AFS_DEMAND_ATTACH_FS
4811 VolState state_save;
4813 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4818 DFlushVolume(vp->hashid);
4820 #ifdef AFS_DEMAND_ATTACH_FS
4824 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4826 #ifdef AFS_DEMAND_ATTACH_FS
4830 /* Too time consuming and unnecessary for the volserver */
4831 if (programType == fileServer) {
4832 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4833 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4834 IH_CONDSYNC(vp->diskDataHandle);
4835 #ifdef AFS_NAMEI_ENV
4836 IH_CONDSYNC(vp->linkHandle);
4837 #endif /* AFS_NAMEI_ENV */
4840 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4841 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4842 IH_RELEASE(vp->diskDataHandle);
4843 IH_RELEASE(vp->linkHandle);
4845 #ifdef AFS_DEMAND_ATTACH_FS
4846 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4851 VChangeState_r(vp, state_save);
4856 /***************************************************/
4857 /* Volume write and fsync routines */
4858 /***************************************************/
4861 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4863 #ifdef AFS_DEMAND_ATTACH_FS
4864 VolState state_save;
4866 if (flags & VOL_UPDATE_WAIT) {
4867 VCreateReservation_r(vp);
4868 VWaitExclusiveState_r(vp);
4873 if (programType == fileServer) {
4875 V_uniquifier(vp) = V_nextVnodeUnique(vp);
4878 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4879 if (V_uniquifier(vp) < V_nextVnodeUnique(vp)) {
4880 /* uniquifier rolled over; reset the counters */
4881 V_nextVnodeUnique(vp) = 2; /* 1 is reserved for the root vnode */
4883 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4888 #ifdef AFS_DEMAND_ATTACH_FS
4889 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4893 WriteVolumeHeader_r(ec, vp);
4895 #ifdef AFS_DEMAND_ATTACH_FS
4897 VChangeState_r(vp, state_save);
4898 if (flags & VOL_UPDATE_WAIT) {
4899 VCancelReservation_r(vp);
4904 Log("VUpdateVolume: error updating volume header, volume %" AFS_VOLID_FMT " (%s)\n",
4905 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
4906 /* try to update on-disk header,
4907 * while preventing infinite recursion */
4908 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4909 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4915 VUpdateVolume(Error * ec, Volume * vp)
4918 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4923 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4927 #ifdef AFS_DEMAND_ATTACH_FS
4928 VolState state_save;
4931 if (flags & VOL_SYNC_WAIT) {
4932 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4934 VUpdateVolume_r(ec, vp, 0);
4937 #ifdef AFS_DEMAND_ATTACH_FS
4938 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4941 fdP = IH_OPEN(V_diskDataHandle(vp));
4942 opr_Assert(fdP != NULL);
4943 code = FDH_SYNC(fdP);
4944 opr_Assert(code == 0);
4946 #ifdef AFS_DEMAND_ATTACH_FS
4948 VChangeState_r(vp, state_save);
4954 VSyncVolume(Error * ec, Volume * vp)
4957 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4962 /***************************************************/
4963 /* Volume dealloaction routines */
4964 /***************************************************/
4966 #ifdef AFS_DEMAND_ATTACH_FS
4968 FreeVolume(Volume * vp)
4970 /* free the heap space, iff it's safe.
4971 * otherwise, pull it out of the hash table, so it
4972 * will get deallocated when all refs to it go away */
4973 if (!VCheckFree(vp)) {
4974 DeleteVolumeFromHashTable(vp);
4975 DeleteVolumeFromVByPList_r(vp);
4977 /* make sure we invalidate the header cache entry */
4978 FreeVolumeHeader(vp);
4981 #endif /* AFS_DEMAND_ATTACH_FS */
4984 ReallyFreeVolume(Volume * vp)
4989 #ifdef AFS_DEMAND_ATTACH_FS
4991 VChangeState_r(vp, VOL_STATE_FREED);
4992 if (vp->pending_vol_op)
4993 free(vp->pending_vol_op);
4994 #endif /* AFS_DEMAND_ATTACH_FS */
4995 for (i = 0; i < nVNODECLASSES; i++)
4996 if (vp->vnodeIndex[i].bitmap)
4997 free(vp->vnodeIndex[i].bitmap);
4998 FreeVolumeHeader(vp);
4999 #ifndef AFS_DEMAND_ATTACH_FS
5000 DeleteVolumeFromHashTable(vp);
5001 #endif /* AFS_DEMAND_ATTACH_FS */
5005 /* check to see if we should shutdown this volume
5006 * returns 1 if volume was freed, 0 otherwise */
5007 #ifdef AFS_DEMAND_ATTACH_FS
5009 VCheckDetach(Volume * vp)
5014 if (vp->nUsers || vp->nWaiters)
5017 if (vp->shuttingDown) {
5019 if ((programType != fileServer) &&
5020 (V_inUse(vp) == programType) &&
5021 ((V_checkoutMode(vp) == V_VOLUPD) ||
5022 (V_checkoutMode(vp) == V_SECRETLY) ||
5023 ((V_checkoutMode(vp) == V_CLONE) &&
5024 (VolumeWriteable(vp))))) {
5026 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5028 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " "
5029 "failed with errno %d\n", afs_printable_VolumeId_lu(vp->hashid), errno);
5032 VReleaseVolumeHandles_r(vp);
5034 ReallyFreeVolume(vp);
5035 if (programType == fileServer) {
5036 opr_cv_broadcast(&vol_put_volume_cond);
5041 #else /* AFS_DEMAND_ATTACH_FS */
5043 VCheckDetach(Volume * vp)
5051 if (vp->shuttingDown) {
5053 if ((programType != fileServer) &&
5054 (V_inUse(vp) == programType) &&
5055 ((V_checkoutMode(vp) == V_VOLUPD) ||
5056 (V_checkoutMode(vp) == V_SECRETLY) ||
5057 ((V_checkoutMode(vp) == V_CLONE) &&
5058 (VolumeWriteable(vp))))) {
5060 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5062 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " failed with errno %d\n",
5063 afs_printable_VolumeId_lu(vp->hashid), errno);
5066 VReleaseVolumeHandles_r(vp);
5067 ReallyFreeVolume(vp);
5068 if (programType == fileServer) {
5069 #if defined(AFS_PTHREAD_ENV)
5070 opr_cv_broadcast(&vol_put_volume_cond);
5071 #else /* AFS_PTHREAD_ENV */
5072 LWP_NoYieldSignal(VPutVolume);
5073 #endif /* AFS_PTHREAD_ENV */
5078 #endif /* AFS_DEMAND_ATTACH_FS */
5080 /* check to see if we should offline this volume
5081 * return 1 if volume went offline, 0 otherwise */
5082 #ifdef AFS_DEMAND_ATTACH_FS
5084 VCheckOffline(Volume * vp)
5088 if (vp->goingOffline && !vp->nUsers) {
5090 opr_Assert(programType == fileServer);
5091 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5092 (V_attachState(vp) != VOL_STATE_FREED) &&
5093 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5094 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5095 (V_attachState(vp) != VOL_STATE_DELETED));
5099 * VOL_STATE_GOING_OFFLINE
5100 * VOL_STATE_SHUTTING_DOWN
5101 * VIsErrorState(V_attachState(vp))
5102 * VIsExclusiveState(V_attachState(vp))
5105 VCreateReservation_r(vp);
5106 VChangeState_r(vp, VOL_STATE_OFFLINING);
5109 /* must clear the goingOffline flag before we drop the glock */
5110 vp->goingOffline = 0;
5115 /* perform async operations */
5116 VUpdateVolume_r(&error, vp, 0);
5117 VCloseVolumeHandles_r(vp);
5119 if (GetLogLevel() != 0) {
5120 if (V_offlineMessage(vp)[0]) {
5121 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5122 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5123 V_offlineMessage(vp));
5125 Log("VOffline: Volume %lu (%s) is now offline\n",
5126 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5130 /* invalidate the volume header cache entry */
5131 FreeVolumeHeader(vp);
5133 /* if nothing changed state to error or salvaging,
5134 * drop state to unattached */
5135 if (!VIsErrorState(V_attachState(vp))) {
5136 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5138 VCancelReservation_r(vp);
5139 /* no usage of vp is safe beyond this point */
5143 #else /* AFS_DEMAND_ATTACH_FS */
5145 VCheckOffline(Volume * vp)
5149 if (vp->goingOffline && !vp->nUsers) {
5151 opr_Assert(programType == fileServer);
5154 vp->goingOffline = 0;
5156 VUpdateVolume_r(&error, vp, 0);
5157 VCloseVolumeHandles_r(vp);
5158 if (GetLogLevel() != 0) {
5159 if (V_offlineMessage(vp)[0]) {
5160 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5161 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5162 V_offlineMessage(vp));
5164 Log("VOffline: Volume %lu (%s) is now offline\n",
5165 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5168 FreeVolumeHeader(vp);
5169 #ifdef AFS_PTHREAD_ENV
5170 opr_cv_broadcast(&vol_put_volume_cond);
5171 #else /* AFS_PTHREAD_ENV */
5172 LWP_NoYieldSignal(VPutVolume);
5173 #endif /* AFS_PTHREAD_ENV */
5177 #endif /* AFS_DEMAND_ATTACH_FS */
5179 /***************************************************/
5180 /* demand attach fs ref counting routines */
5181 /***************************************************/
5183 #ifdef AFS_DEMAND_ATTACH_FS
5184 /* the following two functions handle reference counting for
5185 * asynchronous operations on volume structs.
5187 * their purpose is to prevent a VDetachVolume or VShutdown
5188 * from free()ing the Volume struct during an async i/o op */
5190 /* register with the async volume op ref counter */
5191 /* VCreateReservation_r moved into inline code header because it
5192 * is now needed in vnode.c -- tkeiser 11/20/2007
5196 * decrement volume-package internal refcount.
5198 * @param vp volume object pointer
5200 * @internal volume package internal use only
5203 * @arg VOL_LOCK is held
5204 * @arg lightweight refcount held
5206 * @post volume waiters refcount is decremented; volume may
5207 * have been deallocated/shutdown/offlined/salvaged/
5208 * whatever during the process
5210 * @warning once you have tossed your last reference (you can acquire
5211 * lightweight refs recursively) it is NOT SAFE to reference
5212 * a volume object pointer ever again
5214 * @see VCreateReservation_r
5216 * @note DEMAND_ATTACH_FS only
5219 VCancelReservation_r(Volume * vp)
5221 opr_Verify(--vp->nWaiters >= 0);
5222 if (vp->nWaiters == 0) {
5224 if (!VCheckDetach(vp)) {
5231 /* check to see if we should free this volume now
5232 * return 1 if volume was freed, 0 otherwise */
5234 VCheckFree(Volume * vp)
5237 if ((vp->nUsers == 0) &&
5238 (vp->nWaiters == 0) &&
5239 !(V_attachFlags(vp) & (VOL_IN_HASH |
5243 ReallyFreeVolume(vp);
5248 #endif /* AFS_DEMAND_ATTACH_FS */
5251 /***************************************************/
5252 /* online volume operations routines */
5253 /***************************************************/
5255 #ifdef AFS_DEMAND_ATTACH_FS
5257 * register a volume operation on a given volume.
5259 * @param[in] vp volume object
5260 * @param[in] vopinfo volume operation info object
5262 * @pre VOL_LOCK is held
5264 * @post volume operation info object attached to volume object.
5265 * volume operation statistics updated.
5267 * @note by "attached" we mean a copy of the passed in object is made
5269 * @internal volume package internal use only
5272 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5274 FSSYNC_VolOp_info * info;
5276 /* attach a vol op info node to the volume struct */
5277 info = malloc(sizeof(FSSYNC_VolOp_info));
5278 opr_Assert(info != NULL);
5279 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5280 vp->pending_vol_op = info;
5283 vp->stats.last_vol_op = FT_ApproxTime();
5284 vp->stats.vol_ops++;
5285 IncUInt64(&VStats.vol_ops);
5291 * deregister the volume operation attached to this volume.
5293 * @param[in] vp volume object pointer
5295 * @pre VOL_LOCK is held
5297 * @post the volume operation info object is detached from the volume object
5299 * @internal volume package internal use only
5302 VDeregisterVolOp_r(Volume * vp)
5304 if (vp->pending_vol_op) {
5305 free(vp->pending_vol_op);
5306 vp->pending_vol_op = NULL;
5310 #endif /* AFS_DEMAND_ATTACH_FS */
5313 * determine whether it is safe to leave a volume online during
5314 * the volume operation described by the vopinfo object.
5316 * @param[in] vp volume object
5317 * @param[in] vopinfo volume operation info object
5319 * @return whether it is safe to leave volume online
5320 * @retval 0 it is NOT SAFE to leave the volume online
5321 * @retval 1 it is safe to leave the volume online during the operation
5324 * @arg VOL_LOCK is held
5325 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5326 * this condition is met)
5328 * @internal volume package internal use only
5331 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5333 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5334 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5335 (vopinfo->com.reason == V_READONLY ||
5336 (!VolumeWriteable(vp) &&
5337 (vopinfo->com.reason == V_CLONE ||
5338 vopinfo->com.reason == V_DUMP)))));
5342 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5345 * @param[in] vp volume object
5346 * @param[in] vopinfo volume operation info object
5348 * @return whether it is safe to leave volume online
5349 * @retval 0 it is NOT SAFE to leave the volume online
5350 * @retval 1 it is safe to leave the volume online during the operation
5351 * @retval -1 unsure; volume header is required in order to know whether or
5352 * not is is safe to leave the volume online
5354 * @pre VOL_LOCK is held
5356 * @internal volume package internal use only
5359 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5361 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5362 * assume that we don't know VolumeWriteable; return -1 if the answer
5363 * depends on VolumeWriteable */
5365 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5368 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5369 vopinfo->com.reason == V_READONLY) {
5373 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5374 (vopinfo->com.reason == V_CLONE ||
5375 vopinfo->com.reason == V_DUMP)) {
5377 /* must know VolumeWriteable */
5384 * determine whether VBUSY should be set during this volume operation.
5386 * @param[in] vp volume object
5387 * @param[in] vopinfo volume operation info object
5389 * @return whether VBUSY should be set
5390 * @retval 0 VBUSY does NOT need to be set
5391 * @retval 1 VBUSY SHOULD be set
5393 * @pre VOL_LOCK is held
5395 * @internal volume package internal use only
5398 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5400 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5401 vopinfo->com.reason == FSYNC_SALVAGE) ||
5402 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5403 (vopinfo->com.reason == V_CLONE ||
5404 vopinfo->com.reason == V_DUMP)));
5408 /***************************************************/
5409 /* online salvager routines */
5410 /***************************************************/
5411 #if defined(AFS_DEMAND_ATTACH_FS)
5414 * offline a volume to let it be salvaged.
5416 * @param[in] vp Volume to offline
5418 * @return whether we offlined the volume successfully
5419 * @retval 0 volume was not offlined
5420 * @retval 1 volume is now offline
5422 * @note This is similar to VCheckOffline, but slightly different. We do not
5423 * deal with vp->goingOffline, and we try to avoid touching the volume
5424 * header except just to set needsSalvaged
5426 * @pre VOL_LOCK held
5427 * @pre vp->nUsers == 0
5428 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5431 VOfflineForSalvage_r(struct Volume *vp)
5435 VCreateReservation_r(vp);
5436 VWaitExclusiveState_r(vp);
5438 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5439 /* Someone's using the volume, or someone got to scheduling the salvage
5440 * before us. I don't think either of these should be possible, as we
5441 * should gain no new heavyweight references while we're trying to
5442 * salvage, but just to be sure... */
5443 VCancelReservation_r(vp);
5447 VChangeState_r(vp, VOL_STATE_OFFLINING);
5451 V_needsSalvaged(vp) = 1;
5452 /* ignore error; updating needsSalvaged is just best effort */
5453 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5455 VCloseVolumeHandles_r(vp);
5457 FreeVolumeHeader(vp);
5459 /* volume has been effectively offlined; we can mark it in the SALVAGING
5460 * state now, which lets FSSYNC give it away */
5461 VChangeState_r(vp, VOL_STATE_SALVAGING);
5463 VCancelReservation_r(vp);
5469 * check whether a salvage needs to be performed on this volume.
5471 * @param[in] vp pointer to volume object
5473 * @return status code
5474 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5475 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5476 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5477 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5478 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5480 * @pre VOL_LOCK is held
5482 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5483 * then a salvage will be requested
5485 * @note this is one of the event handlers called by VCancelReservation_r
5487 * @note the caller must check if the volume needs to be freed after calling
5488 * this; the volume may not have any references or be on any lists after
5489 * we return, and we do not free it
5491 * @see VCancelReservation_r
5493 * @internal volume package internal use only.
5496 VCheckSalvage(Volume * vp)
5498 int ret = VCHECK_SALVAGE_OK;
5500 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5501 if (!vp->salvage.requested) {
5502 return VCHECK_SALVAGE_OK;
5505 return VCHECK_SALVAGE_ASYNC;
5508 /* prevent recursion; some of the code below creates and removes
5509 * lightweight refs, which can call VCheckSalvage */
5510 if (vp->salvage.scheduling) {
5511 return VCHECK_SALVAGE_ASYNC;
5513 vp->salvage.scheduling = 1;
5515 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5516 if (!VOfflineForSalvage_r(vp)) {
5517 vp->salvage.scheduling = 0;
5518 return VCHECK_SALVAGE_FAIL;
5522 if (vp->salvage.requested) {
5523 ret = VScheduleSalvage_r(vp);
5525 vp->salvage.scheduling = 0;
5526 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5531 * request volume salvage.
5533 * @param[out] ec computed client error code
5534 * @param[in] vp volume object pointer
5535 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5536 * @param[in] flags see flags note below
5539 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5540 * not been fully attached
5542 * @pre VOL_LOCK is held.
5544 * @post volume state is changed.
5545 * for fileserver, salvage will be requested once refcount reaches zero.
5547 * @return operation status code
5548 * @retval 0 volume salvage will occur
5549 * @retval 1 volume salvage could not be scheduled
5553 * @note in the fileserver, this call does not synchronously schedule a volume
5554 * salvage. rather, it sets volume state so that when volume refcounts
5555 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5556 * nUsers and nWaiters must be zero.
5558 * @internal volume package internal use only.
5561 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5565 * for DAFS volume utilities that are not supposed to schedule salvages,
5566 * just transition to error state instead
5568 if (!VCanScheduleSalvage()) {
5569 VChangeState_r(vp, VOL_STATE_ERROR);
5574 if (programType != fileServer && !VCanUseFSSYNC()) {
5575 VChangeState_r(vp, VOL_STATE_ERROR);
5580 if (!vp->salvage.requested) {
5581 vp->salvage.requested = 1;
5582 vp->salvage.reason = reason;
5583 vp->stats.last_salvage = FT_ApproxTime();
5585 /* Note that it is not possible for us to reach this point if a
5586 * salvage is already running on this volume (even if the fileserver
5587 * was restarted during the salvage). If a salvage were running, the
5588 * salvager would have write-locked the volume header file, so when
5589 * we tried to lock the volume header, the lock would have failed,
5590 * and we would have failed during attachment prior to calling
5591 * VRequestSalvage. So we know that we can schedule salvages without
5592 * fear of a salvage already running for this volume. */
5594 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5596 /* if we don't need to offline the volume, we can go directly
5597 * to SALVAGING. SALVAGING says the volume is offline and is
5598 * either salvaging or ready to be handed to the salvager.
5599 * SALVAGE_REQ says that we want to salvage the volume, but we
5600 * are waiting for it to go offline first. */
5601 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5602 VChangeState_r(vp, VOL_STATE_SALVAGING);
5604 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5605 if (vp->nUsers == 0) {
5606 /* normally VOfflineForSalvage_r would be called from
5607 * PutVolume et al when nUsers reaches 0, but if
5608 * it's already 0, just do it ourselves, since PutVolume
5609 * isn't going to get called */
5610 VOfflineForSalvage_r(vp);
5613 /* If we are non-fileserver, we're telling the fileserver to
5614 * salvage the vol, so we don't need to give it back separately. */
5615 vp->needsPutBack = 0;
5619 Log("VRequestSalvage: volume %" AFS_VOLID_FMT " online salvaged too many times; forced offline.\n", afs_printable_VolumeId_lu(vp->hashid));
5621 /* make sure neither VScheduleSalvage_r nor
5622 * VUpdateSalvagePriority_r try to schedule another salvage */
5623 vp->salvage.requested = vp->salvage.scheduled = 0;
5625 VChangeState_r(vp, VOL_STATE_ERROR);
5629 if ((flags & VOL_SALVAGE_NO_OFFLINE)) {
5630 /* Here, we free the header for the volume, but make sure to only
5631 * do this if VOL_SALVAGE_NO_OFFLINE is specified. The reason for
5632 * this requires a bit of explanation.
5634 * Normally, the volume header will be freed when the volume goes
5635 * goes offline. However, if VOL_SALVAGE_NO_OFFLINE has been
5636 * specified, the volume was in the process of being attached when
5637 * we discovered that it needed salvaging. Thus, the volume will
5638 * never go offline, since it never went fully online in the first
5639 * place. Specifically, we do not call VOfflineForSalvage_r above,
5640 * and we never get rid of the volume via VPutVolume_r; the volume
5641 * has not been initialized enough for those to work.
5643 * So instead, explicitly free the volume header here. If we do not
5644 * do this, we are wasting a header that some other volume could be
5645 * using, since the header remains attached to the volume. Also if
5646 * we do not free the header here, we end up with a volume where
5647 * nUsers == 0, but the volume has a header that is not on the
5648 * header LRU. Some code expects that all nUsers == 0 volumes have
5649 * their header on the header LRU (or have no header).
5651 * Also note that we must not free the volume header here if
5652 * VOL_SALVAGE_NO_OFFLINE is not set. Since, if
5653 * VOL_SALVAGE_NO_OFFLINE is not set, someone else may have a
5654 * reference to this volume, and they assume they can use the
5655 * volume's header. If we free the volume out from under them, they
5656 * can easily segfault.
5658 FreeVolumeHeader(vp);
5665 * update salvageserver scheduling priority for a volume.
5667 * @param[in] vp pointer to volume object
5669 * @return operation status
5671 * @retval 1 request denied, or SALVSYNC communications failure
5673 * @pre VOL_LOCK is held.
5675 * @post in-core salvage priority counter is incremented. if at least
5676 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5677 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5678 * to update its priority queue. if no salvage is scheduled,
5679 * this function is a no-op.
5681 * @note DAFS fileserver only
5683 * @note this should be called whenever a VGetVolume fails due to a
5684 * pending salvage request
5686 * @todo should set exclusive state and drop glock around salvsync call
5688 * @internal volume package internal use only.
5691 VUpdateSalvagePriority_r(Volume * vp)
5695 #ifdef SALVSYNC_BUILD_CLIENT
5700 now = FT_ApproxTime();
5702 /* update the salvageserver priority queue occasionally so that
5703 * frequently requested volumes get moved to the head of the queue
5705 if ((vp->salvage.scheduled) &&
5706 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5707 code = SALVSYNC_SalvageVolume(vp->hashid,
5708 VPartitionPath(vp->partition),
5713 vp->stats.last_salvage_req = now;
5714 if (code != SYNC_OK) {
5718 #endif /* SALVSYNC_BUILD_CLIENT */
5723 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5725 /* A couple of little helper functions. These return true if we tried to
5726 * use this mechanism to schedule a salvage, false if we haven't tried.
5727 * If we did try a salvage then the results are contained in code.
5731 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5732 #ifdef SALVSYNC_BUILD_CLIENT
5733 if (VCanUseSALVSYNC()) {
5734 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over SALVSYNC\n",
5735 afs_printable_VolumeId_lu(vp->hashid), partName);
5737 /* can't use V_id() since there's no guarantee
5738 * we have the disk data header at this point */
5739 *code = SALVSYNC_SalvageVolume(vp->hashid,
5752 try_FSSYNC(Volume *vp, char *partName, int *code) {
5753 #ifdef FSSYNC_BUILD_CLIENT
5754 if (VCanUseFSSYNC()) {
5755 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over FSSYNC\n",
5756 afs_printable_VolumeId_lu(vp->hashid), partName);
5759 * If we aren't the fileserver, tell the fileserver the volume
5760 * needs to be salvaged. We could directly tell the
5761 * salvageserver, but the fileserver keeps track of some stats
5762 * related to salvages, and handles some other salvage-related
5763 * complications for us.
5765 *code = FSYNC_VolOp(vp->hashid, partName,
5766 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5769 #endif /* FSSYNC_BUILD_CLIENT */
5774 * schedule a salvage with the salvage server or fileserver.
5776 * @param[in] vp pointer to volume object
5778 * @return operation status
5779 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5780 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5781 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5782 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5783 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5786 * @arg VOL_LOCK is held.
5787 * @arg nUsers and nWaiters should be zero.
5789 * @post salvageserver or fileserver is sent a salvage request
5791 * @note If we are the fileserver, the request will be sent to the salvage
5792 * server over SALVSYNC. If we are not the fileserver, the request will be
5793 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5795 * @note the caller must check if the volume needs to be freed after calling
5796 * this; the volume may not have any references or be on any lists after
5797 * we return, and we do not free it
5801 * @internal volume package internal use only.
5804 VScheduleSalvage_r(Volume * vp)
5806 int ret = VCHECK_SALVAGE_SCHEDULED;
5808 VolState state_save;
5809 VThreadOptions_t * thread_opts;
5812 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5814 if (vp->nWaiters || vp->nUsers) {
5815 return VCHECK_SALVAGE_ASYNC;
5818 /* prevent endless salvage,attach,salvage,attach,... loops */
5819 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5820 return VCHECK_SALVAGE_FAIL;
5824 * don't perform salvsync ops on certain threads
5826 thread_opts = pthread_getspecific(VThread_key);
5827 if (thread_opts == NULL) {
5828 thread_opts = &VThread_defaults;
5830 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5831 return VCHECK_SALVAGE_ASYNC;
5834 if (vp->salvage.scheduled) {
5835 return VCHECK_SALVAGE_SCHEDULED;
5838 VCreateReservation_r(vp);
5839 VWaitExclusiveState_r(vp);
5842 * XXX the scheduling process should really be done asynchronously
5843 * to avoid fssync deadlocks
5845 if (vp->salvage.scheduled) {
5846 ret = VCHECK_SALVAGE_SCHEDULED;
5848 /* if we haven't previously scheduled a salvage, do so now
5850 * set the volume to an exclusive state and drop the lock
5851 * around the SALVSYNC call
5853 strlcpy(partName, vp->partition->name, sizeof(partName));
5854 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5857 opr_Verify(try_SALVSYNC(vp, partName, &code)
5858 || try_FSSYNC(vp, partName, &code));
5861 VChangeState_r(vp, state_save);
5863 if (code == SYNC_OK) {
5864 ret = VCHECK_SALVAGE_SCHEDULED;
5865 vp->salvage.scheduled = 1;
5866 vp->stats.last_salvage_req = FT_ApproxTime();
5867 if (VCanUseSALVSYNC()) {
5868 /* don't record these stats for non-fileservers; let the
5869 * fileserver take care of these */
5870 vp->stats.salvages++;
5871 IncUInt64(&VStats.salvages);
5875 case SYNC_BAD_COMMAND:
5876 case SYNC_COM_ERROR:
5877 ret = VCHECK_SALVAGE_FAIL;
5880 ret = VCHECK_SALVAGE_DENIED;
5881 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5882 "denied\n", afs_printable_VolumeId_lu(vp->hashid));
5885 ret = VCHECK_SALVAGE_FAIL;
5886 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5887 "failed\n", afs_printable_VolumeId_lu(vp->hashid));
5890 ret = VCHECK_SALVAGE_FAIL;
5891 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5892 "received unknown protocol error %d\n",
5893 afs_printable_VolumeId_lu(vp->hashid), code);
5897 if (VCanUseFSSYNC()) {
5898 VChangeState_r(vp, VOL_STATE_ERROR);
5903 /* NB: this is cancelling the reservation we obtained above, but we do
5904 * not call VCancelReservation_r, since that may trigger the vp dtor,
5905 * possibly free'ing the vp. We need to keep the vp around after
5906 * this, as the caller may reference vp without any refs. Instead, it
5907 * is the duty of the caller to inspect 'vp' after we return to see if
5908 * needs to be freed. */
5909 opr_Verify(--vp->nWaiters >= 0);
5912 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5914 #ifdef SALVSYNC_BUILD_CLIENT
5917 * connect to the salvageserver SYNC service.
5919 * @return operation status
5923 * @post connection to salvageserver SYNC service established
5925 * @see VConnectSALV_r
5926 * @see VDisconnectSALV
5927 * @see VReconnectSALV
5934 retVal = VConnectSALV_r();
5940 * connect to the salvageserver SYNC service.
5942 * @return operation status
5946 * @pre VOL_LOCK is held.
5948 * @post connection to salvageserver SYNC service established
5951 * @see VDisconnectSALV_r
5952 * @see VReconnectSALV_r
5953 * @see SALVSYNC_clientInit
5955 * @internal volume package internal use only.
5958 VConnectSALV_r(void)
5960 return SALVSYNC_clientInit();
5964 * disconnect from the salvageserver SYNC service.
5966 * @return operation status
5969 * @pre client should have a live connection to the salvageserver
5971 * @post connection to salvageserver SYNC service destroyed
5973 * @see VDisconnectSALV_r
5975 * @see VReconnectSALV
5978 VDisconnectSALV(void)
5981 VDisconnectSALV_r();
5987 * disconnect from the salvageserver SYNC service.
5989 * @return operation status
5993 * @arg VOL_LOCK is held.
5994 * @arg client should have a live connection to the salvageserver.
5996 * @post connection to salvageserver SYNC service destroyed
5998 * @see VDisconnectSALV
5999 * @see VConnectSALV_r
6000 * @see VReconnectSALV_r
6001 * @see SALVSYNC_clientFinis
6003 * @internal volume package internal use only.
6006 VDisconnectSALV_r(void)
6008 return SALVSYNC_clientFinis();
6012 * disconnect and then re-connect to the salvageserver SYNC service.
6014 * @return operation status
6018 * @pre client should have a live connection to the salvageserver
6020 * @post old connection is dropped, and a new one is established
6023 * @see VDisconnectSALV
6024 * @see VReconnectSALV_r
6027 VReconnectSALV(void)
6031 retVal = VReconnectSALV_r();
6037 * disconnect and then re-connect to the salvageserver SYNC service.
6039 * @return operation status
6044 * @arg VOL_LOCK is held.
6045 * @arg client should have a live connection to the salvageserver.
6047 * @post old connection is dropped, and a new one is established
6049 * @see VConnectSALV_r
6050 * @see VDisconnectSALV
6051 * @see VReconnectSALV
6052 * @see SALVSYNC_clientReconnect
6054 * @internal volume package internal use only.
6057 VReconnectSALV_r(void)
6059 return SALVSYNC_clientReconnect();
6061 #endif /* SALVSYNC_BUILD_CLIENT */
6062 #endif /* AFS_DEMAND_ATTACH_FS */
6065 /***************************************************/
6066 /* FSSYNC routines */
6067 /***************************************************/
6069 /* This must be called by any volume utility which needs to run while the
6070 file server is also running. This is separated from VInitVolumePackage2 so
6071 that a utility can fork--and each of the children can independently
6072 initialize communication with the file server */
6073 #ifdef FSSYNC_BUILD_CLIENT
6075 * connect to the fileserver SYNC service.
6077 * @return operation status
6082 * @arg VInit must equal 2.
6083 * @arg Program Type must not be fileserver or salvager.
6085 * @post connection to fileserver SYNC service established
6088 * @see VDisconnectFS
6089 * @see VChildProcReconnectFS
6096 retVal = VConnectFS_r();
6102 * connect to the fileserver SYNC service.
6104 * @return operation status
6109 * @arg VInit must equal 2.
6110 * @arg Program Type must not be fileserver or salvager.
6111 * @arg VOL_LOCK is held.
6113 * @post connection to fileserver SYNC service established
6116 * @see VDisconnectFS_r
6117 * @see VChildProcReconnectFS_r
6119 * @internal volume package internal use only.
6125 opr_Assert((VInit == 2) &&
6126 (programType != fileServer) &&
6127 (programType != salvager));
6128 rc = FSYNC_clientInit();
6136 * disconnect from the fileserver SYNC service.
6139 * @arg client should have a live connection to the fileserver.
6140 * @arg VOL_LOCK is held.
6141 * @arg Program Type must not be fileserver or salvager.
6143 * @post connection to fileserver SYNC service destroyed
6145 * @see VDisconnectFS
6147 * @see VChildProcReconnectFS_r
6149 * @internal volume package internal use only.
6152 VDisconnectFS_r(void)
6154 opr_Assert((programType != fileServer) &&
6155 (programType != salvager));
6156 FSYNC_clientFinis();
6161 * disconnect from the fileserver SYNC service.
6164 * @arg client should have a live connection to the fileserver.
6165 * @arg Program Type must not be fileserver or salvager.
6167 * @post connection to fileserver SYNC service destroyed
6169 * @see VDisconnectFS_r
6171 * @see VChildProcReconnectFS
6182 * connect to the fileserver SYNC service from a child process following a fork.
6184 * @return operation status
6189 * @arg VOL_LOCK is held.
6190 * @arg current FSYNC handle is shared with a parent process
6192 * @post current FSYNC handle is discarded and a new connection to the
6193 * fileserver SYNC service is established
6195 * @see VChildProcReconnectFS
6197 * @see VDisconnectFS_r
6199 * @internal volume package internal use only.
6202 VChildProcReconnectFS_r(void)
6204 return FSYNC_clientChildProcReconnect();
6208 * connect to the fileserver SYNC service from a child process following a fork.
6210 * @return operation status
6214 * @pre current FSYNC handle is shared with a parent process
6216 * @post current FSYNC handle is discarded and a new connection to the
6217 * fileserver SYNC service is established
6219 * @see VChildProcReconnectFS_r
6221 * @see VDisconnectFS
6224 VChildProcReconnectFS(void)
6228 ret = VChildProcReconnectFS_r();
6232 #endif /* FSSYNC_BUILD_CLIENT */
6235 /***************************************************/
6236 /* volume bitmap routines */
6237 /***************************************************/
6240 * Grow the bitmap by the defined increment
6243 VGrowBitmap(struct vnodeIndex *index)
6247 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6248 osi_Assert(bp != NULL);
6250 bp += index->bitmapSize;
6251 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6252 index->bitmapOffset = index->bitmapSize;
6253 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6259 * allocate a vnode bitmap number for the vnode
6261 * @param[out] ec error code
6262 * @param[in] vp volume object pointer
6263 * @param[in] index vnode index number for the vnode
6264 * @param[in] flags flag values described in note
6266 * @note for DAFS, flags parameter controls locking behavior.
6267 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6268 * will create a reservation and block on any other exclusive
6269 * operations. Otherwise, this function assumes the caller
6270 * already has exclusive access to vp, and we just change the
6273 * @pre VOL_LOCK held
6275 * @return bit number allocated
6281 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6282 struct vnodeIndex *index, int flags)
6286 #ifdef AFS_DEMAND_ATTACH_FS
6287 VolState state_save;
6288 #endif /* AFS_DEMAND_ATTACH_FS */
6292 /* This test is probably redundant */
6293 if (!VolumeWriteable(vp)) {
6294 *ec = (bit32) VREADONLY;
6298 #ifdef AFS_DEMAND_ATTACH_FS
6299 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6300 VCreateReservation_r(vp);
6301 VWaitExclusiveState_r(vp);
6303 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6304 #endif /* AFS_DEMAND_ATTACH_FS */
6307 if ((programType == fileServer) && !index->bitmap) {
6309 #ifndef AFS_DEMAND_ATTACH_FS
6310 /* demand attach fs uses the volume state to avoid races.
6311 * specialStatus field is not used at all */
6313 if (vp->specialStatus == VBUSY) {
6314 if (vp->goingOffline) { /* vos dump waiting for the volume to
6315 * go offline. We probably come here
6316 * from AddNewReadableResidency */
6319 while (vp->specialStatus == VBUSY) {
6320 #ifdef AFS_PTHREAD_ENV
6324 #else /* !AFS_PTHREAD_ENV */
6326 #endif /* !AFS_PTHREAD_ENV */
6330 #endif /* !AFS_DEMAND_ATTACH_FS */
6332 if (!index->bitmap) {
6333 #ifndef AFS_DEMAND_ATTACH_FS
6334 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6335 #endif /* AFS_DEMAND_ATTACH_FS */
6336 for (i = 0; i < nVNODECLASSES; i++) {
6337 VGetBitmap_r(ec, vp, i);
6339 #ifdef AFS_DEMAND_ATTACH_FS
6340 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6341 #else /* AFS_DEMAND_ATTACH_FS */
6342 DeleteVolumeFromHashTable(vp);
6343 vp->shuttingDown = 1; /* Let who has it free it. */
6344 vp->specialStatus = 0;
6345 #endif /* AFS_DEMAND_ATTACH_FS */
6349 #ifndef AFS_DEMAND_ATTACH_FS
6351 vp->specialStatus = 0; /* Allow others to have access. */
6352 #endif /* AFS_DEMAND_ATTACH_FS */
6355 #endif /* BITMAP_LATER */
6357 #ifdef AFS_DEMAND_ATTACH_FS
6359 #endif /* AFS_DEMAND_ATTACH_FS */
6360 bp = index->bitmap + index->bitmapOffset;
6361 ep = index->bitmap + index->bitmapSize;
6363 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6365 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6368 o = opr_ffs(~*bp) - 1;
6370 ret = ((bp - index->bitmap) * 8 + o);
6371 #ifdef AFS_DEMAND_ATTACH_FS
6373 #endif /* AFS_DEMAND_ATTACH_FS */
6376 bp += sizeof(bit32) /* i.e. 4 */ ;
6378 /* No bit map entry--must grow bitmap */
6380 bp = index->bitmap + index->bitmapOffset;
6382 ret = index->bitmapOffset * 8;
6383 #ifdef AFS_DEMAND_ATTACH_FS
6385 #endif /* AFS_DEMAND_ATTACH_FS */
6388 #ifdef AFS_DEMAND_ATTACH_FS
6389 VChangeState_r(vp, state_save);
6390 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6391 VCancelReservation_r(vp);
6393 #endif /* AFS_DEMAND_ATTACH_FS */
6398 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6402 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6408 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6409 unsigned bitNumber, int flags)
6411 unsigned int offset;
6415 #ifdef AFS_DEMAND_ATTACH_FS
6416 if (flags & VOL_FREE_BITMAP_WAIT) {
6417 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6418 * state, so ensure we're not in an exclusive volume state when we update
6420 VCreateReservation_r(vp);
6421 VWaitExclusiveState_r(vp);
6428 #endif /* BITMAP_LATER */
6430 offset = bitNumber >> 3;
6431 if (offset >= index->bitmapSize) {
6435 if (offset < index->bitmapOffset)
6436 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6437 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6440 #ifdef AFS_DEMAND_ATTACH_FS
6441 if (flags & VOL_FREE_BITMAP_WAIT) {
6442 VCancelReservation_r(vp);
6445 return; /* make the compiler happy for non-DAFS */
6449 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6453 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6457 /* this function will drop the glock internally.
6458 * for old pthread fileservers, this is safe thanks to vbusy.
6460 * for demand attach fs, caller must have already called
6461 * VCreateReservation_r and VWaitExclusiveState_r */
6463 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6465 StreamHandle_t *file;
6466 afs_sfsize_t nVnodes, size;
6467 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6468 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6469 struct VnodeDiskObject *vnode;
6470 unsigned int unique = 0;
6474 #endif /* BITMAP_LATER */
6475 #ifdef AFS_DEMAND_ATTACH_FS
6476 VolState state_save;
6477 #endif /* AFS_DEMAND_ATTACH_FS */
6481 #ifdef AFS_DEMAND_ATTACH_FS
6482 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6483 #endif /* AFS_DEMAND_ATTACH_FS */
6486 fdP = IH_OPEN(vip->handle);
6487 opr_Assert(fdP != NULL);
6488 file = FDH_FDOPEN(fdP, "r");
6489 opr_Assert(file != NULL);
6490 vnode = malloc(vcp->diskSize);
6491 opr_Assert(vnode != NULL);
6492 size = OS_SIZE(fdP->fd_fd);
6493 opr_Assert(size != -1);
6494 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6496 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6497 * a few files can be created in this volume,
6498 * the whole thing is rounded up to nearest 4
6499 * bytes, because the bit map allocator likes
6502 BitMap = (byte *) calloc(1, vip->bitmapSize);
6503 opr_Assert(BitMap != NULL);
6504 #else /* BITMAP_LATER */
6505 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6506 opr_Assert(vip->bitmap != NULL);
6507 vip->bitmapOffset = 0;
6508 #endif /* BITMAP_LATER */
6509 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6511 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6512 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6514 if (vnode->type != vNull) {
6515 if (vnode->vnodeMagic != vcp->magic) {
6516 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6521 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6522 #else /* BITMAP_LATER */
6523 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6524 #endif /* BITMAP_LATER */
6525 if (unique <= vnode->uniquifier)
6526 unique = vnode->uniquifier + 1;
6528 #ifndef AFS_PTHREAD_ENV
6529 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6532 #endif /* !AFS_PTHREAD_ENV */
6535 if (vp->nextVnodeUnique < unique) {
6536 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6539 /* Paranoia, partly justified--I think fclose after fdopen
6540 * doesn't seem to close fd. In any event, the documentation
6541 * doesn't specify, so it's safer to close it twice.
6549 /* There may have been a racing condition with some other thread, both
6550 * creating the bitmaps for this volume. If the other thread was faster
6551 * the pointer to bitmap should already be filled and we can free ours.
6553 if (vip->bitmap == NULL) {
6554 vip->bitmap = BitMap;
6555 vip->bitmapOffset = 0;
6558 #endif /* BITMAP_LATER */
6559 #ifdef AFS_DEMAND_ATTACH_FS
6560 VChangeState_r(vp, state_save);
6561 #endif /* AFS_DEMAND_ATTACH_FS */
6565 /***************************************************/
6566 /* Volume Path and Volume Number utility routines */
6567 /***************************************************/
6570 * find the first occurrence of a volume header file and return the path.
6572 * @param[out] ec outbound error code
6573 * @param[in] volumeId volume id to find
6574 * @param[out] partitionp pointer to disk partition path string
6575 * @param[out] namep pointer to volume header file name string
6577 * @post path to first occurrence of volume header is returned in partitionp
6578 * and namep, or ec is set accordingly.
6580 * @warning this function is NOT re-entrant -- partitionp and namep point to
6581 * static data segments
6583 * @note if a volume utility inadvertently leaves behind a stale volume header
6584 * on a vice partition, it is possible for callers to get the wrong one,
6585 * depending on the order of the disk partition linked list.
6589 VGetVolumePath(Error * ec, VolumeId volumeId, char **partitionp, char **namep)
6591 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6592 char path[VMAXPATHLEN];
6594 struct DiskPartition64 *dp;
6597 name[0] = OS_DIRSEPC;
6598 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6599 afs_printable_VolumeId_lu(volumeId));
6600 for (dp = DiskPartitionList; dp; dp = dp->next) {
6601 struct afs_stat_st status;
6602 strcpy(path, VPartitionPath(dp));
6604 if (afs_stat(path, &status) == 0) {
6605 strcpy(partition, dp->name);
6612 *partitionp = *namep = NULL;
6614 *partitionp = partition;
6620 * extract a volume number from a volume header filename string.
6622 * @param[in] name volume header filename string
6624 * @return volume number
6626 * @note the string must be of the form VFORMAT. the only permissible
6627 * deviation is a leading OS_DIRSEPC character.
6632 VolumeNumber(char *name)
6634 if (*name == OS_DIRSEPC)
6636 return strtoul(name + 1, NULL, 10);
6640 * compute the volume header filename.
6642 * @param[in] volumeId
6644 * @return volume header filename
6646 * @post volume header filename string is constructed
6648 * @warning this function is NOT re-entrant -- the returned string is
6649 * stored in a static char array. see VolumeExternalName_r
6650 * for a re-entrant equivalent.
6652 * @see VolumeExternalName_r
6654 * @deprecated due to the above re-entrancy warning, this interface should
6655 * be considered deprecated. Please use VolumeExternalName_r
6659 VolumeExternalName(VolumeId volumeId)
6661 static char name[VMAXPATHLEN];
6662 snprintf(name, sizeof name, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6667 * compute the volume header filename.
6669 * @param[in] volumeId
6670 * @param[inout] name array in which to store filename
6671 * @param[in] len length of name array
6673 * @return result code from afs_snprintf
6675 * @see VolumeExternalName
6678 * @note re-entrant equivalent of VolumeExternalName
6681 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6683 return snprintf(name, len, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6687 /***************************************************/
6688 /* Volume Usage Statistics routines */
6689 /***************************************************/
6691 #define OneDay (86400) /* 24 hours' worth of seconds */
6694 Midnight(time_t t) {
6695 struct tm local, *l;
6698 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6699 l = localtime_r(&t, &local);
6705 /* the following is strictly speaking problematic on the
6706 switching day to daylight saving time, after the switch,
6707 as tm_isdst does not match. Similarly, on the looong day when
6708 switching back the OneDay check will not do what naively expected!
6709 The effects are minor, though, and more a matter of interpreting
6711 #ifndef AFS_PTHREAD_ENV
6714 local.tm_hour = local.tm_min=local.tm_sec = 0;
6715 midnight = mktime(&local);
6716 if (midnight != (time_t) -1) return(midnight);
6718 return( (t/OneDay)*OneDay );
6722 /*------------------------------------------------------------------------
6723 * [export] VAdjustVolumeStatistics
6726 * If we've passed midnight, we need to update all the day use
6727 * statistics as well as zeroing the detailed volume statistics
6728 * (if we are implementing them).
6731 * vp : Pointer to the volume structure describing the lucky
6732 * volume being considered for update.
6738 * Nothing interesting.
6742 *------------------------------------------------------------------------*/
6745 VAdjustVolumeStatistics_r(Volume * vp)
6747 unsigned int now = FT_ApproxTime();
6749 if (now - V_dayUseDate(vp) > OneDay) {
6752 ndays = (now - V_dayUseDate(vp)) / OneDay;
6753 for (i = 6; i > ndays - 1; i--)
6754 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6755 for (i = 0; i < ndays - 1 && i < 7; i++)
6756 V_weekUse(vp)[i] = 0;
6758 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6760 V_dayUseDate(vp) = Midnight(now);
6763 * All we need to do is bzero the entire VOL_STATS_BYTES of
6764 * the detailed volume statistics area.
6766 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6769 /*It's been more than a day of collection */
6771 * Always return happily.
6774 } /*VAdjustVolumeStatistics */
6777 VAdjustVolumeStatistics(Volume * vp)
6781 retVal = VAdjustVolumeStatistics_r(vp);
6787 VBumpVolumeUsage_r(Volume * vp)
6789 unsigned int now = FT_ApproxTime();
6790 V_accessDate(vp) = now;
6791 if (now - V_dayUseDate(vp) > OneDay)
6792 VAdjustVolumeStatistics_r(vp);
6794 * Save the volume header image to disk after a threshold of bumps to dayUse,
6795 * at most every usage_rate_limit seconds.
6798 vp->usage_bumps_outstanding++;
6799 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6800 && vp->usage_bumps_next_write <= now) {
6802 vp->usage_bumps_outstanding = 0;
6803 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6804 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6809 VBumpVolumeUsage(Volume * vp)
6812 VBumpVolumeUsage_r(vp);
6817 VSetDiskUsage_r(void)
6819 #ifndef AFS_DEMAND_ATTACH_FS
6820 static int FifteenMinuteCounter = 0;
6824 /* NOTE: Don't attempt to access the partitions list until the
6825 * initialization level indicates that all volumes are attached,
6826 * which implies that all partitions are initialized. */
6827 #ifdef AFS_PTHREAD_ENV
6828 VOL_CV_WAIT(&vol_vinit_cond);
6829 #else /* AFS_PTHREAD_ENV */
6831 #endif /* AFS_PTHREAD_ENV */
6834 VResetDiskUsage_r();
6836 #ifndef AFS_DEMAND_ATTACH_FS
6837 if (++FifteenMinuteCounter == 3) {
6838 FifteenMinuteCounter = 0;
6841 #endif /* !AFS_DEMAND_ATTACH_FS */
6853 /***************************************************/
6854 /* Volume Update List routines */
6855 /***************************************************/
6857 /* The number of minutes that a volume hasn't been updated before the
6858 * "Dont salvage" flag in the volume header will be turned on */
6859 #define SALVAGE_INTERVAL (10*60)
6864 * volume update list functionality has been moved into the VLRU
6865 * the DONT_SALVAGE flag is now set during VLRU demotion
6868 #ifndef AFS_DEMAND_ATTACH_FS
6869 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6870 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6871 static int updateSize = 0; /* number of entries possible */
6872 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6873 #endif /* !AFS_DEMAND_ATTACH_FS */
6876 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6879 vp->updateTime = FT_ApproxTime();
6880 if (V_dontSalvage(vp) == 0)
6882 V_dontSalvage(vp) = 0;
6883 VSyncVolume_r(ec, vp, 0);
6884 #ifdef AFS_DEMAND_ATTACH_FS
6885 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6886 #else /* !AFS_DEMAND_ATTACH_FS */
6889 if (UpdateList == NULL) {
6890 updateSize = UPDATE_LIST_SIZE;
6891 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6893 if (nUpdatedVolumes == updateSize) {
6895 if (updateSize > 524288) {
6896 Log("warning: there is likely a bug in the volume update scanner\n");
6899 UpdateList = realloc(UpdateList,
6900 sizeof(VolumeId) * updateSize);
6903 opr_Assert(UpdateList != NULL);
6904 UpdateList[nUpdatedVolumes++] = V_id(vp);
6905 #endif /* !AFS_DEMAND_ATTACH_FS */
6908 #ifndef AFS_DEMAND_ATTACH_FS
6910 VScanUpdateList(void)
6915 afs_uint32 now = FT_ApproxTime();
6916 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6917 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6919 UpdateList[i - gap] = UpdateList[i];
6921 /* XXX this routine needlessly messes up the Volume LRU by
6922 * breaking the LRU temporal-locality assumptions.....
6923 * we should use a special volume header allocator here */
6924 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6927 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6928 V_dontSalvage(vp) = DONT_SALVAGE;
6929 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6937 #ifndef AFS_PTHREAD_ENV
6939 #endif /* !AFS_PTHREAD_ENV */
6941 nUpdatedVolumes -= gap;
6943 #endif /* !AFS_DEMAND_ATTACH_FS */
6946 /***************************************************/
6947 /* Volume LRU routines */
6948 /***************************************************/
6953 * with demand attach fs, we attempt to soft detach(1)
6954 * volumes which have not been accessed in a long time
6955 * in order to speed up fileserver shutdown
6957 * (1) by soft detach we mean a process very similar
6958 * to VOffline, except the final state of the
6959 * Volume will be VOL_STATE_PREATTACHED, instead
6960 * of the usual VOL_STATE_UNATTACHED
6962 #ifdef AFS_DEMAND_ATTACH_FS
6964 /* implementation is reminiscent of a generational GC
6966 * queue 0 is newly attached volumes. this queue is
6967 * sorted by attach timestamp
6969 * queue 1 is volumes that have been around a bit
6970 * longer than queue 0. this queue is sorted by
6973 * queue 2 is volumes tha have been around the longest.
6974 * this queue is unsorted
6976 * queue 3 is volumes that have been marked as
6977 * candidates for soft detachment. this queue is
6980 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6981 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6984 * definition of a VLRU queue.
6987 volatile struct rx_queue q;
6994 * main VLRU data structure.
6997 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
7000 /** time interval (in seconds) between promotion passes for
7001 * each young generation queue. */
7002 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
7004 /** time interval (in seconds) between soft detach candidate
7005 * scans for each generation queue.
7007 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
7008 * we perform a soft detach pass. */
7009 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
7011 /* scheduler state */
7012 int next_idx; /**< next queue to receive attention */
7013 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
7014 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
7016 int scanner_state; /**< state of scanner thread */
7017 pthread_cond_t cv; /**< state transition CV */
7020 /** global VLRU state */
7021 static struct VLRU volume_LRU;
7024 * defined states for VLRU scanner thread.
7027 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7028 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7029 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7030 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7031 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7032 } vlru_thread_state_t;
7034 /* vlru disk data header stuff */
7035 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7036 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7038 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7039 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7042 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7043 * soft detachment. */
7044 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7046 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7047 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7049 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7050 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7052 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7053 static afs_uint32 VLRU_enabled = 1;
7055 /* queue synchronization routines */
7056 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7057 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7058 static void VLRU_Wait_r(struct VLRU_q * q);
7061 * set VLRU subsystem tunable parameters.
7063 * @param[in] option tunable option to modify
7064 * @param[in] val new value for tunable parameter
7066 * @pre @c VInitVolumePackage2 has not yet been called.
7068 * @post tunable parameter is modified
7072 * @note valid option parameters are:
7073 * @arg @c VLRU_SET_THRESH
7074 * set the period of inactivity after which
7075 * volumes are eligible for soft detachment
7076 * @arg @c VLRU_SET_INTERVAL
7077 * set the time interval between calls
7078 * to the volume LRU "garbage collector"
7079 * @arg @c VLRU_SET_MAX
7080 * set the max number of volumes to deallocate
7084 VLRU_SetOptions(int option, afs_uint32 val)
7086 if (option == VLRU_SET_THRESH) {
7087 VLRU_offline_thresh = val;
7088 } else if (option == VLRU_SET_INTERVAL) {
7089 VLRU_offline_interval = val;
7090 } else if (option == VLRU_SET_MAX) {
7091 VLRU_offline_max = val;
7092 } else if (option == VLRU_SET_ENABLED) {
7095 VLRU_ComputeConstants();
7099 * compute VLRU internal timing parameters.
7101 * @post VLRU scanner thread internal timing parameters are computed
7103 * @note computes internal timing parameters based upon user-modifiable
7104 * tunable parameters.
7108 * @internal volume package internal use only.
7111 VLRU_ComputeConstants(void)
7113 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7115 /* compute the candidate scan interval */
7116 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7118 /* compute the promotion intervals */
7119 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7120 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7123 /* compute the gen 0 scan interval */
7124 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7126 /* compute the gen 0 scan interval */
7127 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7132 * initialize VLRU subsystem.
7134 * @pre this function has not yet been called
7136 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7140 * @internal volume package internal use only.
7146 pthread_attr_t attrs;
7149 if (!VLRU_enabled) {
7150 Log("VLRU: disabled\n");
7154 /* initialize each of the VLRU queues */
7155 for (i = 0; i < VLRU_QUEUES; i++) {
7156 queue_Init(&volume_LRU.q[i]);
7157 volume_LRU.q[i].len = 0;
7158 volume_LRU.q[i].busy = 0;
7159 opr_cv_init(&volume_LRU.q[i].cv);
7162 /* setup the timing constants */
7163 VLRU_ComputeConstants();
7165 /* XXX put inside log level check? */
7166 Log("VLRU: starting scanner with the following configuration parameters:\n");
7167 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7168 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7169 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7170 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7171 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7172 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7174 /* start up the VLRU scanner */
7175 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7176 if (programType == fileServer) {
7177 opr_cv_init(&volume_LRU.cv);
7178 opr_Verify(pthread_attr_init(&attrs) == 0);
7179 opr_Verify(pthread_attr_setdetachstate(&attrs,
7180 PTHREAD_CREATE_DETACHED) == 0);
7181 opr_Verify(pthread_create(&tid, &attrs,
7182 &VLRU_ScannerThread, NULL) == 0);
7187 * initialize the VLRU-related fields of a newly allocated volume object.
7189 * @param[in] vp pointer to volume object
7192 * @arg @c VOL_LOCK is held.
7193 * @arg volume object is not on a VLRU queue.
7195 * @post VLRU fields are initialized to indicate that volume object is not
7196 * currently registered with the VLRU subsystem
7200 * @internal volume package interal use only.
7203 VLRU_Init_Node_r(Volume * vp)
7208 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7209 vp->vlru.idx = VLRU_QUEUE_INVALID;
7213 * add a volume object to a VLRU queue.
7215 * @param[in] vp pointer to volume object
7218 * @arg @c VOL_LOCK is held.
7219 * @arg caller MUST hold a lightweight ref on @p vp.
7220 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7222 * @post the volume object is added to the appropriate VLRU queue
7224 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7225 * then the volume is added to that queue. Otherwise, the value
7226 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7227 * volume is added to the NEW generation queue.
7229 * @note @c VOL_LOCK may be dropped internally
7231 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7232 * during the add operation, and is restored to the previous
7233 * state prior to return.
7237 * @internal volume package internal use only.
7240 VLRU_Add_r(Volume * vp)
7243 VolState state_save;
7248 if (queue_IsOnQueue(&vp->vlru))
7251 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7254 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7255 idx = VLRU_QUEUE_NEW;
7258 VLRU_Wait_r(&volume_LRU.q[idx]);
7260 /* repeat check since VLRU_Wait_r may have dropped
7262 if (queue_IsNotOnQueue(&vp->vlru)) {
7264 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7265 volume_LRU.q[idx].len++;
7266 V_attachFlags(vp) |= VOL_ON_VLRU;
7267 vp->stats.last_promote = FT_ApproxTime();
7270 VChangeState_r(vp, state_save);
7274 * delete a volume object from a VLRU queue.
7276 * @param[in] vp pointer to volume object
7279 * @arg @c VOL_LOCK is held.
7280 * @arg caller MUST hold a lightweight ref on @p vp.
7281 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7283 * @post volume object is removed from the VLRU queue
7285 * @note @c VOL_LOCK may be dropped internally
7289 * @todo We should probably set volume state to something exlcusive
7290 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7292 * @internal volume package internal use only.
7295 VLRU_Delete_r(Volume * vp)
7302 if (queue_IsNotOnQueue(&vp->vlru))
7308 if (idx == VLRU_QUEUE_INVALID)
7310 VLRU_Wait_r(&volume_LRU.q[idx]);
7311 } while (idx != vp->vlru.idx);
7313 /* now remove from the VLRU and update
7314 * the appropriate counter */
7315 queue_Remove(&vp->vlru);
7316 volume_LRU.q[idx].len--;
7317 vp->vlru.idx = VLRU_QUEUE_INVALID;
7318 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7322 * tell the VLRU subsystem that a volume was just accessed.
7324 * @param[in] vp pointer to volume object
7327 * @arg @c VOL_LOCK is held
7328 * @arg caller MUST hold a lightweight ref on @p vp
7329 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7331 * @post volume VLRU access statistics are updated. If the volume was on
7332 * the VLRU soft detach candidate queue, it is moved to the NEW
7335 * @note @c VOL_LOCK may be dropped internally
7339 * @internal volume package internal use only.
7342 VLRU_UpdateAccess_r(Volume * vp)
7344 Volume * rvp = NULL;
7349 if (queue_IsNotOnQueue(&vp->vlru))
7352 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7354 /* update the access timestamp */
7355 vp->stats.last_get = FT_ApproxTime();
7358 * if the volume is on the soft detach candidate
7359 * list, we need to safely move it back to a
7360 * regular generation. this has to be done
7361 * carefully so we don't race against the scanner
7365 /* if this volume is on the soft detach candidate queue,
7366 * then grab exclusive access to the necessary queues */
7367 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7369 VCreateReservation_r(rvp);
7371 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7372 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7373 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7374 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7377 /* make sure multiple threads don't race to update */
7378 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7379 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7383 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7384 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7385 VCancelReservation_r(rvp);
7390 * switch a volume between two VLRU queues.
7392 * @param[in] vp pointer to volume object
7393 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7394 * @param[in] append controls whether the volume will be appended or
7395 * prepended to the queue. A nonzero value means it will
7396 * be appended; zero means it will be prepended.
7398 * @pre The new (and old, if applicable) queue(s) must either be owned
7399 * exclusively by the calling thread for asynchronous manipulation,
7400 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7401 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7402 * for further details of the queue asynchronous processing mechanism.
7404 * @post If the volume object was already on a VLRU queue, it is
7405 * removed from the queue. Depending on the value of the append
7406 * parameter, the volume object is either appended or prepended
7407 * to the VLRU queue referenced by the new_idx parameter.
7411 * @see VLRU_BeginExclusive_r
7412 * @see VLRU_EndExclusive_r
7415 * @internal volume package internal use only.
7418 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7420 if (queue_IsNotOnQueue(&vp->vlru))
7423 queue_Remove(&vp->vlru);
7424 volume_LRU.q[vp->vlru.idx].len--;
7426 /* put the volume back on the correct generational queue */
7428 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7430 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7433 volume_LRU.q[new_idx].len++;
7434 vp->vlru.idx = new_idx;
7438 * VLRU background thread.
7440 * The VLRU Scanner Thread is responsible for periodically scanning through
7441 * each VLRU queue looking for volumes which should be moved to another
7442 * queue, or soft detached.
7444 * @param[in] args unused thread arguments parameter
7446 * @return unused thread return value
7447 * @retval NULL always
7449 * @internal volume package internal use only.
7452 VLRU_ScannerThread(void * args)
7454 afs_uint32 now, min_delay, delay;
7455 int i, min_idx, min_op, overdue, state;
7457 /* set t=0 for promotion cycle to be
7458 * fileserver startup */
7459 now = FT_ApproxTime();
7460 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7461 volume_LRU.last_promotion[i] = now;
7464 /* don't start the scanner until VLRU_offline_thresh
7465 * plus a small delay for VInitVolumePackage2 to finish
7468 sleep(VLRU_offline_thresh + 60);
7470 /* set t=0 for scan cycle to be now */
7471 now = FT_ApproxTime();
7472 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7473 volume_LRU.last_scan[i] = now;
7477 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7478 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7481 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7482 /* check to see if we've been asked to pause */
7483 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7484 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7485 opr_cv_broadcast(&volume_LRU.cv);
7487 VOL_CV_WAIT(&volume_LRU.cv);
7488 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7491 /* scheduling can happen outside the glock */
7494 /* figure out what is next on the schedule */
7496 /* figure out a potential schedule for the new generation first */
7498 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7501 if (min_delay > volume_LRU.scan_interval[0]) {
7502 /* unsigned overflow -- we're overdue to run this scan */
7507 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7509 i = VLRU_QUEUE_CANDIDATE;
7510 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7511 if (delay < min_delay) {
7515 if (delay > volume_LRU.scan_interval[i]) {
7516 /* unsigned overflow -- we're overdue to run this scan */
7523 /* if we're still not overdue for something, figure out schedules for promotions */
7524 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7525 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7526 if (delay < min_delay) {
7531 if (delay > volume_LRU.promotion_interval[i]) {
7532 /* unsigned overflow -- we're overdue to run this promotion */
7541 /* sleep as needed */
7546 /* do whatever is next */
7549 VLRU_Promote_r(min_idx);
7550 VLRU_Demote_r(min_idx+1);
7552 VLRU_Scan_r(min_idx);
7554 now = FT_ApproxTime();
7557 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7559 /* signal that scanner is down */
7560 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7561 opr_cv_broadcast(&volume_LRU.cv);
7567 * promote volumes from one VLRU generation to the next.
7569 * This routine scans a VLRU generation looking for volumes which are
7570 * eligible to be promoted to the next generation. All volumes which
7571 * meet the eligibility requirement are promoted.
7573 * Promotion eligibility is based upon meeting both of the following
7576 * @arg The volume has been accessed since the last promotion:
7577 * @c (vp->stats.last_get >= vp->stats.last_promote)
7578 * @arg The last promotion occurred at least
7579 * @c volume_LRU.promotion_interval[idx] seconds ago
7581 * As a performance optimization, promotions are "globbed". In other
7582 * words, we promote arbitrarily large contiguous sublists of elements
7585 * @param[in] idx VLRU queue index to scan
7589 * @internal VLRU internal use only.
7592 VLRU_Promote_r(int idx)
7594 int len, chaining, promote;
7595 afs_uint32 now, thresh;
7596 struct rx_queue *qp, *nqp;
7597 Volume * vp, *start = NULL, *end = NULL;
7599 /* get exclusive access to two chains, and drop the glock */
7600 VLRU_Wait_r(&volume_LRU.q[idx]);
7601 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7602 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7603 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7606 thresh = volume_LRU.promotion_interval[idx];
7607 now = FT_ApproxTime();
7610 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7611 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7612 promote = (((vp->stats.last_promote + thresh) <= now) &&
7613 (vp->stats.last_get >= vp->stats.last_promote));
7621 /* promote and prepend chain */
7622 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7636 /* promote and prepend */
7637 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7641 volume_LRU.q[idx].len -= len;
7642 volume_LRU.q[idx+1].len += len;
7645 /* release exclusive access to the two chains */
7647 volume_LRU.last_promotion[idx] = now;
7648 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7649 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7652 /* run the demotions */
7654 VLRU_Demote_r(int idx)
7657 int len, chaining, demote;
7658 afs_uint32 now, thresh;
7659 struct rx_queue *qp, *nqp;
7660 Volume * vp, *start = NULL, *end = NULL;
7661 Volume ** salv_flag_vec = NULL;
7662 int salv_vec_offset = 0;
7664 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7666 /* get exclusive access to two chains, and drop the glock */
7667 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7668 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7669 VLRU_Wait_r(&volume_LRU.q[idx]);
7670 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7673 /* no big deal if this allocation fails */
7674 if (volume_LRU.q[idx].len) {
7675 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7678 now = FT_ApproxTime();
7679 thresh = volume_LRU.promotion_interval[idx-1];
7682 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7683 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7684 demote = (((vp->stats.last_promote + thresh) <= now) &&
7685 (vp->stats.last_get < (now - thresh)));
7687 /* we now do volume update list DONT_SALVAGE flag setting during
7688 * demotion passes */
7689 if (salv_flag_vec &&
7690 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7692 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7693 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7694 salv_flag_vec[salv_vec_offset++] = vp;
7695 VCreateReservation_r(vp);
7704 /* demote and append chain */
7705 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7719 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7723 volume_LRU.q[idx].len -= len;
7724 volume_LRU.q[idx-1].len += len;
7727 /* release exclusive access to the two chains */
7729 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7730 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7732 /* now go back and set the DONT_SALVAGE flags as appropriate */
7733 if (salv_flag_vec) {
7735 for (i = 0; i < salv_vec_offset; i++) {
7736 vp = salv_flag_vec[i];
7737 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7738 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7739 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7742 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7743 V_dontSalvage(vp) = DONT_SALVAGE;
7744 VUpdateVolume_r(&ec, vp, 0);
7748 VCancelReservation_r(vp);
7750 free(salv_flag_vec);
7754 /* run a pass of the VLRU GC scanner */
7756 VLRU_Scan_r(int idx)
7758 afs_uint32 now, thresh;
7759 struct rx_queue *qp, *nqp;
7763 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7765 /* gain exclusive access to the idx VLRU */
7766 VLRU_Wait_r(&volume_LRU.q[idx]);
7767 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7769 if (idx != VLRU_QUEUE_CANDIDATE) {
7770 /* gain exclusive access to the candidate VLRU */
7771 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7772 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7775 now = FT_ApproxTime();
7776 thresh = now - VLRU_offline_thresh;
7778 /* perform candidate selection and soft detaching */
7779 if (idx == VLRU_QUEUE_CANDIDATE) {
7780 /* soft detach some volumes from the candidate pool */
7784 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7785 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7786 if (i >= VLRU_offline_max) {
7789 /* check timestamp to see if it's a candidate for soft detaching */
7790 if (vp->stats.last_get <= thresh) {
7792 if (VCheckSoftDetach(vp, thresh))
7798 /* scan for volumes to become soft detach candidates */
7799 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7800 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7802 /* check timestamp to see if it's a candidate for soft detaching */
7803 if (vp->stats.last_get <= thresh) {
7804 VCheckSoftDetachCandidate(vp, thresh);
7807 if (!(i&0x7f)) { /* lock coarsening optimization */
7815 /* relinquish exclusive access to the VLRU chains */
7819 volume_LRU.last_scan[idx] = now;
7820 if (idx != VLRU_QUEUE_CANDIDATE) {
7821 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7823 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7826 /* check whether volume is safe to soft detach
7827 * caller MUST NOT hold a ref count on vp */
7829 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7833 if (vp->nUsers || vp->nWaiters)
7836 if (vp->stats.last_get <= thresh) {
7837 ret = VSoftDetachVolume_r(vp, thresh);
7843 /* check whether volume should be made a
7844 * soft detach candidate */
7846 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7849 if (vp->nUsers || vp->nWaiters)
7854 opr_Assert(idx == VLRU_QUEUE_NEW);
7856 if (vp->stats.last_get <= thresh) {
7857 /* move to candidate pool */
7858 queue_Remove(&vp->vlru);
7859 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7860 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7861 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7862 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7870 /* begin exclusive access on VLRU */
7872 VLRU_BeginExclusive_r(struct VLRU_q * q)
7874 opr_Assert(q->busy == 0);
7878 /* end exclusive access on VLRU */
7880 VLRU_EndExclusive_r(struct VLRU_q * q)
7882 opr_Assert(q->busy);
7884 opr_cv_broadcast(&q->cv);
7887 /* wait for another thread to end exclusive access on VLRU */
7889 VLRU_Wait_r(struct VLRU_q * q)
7892 VOL_CV_WAIT(&q->cv);
7897 * volume soft detach
7899 * caller MUST NOT hold a ref count on vp */
7901 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7906 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7908 ts_save = vp->stats.last_get;
7909 if (ts_save > thresh)
7912 if (vp->nUsers || vp->nWaiters)
7915 if (VIsExclusiveState(V_attachState(vp))) {
7919 switch (V_attachState(vp)) {
7920 case VOL_STATE_UNATTACHED:
7921 case VOL_STATE_PREATTACHED:
7922 case VOL_STATE_ERROR:
7923 case VOL_STATE_GOING_OFFLINE:
7924 case VOL_STATE_SHUTTING_DOWN:
7925 case VOL_STATE_SALVAGING:
7926 case VOL_STATE_DELETED:
7927 volume_LRU.q[vp->vlru.idx].len--;
7929 /* create and cancel a reservation to
7930 * give the volume an opportunity to
7932 VCreateReservation_r(vp);
7933 queue_Remove(&vp->vlru);
7934 vp->vlru.idx = VLRU_QUEUE_INVALID;
7935 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7936 VCancelReservation_r(vp);
7942 /* hold the volume and take it offline.
7943 * no need for reservations, as VHold_r
7944 * takes care of that internally. */
7945 if (VHold_r(vp) == 0) {
7946 /* vhold drops the glock, so now we should
7947 * check to make sure we aren't racing against
7948 * other threads. if we are racing, offlining vp
7949 * would be wasteful, and block the scanner for a while
7953 (vp->shuttingDown) ||
7954 (vp->goingOffline) ||
7955 (vp->stats.last_get != ts_save)) {
7956 /* looks like we're racing someone else. bail */
7960 /* pull it off the VLRU */
7961 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7962 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7963 queue_Remove(&vp->vlru);
7964 vp->vlru.idx = VLRU_QUEUE_INVALID;
7965 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7967 /* take if offline */
7968 VOffline_r(vp, "volume has been soft detached");
7970 /* invalidate the volume header cache */
7971 FreeVolumeHeader(vp);
7974 IncUInt64(&VStats.soft_detaches);
7975 vp->stats.soft_detaches++;
7977 /* put in pre-attached state so demand
7978 * attacher can work on it */
7979 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7985 #endif /* AFS_DEMAND_ATTACH_FS */
7988 /***************************************************/
7989 /* Volume Header Cache routines */
7990 /***************************************************/
7993 * volume header cache.
7995 struct volume_hdr_LRU_t volume_hdr_LRU;
7998 * initialize the volume header cache.
8000 * @param[in] howMany number of header cache entries to preallocate
8002 * @pre VOL_LOCK held. Function has never been called before.
8004 * @post howMany cache entries are allocated, initialized, and added
8005 * to the LRU list. Header cache statistics are initialized.
8007 * @note only applicable to fileServer program type. Should only be
8008 * called once during volume package initialization.
8010 * @internal volume package internal use only.
8013 VInitVolumeHeaderCache(afs_uint32 howMany)
8015 struct volHeader *hp;
8016 if (programType != fileServer)
8018 queue_Init(&volume_hdr_LRU);
8019 volume_hdr_LRU.stats.free = 0;
8020 volume_hdr_LRU.stats.used = howMany;
8021 volume_hdr_LRU.stats.attached = 0;
8022 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8023 opr_Assert(hp != NULL);
8026 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8027 * to ensure they have the right values
8029 ReleaseVolumeHeader(hp++);
8032 /* get a volume header off of the volume header LRU.
8034 * @return volume header
8035 * @retval NULL no usable volume header is available on the LRU
8037 * @pre VOL_LOCK held
8039 * @post for DAFS, if the returned header is associated with a volume, that
8040 * volume is NOT in an exclusive state
8042 * @internal volume package internal use only.
8044 #ifdef AFS_DEMAND_ATTACH_FS
8045 static struct volHeader*
8046 GetVolHeaderFromLRU(void)
8048 struct volHeader *hd = NULL, *qh, *nqh;
8049 /* Usually, a volume in an exclusive state will not have its header on
8050 * the LRU. However, it is possible for this to occur when a salvage
8051 * request is received over FSSYNC, and possibly in other corner cases.
8052 * So just skip over headers whose volumes are in an exclusive state. We
8053 * could VWaitExclusiveState_r instead, but not waiting is faster and
8055 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8056 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8064 #else /* AFS_DEMAND_ATTACH_FS */
8065 static struct volHeader*
8066 GetVolHeaderFromLRU(void)
8068 struct volHeader *hd = NULL;
8069 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8070 hd = queue_First(&volume_hdr_LRU, volHeader);
8075 #endif /* !AFS_DEMAND_ATTACH_FS */
8078 * get a volume header and attach it to the volume object.
8080 * @param[in] vp pointer to volume object
8082 * @return cache entry status
8083 * @retval 0 volume header was newly attached; cache data is invalid
8084 * @retval 1 volume header was previously attached; cache data is valid
8086 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8088 * @post volume header attached to volume object. if necessary, header cache
8089 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8091 * @note VOL_LOCK may be dropped
8093 * @warning this interface does not load header data from disk. it merely
8094 * attaches a header object to the volume object, and may sync the old
8095 * header cache data out to disk in the process.
8097 * @internal volume package internal use only.
8100 GetVolumeHeader(Volume * vp)
8103 struct volHeader *hd;
8105 static int everLogged = 0;
8107 #ifdef AFS_DEMAND_ATTACH_FS
8108 VolState vp_save = 0, back_save = 0;
8110 /* XXX debug 9/19/05 we've apparently got
8111 * a ref counting bug somewhere that's
8112 * breaking the nUsers == 0 => header on LRU
8114 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8115 Log("nUsers == 0, but header not on LRU\n");
8120 old = (vp->header != NULL); /* old == volume already has a header */
8122 if (programType != fileServer) {
8123 /* for volume utilities, we allocate volHeaders as needed */
8125 hd = calloc(1, sizeof(*vp->header));
8126 opr_Assert(hd != NULL);
8129 #ifdef AFS_DEMAND_ATTACH_FS
8130 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8134 /* for the fileserver, we keep a volume header cache */
8136 /* the header we previously dropped in the lru is
8137 * still available. pull it off the lru and return */
8140 opr_Assert(hd->back == vp);
8141 #ifdef AFS_DEMAND_ATTACH_FS
8142 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8145 hd = GetVolHeaderFromLRU();
8147 /* LRU is empty, so allocate a new volHeader
8148 * this is probably indicative of a leak, so let the user know */
8149 hd = calloc(1, sizeof(struct volHeader));
8150 opr_Assert(hd != NULL);
8152 Log("****Allocated more volume headers, probably leak****\n");
8155 volume_hdr_LRU.stats.free++;
8158 /* this header used to belong to someone else.
8159 * we'll need to check if the header needs to
8160 * be sync'd out to disk */
8162 #ifdef AFS_DEMAND_ATTACH_FS
8163 /* GetVolHeaderFromLRU had better not give us back a header
8164 * with a volume in exclusive state... */
8165 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8168 if (hd->diskstuff.inUse) {
8169 /* volume was in use, so we'll need to sync
8170 * its header to disk */
8172 #ifdef AFS_DEMAND_ATTACH_FS
8173 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8174 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8175 VCreateReservation_r(hd->back);
8179 WriteVolumeHeader_r(&error, hd->back);
8180 /* Ignore errors; catch them later */
8182 #ifdef AFS_DEMAND_ATTACH_FS
8187 hd->back->header = NULL;
8188 #ifdef AFS_DEMAND_ATTACH_FS
8189 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8191 if (hd->diskstuff.inUse) {
8192 VChangeState_r(hd->back, back_save);
8193 VCancelReservation_r(hd->back);
8194 VChangeState_r(vp, vp_save);
8198 volume_hdr_LRU.stats.attached++;
8202 #ifdef AFS_DEMAND_ATTACH_FS
8203 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8206 volume_hdr_LRU.stats.free--;
8207 volume_hdr_LRU.stats.used++;
8209 IncUInt64(&VStats.hdr_gets);
8210 #ifdef AFS_DEMAND_ATTACH_FS
8211 IncUInt64(&vp->stats.hdr_gets);
8212 vp->stats.last_hdr_get = FT_ApproxTime();
8219 * make sure volume header is attached and contains valid cache data.
8221 * @param[out] ec outbound error code
8222 * @param[in] vp pointer to volume object
8224 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8226 * @post header cache entry attached, and loaded with valid data, or
8227 * *ec is nonzero, and the header is released back into the LRU.
8229 * @internal volume package internal use only.
8232 LoadVolumeHeader(Error * ec, Volume * vp)
8234 #ifdef AFS_DEMAND_ATTACH_FS
8235 VolState state_save;
8239 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8240 IncUInt64(&VStats.hdr_loads);
8241 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8244 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8245 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8247 IncUInt64(&vp->stats.hdr_loads);
8248 now = FT_ApproxTime();
8252 V_attachFlags(vp) |= VOL_HDR_LOADED;
8253 vp->stats.last_hdr_load = now;
8255 VChangeState_r(vp, state_save);
8257 #else /* AFS_DEMAND_ATTACH_FS */
8259 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8260 IncUInt64(&VStats.hdr_loads);
8262 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8263 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8266 #endif /* AFS_DEMAND_ATTACH_FS */
8268 /* maintain (nUsers==0) => header in LRU invariant */
8269 FreeVolumeHeader(vp);
8274 * release a header cache entry back into the LRU list.
8276 * @param[in] hd pointer to volume header cache object
8278 * @pre VOL_LOCK held.
8280 * @post header cache object appended onto end of LRU list.
8282 * @note only applicable to fileServer program type.
8284 * @note used to place a header cache entry back into the
8285 * LRU pool without invalidating it as a cache entry.
8287 * @internal volume package internal use only.
8290 ReleaseVolumeHeader(struct volHeader *hd)
8292 if (programType != fileServer)
8294 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8296 queue_Append(&volume_hdr_LRU, hd);
8297 #ifdef AFS_DEMAND_ATTACH_FS
8299 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8302 volume_hdr_LRU.stats.free++;
8303 volume_hdr_LRU.stats.used--;
8307 * free/invalidate a volume header cache entry.
8309 * @param[in] vp pointer to volume object
8311 * @pre VOL_LOCK is held.
8313 * @post For fileserver, header cache entry is returned to LRU, and it is
8314 * invalidated as a cache entry. For volume utilities, the header
8315 * cache entry is freed.
8317 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8318 * whenever it is necessary to invalidate the header cache entry.
8320 * @see ReleaseVolumeHeader
8322 * @internal volume package internal use only.
8325 FreeVolumeHeader(Volume * vp)
8327 struct volHeader *hd = vp->header;
8330 if (programType == fileServer) {
8331 ReleaseVolumeHeader(hd);
8336 #ifdef AFS_DEMAND_ATTACH_FS
8337 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8339 volume_hdr_LRU.stats.attached--;
8344 /***************************************************/
8345 /* Volume Hash Table routines */
8346 /***************************************************/
8349 * set size of volume object hash table.
8351 * @param[in] logsize log(2) of desired hash table size
8353 * @return operation status
8355 * @retval -1 failure
8357 * @pre MUST be called prior to VInitVolumePackage2
8359 * @post Volume Hash Table will have 2^logsize buckets
8362 VSetVolHashSize(int logsize)
8364 /* 64 to 268435456 hash buckets seems like a reasonable range */
8365 if ((logsize < 6 ) || (logsize > 28)) {
8370 VolumeHashTable.Size = opr_jhash_size(logsize);
8371 VolumeHashTable.Mask = opr_jhash_mask(logsize);
8373 /* we can't yet support runtime modification of this
8374 * parameter. we'll need a configuration rwlock to
8375 * make runtime modification feasible.... */
8382 * initialize dynamic data structures for volume hash table.
8384 * @post hash table is allocated, and fields are initialized.
8386 * @internal volume package internal use only.
8389 VInitVolumeHash(void)
8393 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8394 sizeof(VolumeHashChainHead));
8395 opr_Assert(VolumeHashTable.Table != NULL);
8397 for (i=0; i < VolumeHashTable.Size; i++) {
8398 queue_Init(&VolumeHashTable.Table[i]);
8399 #ifdef AFS_DEMAND_ATTACH_FS
8400 opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8401 #endif /* AFS_DEMAND_ATTACH_FS */
8406 * add a volume object to the hash table.
8408 * @param[in] vp pointer to volume object
8409 * @param[in] hashid hash of volume id
8411 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8414 * @post volume is added to hash chain.
8416 * @internal volume package internal use only.
8418 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8419 * asynchronous hash chain reordering to finish.
8422 AddVolumeToHashTable(Volume * vp, VolumeId hashid)
8424 VolumeHashChainHead * head;
8426 if (queue_IsOnQueue(vp))
8429 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8431 #ifdef AFS_DEMAND_ATTACH_FS
8432 /* wait for the hash chain to become available */
8435 V_attachFlags(vp) |= VOL_IN_HASH;
8436 vp->chainCacheCheck = ++head->cacheCheck;
8437 #endif /* AFS_DEMAND_ATTACH_FS */
8440 vp->hashid = hashid;
8441 queue_Append(head, vp);
8445 * delete a volume object from the hash table.
8447 * @param[in] vp pointer to volume object
8449 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8452 * @post volume is removed from hash chain.
8454 * @internal volume package internal use only.
8456 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8457 * asynchronous hash chain reordering to finish.
8460 DeleteVolumeFromHashTable(Volume * vp)
8462 VolumeHashChainHead * head;
8464 if (!queue_IsOnQueue(vp))
8467 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8469 #ifdef AFS_DEMAND_ATTACH_FS
8470 /* wait for the hash chain to become available */
8473 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8475 #endif /* AFS_DEMAND_ATTACH_FS */
8479 /* do NOT reset hashid to zero, as the online
8480 * salvager package may need to know the volume id
8481 * after the volume is removed from the hash */
8485 * lookup a volume object in the hash table given a volume id.
8487 * @param[out] ec error code return
8488 * @param[in] volumeId volume id
8489 * @param[in] hint volume object which we believe could be the correct
8492 * @return volume object pointer
8493 * @retval NULL no such volume id is registered with the hash table.
8495 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8498 * @post volume object with the given id is returned. volume object and
8499 * hash chain access statistics are updated. hash chain may have
8502 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8503 * asynchronous hash chain reordering operation to finish, or
8504 * in order for us to perform an asynchronous chain reordering.
8506 * @note Hash chain reorderings occur when the access count for the
8507 * volume object being looked up exceeds the sum of the previous
8508 * node's (the node ahead of it in the hash chain linked list)
8509 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8511 * @note For DAFS, the hint parameter allows us to short-circuit if the
8512 * cacheCheck fields match between the hash chain head and the
8513 * hint volume object.
8516 VLookupVolume_r(Error * ec, VolumeId volumeId, Volume * hint)
8520 #ifdef AFS_DEMAND_ATTACH_FS
8523 VolumeHashChainHead * head;
8526 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8528 #ifdef AFS_DEMAND_ATTACH_FS
8529 /* wait for the hash chain to become available */
8532 /* check to see if we can short circuit without walking the hash chain */
8533 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8534 IncUInt64(&hint->stats.hash_short_circuits);
8537 #endif /* AFS_DEMAND_ATTACH_FS */
8539 /* someday we need to either do per-chain locks, RWlocks,
8540 * or both for volhash access.
8541 * (and move to a data structure with better cache locality) */
8543 /* search the chain for this volume id */
8544 for(queue_Scan(head, vp, np, Volume)) {
8546 if (vp->hashid == volumeId) {
8551 if (queue_IsEnd(head, vp)) {
8555 #ifdef AFS_DEMAND_ATTACH_FS
8556 /* update hash chain statistics */
8559 FillInt64(lks, 0, looks);
8560 AddUInt64(head->looks, lks, &head->looks);
8561 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8562 IncUInt64(&head->gets);
8567 IncUInt64(&vp->stats.hash_lookups);
8569 /* for demand attach fileserver, we permit occasional hash chain reordering
8570 * so that frequently looked up volumes move towards the head of the chain */
8571 pp = queue_Prev(vp, Volume);
8572 if (!queue_IsEnd(head, pp)) {
8573 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8574 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8575 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8576 VReorderHash_r(head, pp, vp);
8580 /* update the short-circuit cache check */
8581 vp->chainCacheCheck = head->cacheCheck;
8583 #endif /* AFS_DEMAND_ATTACH_FS */
8588 #ifdef AFS_DEMAND_ATTACH_FS
8589 /* perform volume hash chain reordering.
8591 * advance a subchain beginning at vp ahead of
8592 * the adjacent subchain ending at pp */
8594 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8596 Volume *tp, *np, *lp;
8597 afs_uint64 move_thresh;
8599 /* this should never be called if the chain is already busy, so
8600 * no need to wait for other exclusive chain ops to finish */
8602 /* this is a rather heavy set of operations,
8603 * so let's set the chain busy flag and drop
8605 VHashBeginExclusive_r(head);
8608 /* scan forward in the chain from vp looking for the last element
8609 * in the chain we want to advance */
8610 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8611 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8612 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8613 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8617 lp = queue_Prev(tp, Volume);
8619 /* scan backwards from pp to determine where to splice and
8620 * insert the subchain we're advancing */
8621 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8622 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8626 tp = queue_Next(tp, Volume);
8628 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8629 queue_MoveChainBefore(tp,vp,lp);
8632 IncUInt64(&VStats.hash_reorders);
8634 IncUInt64(&head->reorders);
8636 /* wake up any threads waiting for the hash chain */
8637 VHashEndExclusive_r(head);
8641 /* demand-attach fs volume hash
8642 * asynchronous exclusive operations */
8645 * begin an asynchronous exclusive operation on a volume hash chain.
8647 * @param[in] head pointer to volume hash chain head object
8649 * @pre VOL_LOCK held. hash chain is quiescent.
8651 * @post hash chain marked busy.
8653 * @note this interface is used in conjunction with VHashEndExclusive_r and
8654 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8655 * volume hash chain. Its main use case is hash chain reordering, which
8656 * has the potential to be a highly latent operation.
8658 * @see VHashEndExclusive_r
8663 * @internal volume package internal use only.
8666 VHashBeginExclusive_r(VolumeHashChainHead * head)
8668 opr_Assert(head->busy == 0);
8673 * relinquish exclusive ownership of a volume hash chain.
8675 * @param[in] head pointer to volume hash chain head object
8677 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8679 * @post hash chain is marked quiescent. threads awaiting use of
8680 * chain are awakened.
8682 * @see VHashBeginExclusive_r
8687 * @internal volume package internal use only.
8690 VHashEndExclusive_r(VolumeHashChainHead * head)
8692 opr_Assert(head->busy);
8694 opr_cv_broadcast(&head->chain_busy_cv);
8698 * wait for all asynchronous operations on a hash chain to complete.
8700 * @param[in] head pointer to volume hash chain head object
8702 * @pre VOL_LOCK held.
8704 * @post hash chain object is quiescent.
8706 * @see VHashBeginExclusive_r
8707 * @see VHashEndExclusive_r
8711 * @note This interface should be called before any attempt to
8712 * traverse the hash chain. It is permissible for a thread
8713 * to gain exclusive access to the chain, and then perform
8714 * latent operations on the chain asynchronously wrt the
8717 * @warning if waiting is necessary, VOL_LOCK is dropped
8719 * @internal volume package internal use only.
8722 VHashWait_r(VolumeHashChainHead * head)
8724 while (head->busy) {
8725 VOL_CV_WAIT(&head->chain_busy_cv);
8728 #endif /* AFS_DEMAND_ATTACH_FS */
8731 /***************************************************/
8732 /* Volume by Partition List routines */
8733 /***************************************************/
8736 * demand attach fileserver adds a
8737 * linked list of volumes to each
8738 * partition object, thus allowing
8739 * for quick enumeration of all
8740 * volumes on a partition
8743 #ifdef AFS_DEMAND_ATTACH_FS
8745 * add a volume to its disk partition VByPList.
8747 * @param[in] vp pointer to volume object
8749 * @pre either the disk partition VByPList is owned exclusively
8750 * by the calling thread, or the list is quiescent and
8753 * @post volume is added to disk partition VByPList
8757 * @warning it is the caller's responsibility to ensure list
8760 * @see VVByPListWait_r
8761 * @see VVByPListBeginExclusive_r
8762 * @see VVByPListEndExclusive_r
8764 * @internal volume package internal use only.
8767 AddVolumeToVByPList_r(Volume * vp)
8769 if (queue_IsNotOnQueue(&vp->vol_list)) {
8770 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8771 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8772 vp->partition->vol_list.len++;
8777 * delete a volume from its disk partition VByPList.
8779 * @param[in] vp pointer to volume object
8781 * @pre either the disk partition VByPList is owned exclusively
8782 * by the calling thread, or the list is quiescent and
8785 * @post volume is removed from the disk partition VByPList
8789 * @warning it is the caller's responsibility to ensure list
8792 * @see VVByPListWait_r
8793 * @see VVByPListBeginExclusive_r
8794 * @see VVByPListEndExclusive_r
8796 * @internal volume package internal use only.
8799 DeleteVolumeFromVByPList_r(Volume * vp)
8801 if (queue_IsOnQueue(&vp->vol_list)) {
8802 queue_Remove(&vp->vol_list);
8803 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8804 vp->partition->vol_list.len--;
8809 * begin an asynchronous exclusive operation on a VByPList.
8811 * @param[in] dp pointer to disk partition object
8813 * @pre VOL_LOCK held. VByPList is quiescent.
8815 * @post VByPList marked busy.
8817 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8818 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8821 * @see VVByPListEndExclusive_r
8822 * @see VVByPListWait_r
8826 * @internal volume package internal use only.
8828 /* take exclusive control over the list */
8830 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8832 opr_Assert(dp->vol_list.busy == 0);
8833 dp->vol_list.busy = 1;
8837 * relinquish exclusive ownership of a VByPList.
8839 * @param[in] dp pointer to disk partition object
8841 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8843 * @post VByPList is marked quiescent. threads awaiting use of
8844 * the list are awakened.
8846 * @see VVByPListBeginExclusive_r
8847 * @see VVByPListWait_r
8851 * @internal volume package internal use only.
8854 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8856 opr_Assert(dp->vol_list.busy);
8857 dp->vol_list.busy = 0;
8858 opr_cv_broadcast(&dp->vol_list.cv);
8862 * wait for all asynchronous operations on a VByPList to complete.
8864 * @param[in] dp pointer to disk partition object
8866 * @pre VOL_LOCK is held.
8868 * @post disk partition's VByP list is quiescent
8872 * @note This interface should be called before any attempt to
8873 * traverse the VByPList. It is permissible for a thread
8874 * to gain exclusive access to the list, and then perform
8875 * latent operations on the list asynchronously wrt the
8878 * @warning if waiting is necessary, VOL_LOCK is dropped
8880 * @see VVByPListEndExclusive_r
8881 * @see VVByPListBeginExclusive_r
8883 * @internal volume package internal use only.
8886 VVByPListWait_r(struct DiskPartition64 * dp)
8888 while (dp->vol_list.busy) {
8889 VOL_CV_WAIT(&dp->vol_list.cv);
8892 #endif /* AFS_DEMAND_ATTACH_FS */
8894 /***************************************************/
8895 /* Volume Cache Statistics routines */
8896 /***************************************************/
8899 VPrintCacheStats_r(void)
8901 struct VnodeClassInfo *vcp;
8902 vcp = &VnodeClassInfo[vLarge];
8903 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);
8904 vcp = &VnodeClassInfo[vSmall];
8905 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);
8906 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8907 "%"AFS_INT64_FMT" replacements\n",
8908 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8912 VPrintCacheStats(void)
8915 VPrintCacheStats_r();
8919 #ifdef AFS_DEMAND_ATTACH_FS
8921 UInt64ToDouble(afs_uint64 * x)
8923 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8925 SplitInt64(*x, h, l);
8926 return (((double)h) * c32) + ((double) l);
8930 DoubleToPrintable(double x, char * buf, int len)
8932 static double billion = 1000000000.0;
8935 y[0] = (afs_uint32) (x / (billion * billion));
8936 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8937 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8940 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8942 snprintf(buf, len, "%d%09d", y[1], y[2]);
8944 snprintf(buf, len, "%d", y[2]);
8950 struct VLRUExtStatsEntry {
8954 struct VLRUExtStats {
8960 } queue_info[VLRU_QUEUE_INVALID];
8961 struct VLRUExtStatsEntry * vec;
8965 * add a 256-entry fudge factor onto the vector in case state changes
8966 * out from under us.
8968 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8971 * collect extended statistics for the VLRU subsystem.
8973 * @param[out] stats pointer to stats structure to be populated
8974 * @param[in] nvols number of volumes currently known to exist
8976 * @pre VOL_LOCK held
8978 * @post stats->vec allocated and populated
8980 * @return operation status
8985 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8987 afs_uint32 cur, idx, len;
8988 struct rx_queue * qp, * nqp;
8990 struct VLRUExtStatsEntry * vec;
8992 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8993 vec = stats->vec = calloc(len,
8994 sizeof(struct VLRUExtStatsEntry));
9000 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9001 VLRU_Wait_r(&volume_LRU.q[idx]);
9002 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
9005 stats->queue_info[idx].start = cur;
9007 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
9009 /* out of space in vec */
9012 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
9013 vec[cur].volid = vp->hashid;
9017 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9020 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9028 #define ENUMTOSTRING(en) #en
9029 #define ENUMCASE(en) \
9030 case en: return ENUMTOSTRING(en)
9033 vlru_idx_to_string(int idx)
9036 ENUMCASE(VLRU_QUEUE_NEW);
9037 ENUMCASE(VLRU_QUEUE_MID);
9038 ENUMCASE(VLRU_QUEUE_OLD);
9039 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9040 ENUMCASE(VLRU_QUEUE_HELD);
9041 ENUMCASE(VLRU_QUEUE_INVALID);
9043 return "**UNKNOWN**";
9048 VPrintExtendedCacheStats_r(int flags)
9051 afs_uint32 vol_sum = 0;
9058 struct stats looks, gets, reorders, len;
9059 struct stats ch_looks, ch_gets, ch_reorders;
9061 VolumeHashChainHead *head;
9063 struct VLRUExtStats vlru_stats;
9065 /* zero out stats */
9066 memset(&looks, 0, sizeof(struct stats));
9067 memset(&gets, 0, sizeof(struct stats));
9068 memset(&reorders, 0, sizeof(struct stats));
9069 memset(&len, 0, sizeof(struct stats));
9070 memset(&ch_looks, 0, sizeof(struct stats));
9071 memset(&ch_gets, 0, sizeof(struct stats));
9072 memset(&ch_reorders, 0, sizeof(struct stats));
9074 for (i = 0; i < VolumeHashTable.Size; i++) {
9075 head = &VolumeHashTable.Table[i];
9078 VHashBeginExclusive_r(head);
9081 ch_looks.sum = UInt64ToDouble(&head->looks);
9082 ch_gets.sum = UInt64ToDouble(&head->gets);
9083 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9085 /* update global statistics */
9087 looks.sum += ch_looks.sum;
9088 gets.sum += ch_gets.sum;
9089 reorders.sum += ch_reorders.sum;
9090 len.sum += (double)head->len;
9091 vol_sum += head->len;
9094 len.min = (double) head->len;
9095 len.max = (double) head->len;
9096 looks.min = ch_looks.sum;
9097 looks.max = ch_looks.sum;
9098 gets.min = ch_gets.sum;
9099 gets.max = ch_gets.sum;
9100 reorders.min = ch_reorders.sum;
9101 reorders.max = ch_reorders.sum;
9103 if (((double)head->len) < len.min)
9104 len.min = (double) head->len;
9105 if (((double)head->len) > len.max)
9106 len.max = (double) head->len;
9107 if (ch_looks.sum < looks.min)
9108 looks.min = ch_looks.sum;
9109 else if (ch_looks.sum > looks.max)
9110 looks.max = ch_looks.sum;
9111 if (ch_gets.sum < gets.min)
9112 gets.min = ch_gets.sum;
9113 else if (ch_gets.sum > gets.max)
9114 gets.max = ch_gets.sum;
9115 if (ch_reorders.sum < reorders.min)
9116 reorders.min = ch_reorders.sum;
9117 else if (ch_reorders.sum > reorders.max)
9118 reorders.max = ch_reorders.sum;
9122 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9123 /* compute detailed per-chain stats */
9124 struct stats hdr_loads, hdr_gets;
9125 double v_looks, v_loads, v_gets;
9127 /* initialize stats with data from first element in chain */
9128 vp = queue_First(head, Volume);
9129 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9130 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9131 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9132 ch_gets.min = ch_gets.max = v_looks;
9133 hdr_loads.min = hdr_loads.max = v_loads;
9134 hdr_gets.min = hdr_gets.max = v_gets;
9135 hdr_loads.sum = hdr_gets.sum = 0;
9137 vp = queue_Next(vp, Volume);
9139 /* pull in stats from remaining elements in chain */
9140 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9141 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9142 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9143 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9145 hdr_loads.sum += v_loads;
9146 hdr_gets.sum += v_gets;
9148 if (v_looks < ch_gets.min)
9149 ch_gets.min = v_looks;
9150 else if (v_looks > ch_gets.max)
9151 ch_gets.max = v_looks;
9153 if (v_loads < hdr_loads.min)
9154 hdr_loads.min = v_loads;
9155 else if (v_loads > hdr_loads.max)
9156 hdr_loads.max = v_loads;
9158 if (v_gets < hdr_gets.min)
9159 hdr_gets.min = v_gets;
9160 else if (v_gets > hdr_gets.max)
9161 hdr_gets.max = v_gets;
9164 /* compute per-chain averages */
9165 ch_gets.avg = ch_gets.sum / ((double)head->len);
9166 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9167 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9169 /* dump per-chain stats */
9170 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9172 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9173 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9174 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9175 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9176 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9177 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9178 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9179 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9180 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9181 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9182 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9183 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9184 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9185 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9186 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9187 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9188 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9189 } else if (flags & VOL_STATS_PER_CHAIN) {
9190 /* dump simple per-chain stats */
9191 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9193 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9194 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9195 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9199 VHashEndExclusive_r(head);
9204 /* compute global averages */
9205 len.avg = len.sum / ((double)VolumeHashTable.Size);
9206 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9207 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9208 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9210 /* dump global stats */
9211 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9212 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9213 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9214 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9215 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9216 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9217 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9218 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9219 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9220 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9221 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9222 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9223 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9224 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9225 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9226 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9227 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9228 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9229 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9230 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9231 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9233 /* print extended disk related statistics */
9235 struct DiskPartition64 * diskP;
9236 afs_uint32 vol_count[VOLMAXPARTS+1];
9237 byte part_exists[VOLMAXPARTS+1];
9241 memset(vol_count, 0, sizeof(vol_count));
9242 memset(part_exists, 0, sizeof(part_exists));
9246 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9248 vol_count[id] = diskP->vol_list.len;
9249 part_exists[id] = 1;
9253 for (i = 0; i <= VOLMAXPARTS; i++) {
9254 if (part_exists[i]) {
9255 /* XXX while this is currently safe, it is a violation
9256 * of the VGetPartitionById_r interface contract. */
9257 diskP = VGetPartitionById_r(i, 0);
9259 Log("Partition %s has %d online volumes\n",
9260 VPartitionPath(diskP), diskP->vol_list.len);
9267 /* print extended VLRU statistics */
9268 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9269 afs_uint32 idx, cur, lpos;
9274 Log("VLRU State Dump:\n\n");
9276 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9277 Log("\t%s:\n", vlru_idx_to_string(idx));
9280 for (cur = vlru_stats.queue_info[idx].start;
9281 cur < vlru_stats.queue_info[idx].len;
9283 line[lpos++] = vlru_stats.vec[cur].volid;
9285 Log("\t\t%u, %u, %u, %u, %u,\n",
9286 line[0], line[1], line[2], line[3], line[4]);
9295 Log("\t\t%u, %u, %u, %u, %u\n",
9296 line[0], line[1], line[2], line[3], line[4]);
9301 free(vlru_stats.vec);
9308 VPrintExtendedCacheStats(int flags)
9311 VPrintExtendedCacheStats_r(flags);
9314 #endif /* AFS_DEMAND_ATTACH_FS */
9317 VCanScheduleSalvage(void)
9319 return vol_opts.canScheduleSalvage;
9325 return vol_opts.canUseFSSYNC;
9329 VCanUseSALVSYNC(void)
9331 return vol_opts.canUseSALVSYNC;
9335 VCanUnsafeAttach(void)
9337 return vol_opts.unsafe_attach;