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 <afs/afsint.h>
42 #include <rx/rx_queue.h>
45 #if !defined(AFS_SGI_ENV)
48 #else /* AFS_OSF_ENV */
49 #ifdef AFS_VFSINCL_ENV
52 #include <sys/fs/ufs_fs.h>
54 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
55 #include <ufs/ufs/dinode.h>
56 #include <ufs/ffs/fs.h>
61 #else /* AFS_VFSINCL_ENV */
62 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
65 #endif /* AFS_VFSINCL_ENV */
66 #endif /* AFS_OSF_ENV */
67 #endif /* AFS_SGI_ENV */
68 #endif /* !AFS_NT40_ENV */
76 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
78 #include <sys/mnttab.h>
79 #include <sys/mntent.h>
85 #if defined(AFS_SGI_ENV)
88 #ifndef AFS_LINUX20_ENV
89 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
92 #endif /* AFS_SGI_ENV */
94 #endif /* AFS_HPUX_ENV */
98 #include <afs/errors.h>
101 #include <afs/afssyscalls.h>
103 #include <afs/afsutil.h>
104 #include "daemon_com.h"
106 #include "salvsync.h"
109 #include "partition.h"
110 #include "volume_inline.h"
115 #ifdef AFS_PTHREAD_ENV
116 pthread_mutex_t vol_glock_mutex;
117 pthread_mutex_t vol_trans_mutex;
118 pthread_cond_t vol_put_volume_cond;
119 pthread_cond_t vol_sleep_cond;
120 pthread_cond_t vol_init_attach_cond;
121 pthread_cond_t vol_vinit_cond;
122 int vol_attach_threads = 1;
123 #endif /* AFS_PTHREAD_ENV */
125 /* start-time configurable I/O parameters */
126 ih_init_params vol_io_params;
128 #ifdef AFS_DEMAND_ATTACH_FS
129 pthread_mutex_t vol_salvsync_mutex;
132 * Set this to 1 to disallow SALVSYNC communication in all threads; used
133 * during shutdown, since the salvageserver may have gone away.
135 static volatile sig_atomic_t vol_disallow_salvsync = 0;
136 #endif /* AFS_DEMAND_ATTACH_FS */
139 * has VShutdown_r been called / is VShutdown_r running?
141 static int vol_shutting_down = 0;
144 extern void *calloc(), *realloc();
147 /* Forward declarations */
148 static Volume *attach2(Error * ec, VolId volumeId, char *path,
149 struct DiskPartition64 *partp, Volume * vp,
150 int isbusy, int mode, int *acheckedOut);
151 static void ReallyFreeVolume(Volume * vp);
152 #ifdef AFS_DEMAND_ATTACH_FS
153 static void FreeVolume(Volume * vp);
154 #else /* !AFS_DEMAND_ATTACH_FS */
155 #define FreeVolume(vp) ReallyFreeVolume(vp)
156 static void VScanUpdateList(void);
157 #endif /* !AFS_DEMAND_ATTACH_FS */
158 static void VInitVolumeHeaderCache(afs_uint32 howMany);
159 static int GetVolumeHeader(Volume * vp);
160 static void ReleaseVolumeHeader(struct volHeader *hd);
161 static void FreeVolumeHeader(Volume * vp);
162 static void AddVolumeToHashTable(Volume * vp, int hashid);
163 static void DeleteVolumeFromHashTable(Volume * vp);
165 static int VHold(Volume * vp);
167 static int VHold_r(Volume * vp);
168 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
169 static void VReleaseVolumeHandles_r(Volume * vp);
170 static void VCloseVolumeHandles_r(Volume * vp);
171 static void LoadVolumeHeader(Error * ec, Volume * vp);
172 static int VCheckOffline(Volume * vp);
173 static int VCheckDetach(Volume * vp);
174 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
175 Volume * hint, const struct timespec *ts);
177 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
178 * defined when not linked with vice, XXXX */
179 ProgramType programType; /* The type of program using the package */
180 static VolumePackageOptions vol_opts;
182 /* extended volume package statistics */
185 #ifdef VOL_LOCK_DEBUG
186 pthread_t vol_glock_holder = 0;
190 /* this parameter needs to be tunable at runtime.
191 * 128 was really inadequate for largish servers -- at 16384 volumes this
192 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
193 * talk about bad spatial locality...
195 * an AVL or splay tree might work a lot better, but we'll just increase
196 * the default hash table size for now
198 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
199 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
200 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
203 * turn volume hash chains into partially ordered lists.
204 * when the threshold is exceeded between two adjacent elements,
205 * perform a chain rebalancing operation.
207 * keep the threshold high in order to keep cache line invalidates
208 * low "enough" on SMPs
210 #define VOLUME_HASH_REORDER_THRESHOLD 200
213 * when possible, don't just reorder single elements, but reorder
214 * entire chains of elements at once. a chain of elements that
215 * exceed the element previous to the pivot by at least CHAIN_THRESH
216 * accesses are moved in front of the chain whose elements have at
217 * least CHAIN_THRESH less accesses than the pivot element
219 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
221 #include "rx/rx_queue.h"
224 VolumeHashTable_t VolumeHashTable = {
225 DEFAULT_VOLUME_HASH_SIZE,
226 DEFAULT_VOLUME_HASH_MASK,
231 static void VInitVolumeHash(void);
235 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
239 afs_int32 ffs_tmp = x;
243 for (ffs_i = 1;; ffs_i++) {
250 #endif /* !AFS_HAVE_FFS */
252 #ifdef AFS_PTHREAD_ENV
254 * disk partition queue element
256 typedef struct diskpartition_queue_t {
257 struct rx_queue queue; /**< queue header */
258 struct DiskPartition64 *diskP; /**< disk partition table entry */
259 } diskpartition_queue_t;
261 #ifndef AFS_DEMAND_ATTACH_FS
263 typedef struct vinitvolumepackage_thread_t {
264 struct rx_queue queue;
265 pthread_cond_t thread_done_cv;
266 int n_threads_complete;
267 } vinitvolumepackage_thread_t;
268 static void * VInitVolumePackageThread(void * args);
270 #else /* !AFS_DEMAND_ATTTACH_FS */
271 #define VINIT_BATCH_MAX_SIZE 512
274 * disk partition work queue
276 struct partition_queue {
277 struct rx_queue head; /**< diskpartition_queue_t queue */
278 pthread_mutex_t mutex;
283 * volumes parameters for preattach
285 struct volume_init_batch {
286 struct rx_queue queue; /**< queue header */
287 int thread; /**< posting worker thread */
288 int last; /**< indicates thread is done */
289 int size; /**< number of volume ids in batch */
290 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
294 * volume parameters work queue
296 struct volume_init_queue {
297 struct rx_queue head; /**< volume_init_batch queue */
298 pthread_mutex_t mutex;
303 * volume init worker thread parameters
305 struct vinitvolumepackage_thread_param {
306 int nthreads; /**< total number of worker threads */
307 int thread; /**< thread number for this worker thread */
308 struct partition_queue *pq; /**< queue partitions to scan */
309 struct volume_init_queue *vq; /**< queue of volume to preattach */
312 static void *VInitVolumePackageThread(void *args);
313 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
314 static VolId VInitNextVolumeId(DIR *dirp);
315 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
317 #endif /* !AFS_DEMAND_ATTACH_FS */
318 #endif /* AFS_PTHREAD_ENV */
320 #ifndef AFS_DEMAND_ATTACH_FS
321 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
322 int * nAttached, int * nUnattached);
323 #endif /* AFS_DEMAND_ATTACH_FS */
326 #ifdef AFS_DEMAND_ATTACH_FS
327 /* demand attach fileserver extensions */
330 * in the future we will support serialization of VLRU state into the fs_state
333 * these structures are the beginning of that effort
335 struct VLRU_DiskHeader {
336 struct versionStamp stamp; /* magic and structure version number */
337 afs_uint32 mtime; /* time of dump to disk */
338 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
341 struct VLRU_DiskEntry {
342 afs_uint32 vid; /* volume ID */
343 afs_uint32 idx; /* generation */
344 afs_uint32 last_get; /* timestamp of last get */
347 struct VLRU_StartupQueue {
348 struct VLRU_DiskEntry * entry;
353 typedef struct vshutdown_thread_t {
355 pthread_mutex_t lock;
357 pthread_cond_t master_cv;
359 int n_threads_complete;
361 int schedule_version;
364 byte n_parts_done_pass;
365 byte part_thread_target[VOLMAXPARTS+1];
366 byte part_done_pass[VOLMAXPARTS+1];
367 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
368 int stats[4][VOLMAXPARTS+1];
369 } vshutdown_thread_t;
370 static void * VShutdownThread(void * args);
373 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
374 static int VCheckFree(Volume * vp);
377 static void AddVolumeToVByPList_r(Volume * vp);
378 static void DeleteVolumeFromVByPList_r(Volume * vp);
379 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
380 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
381 static void VVByPListWait_r(struct DiskPartition64 * dp);
383 /* online salvager */
385 VCHECK_SALVAGE_OK = 0, /**< no pending salvage */
386 VCHECK_SALVAGE_SCHEDULED = 1, /**< salvage has been scheduled */
387 VCHECK_SALVAGE_ASYNC = 2, /**< salvage being scheduled */
388 VCHECK_SALVAGE_DENIED = 3, /**< salvage not scheduled; denied */
389 VCHECK_SALVAGE_FAIL = 4 /**< salvage not scheduled; failed */
391 static int VCheckSalvage(Volume * vp);
392 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
393 static int VScheduleSalvage_r(Volume * vp);
396 /* Volume hash table */
397 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
398 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
399 static void VHashEndExclusive_r(VolumeHashChainHead * head);
400 static void VHashWait_r(VolumeHashChainHead * head);
403 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
404 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
405 struct rx_queue ** idx);
406 static void ShutdownController(vshutdown_thread_t * params);
407 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
410 static void VLRU_ComputeConstants(void);
411 static void VInitVLRU(void);
412 static void VLRU_Init_Node_r(Volume * vp);
413 static void VLRU_Add_r(Volume * vp);
414 static void VLRU_Delete_r(Volume * vp);
415 static void VLRU_UpdateAccess_r(Volume * vp);
416 static void * VLRU_ScannerThread(void * args);
417 static void VLRU_Scan_r(int idx);
418 static void VLRU_Promote_r(int idx);
419 static void VLRU_Demote_r(int idx);
420 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
423 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
424 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
425 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
428 pthread_key_t VThread_key;
429 VThreadOptions_t VThread_defaults = {
430 0 /**< allow salvsync */
432 #endif /* AFS_DEMAND_ATTACH_FS */
435 struct Lock vol_listLock; /* Lock obtained when listing volumes:
436 * prevents a volume from being missed
437 * if the volume is attached during a
441 /* Common message used when the volume goes off line */
442 char *VSalvageMessage =
443 "Files in this volume are currently unavailable; call operations";
445 int VInit; /* 0 - uninitialized,
446 * 1 - initialized but not all volumes have been attached,
447 * 2 - initialized and all volumes have been attached,
448 * 3 - initialized, all volumes have been attached, and
449 * VConnectFS() has completed. */
451 static int vinit_attach_abort = 0;
453 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
454 * used to stamp volume headers and in-core
455 * vnodes. When the volume goes on-line the
456 * vnode will be invalidated
457 * access only with VOL_LOCK held */
462 /***************************************************/
463 /* Startup routines */
464 /***************************************************/
466 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
467 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
468 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
472 * assign default values to a VolumePackageOptions struct.
474 * Always call this on a VolumePackageOptions struct first, then set any
475 * specific options you want, then call VInitVolumePackage2.
477 * @param[in] pt caller's program type
478 * @param[out] opts volume package options
481 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
483 opts->nLargeVnodes = opts->nSmallVnodes = 5;
486 opts->canScheduleSalvage = 0;
487 opts->canUseFSSYNC = 0;
488 opts->canUseSALVSYNC = 0;
490 opts->interrupt_rxcall = NULL;
491 opts->offline_timeout = -1;
492 opts->offline_shutdown_timeout = -1;
493 opts->usage_threshold = 128;
494 opts->usage_rate_limit = 5;
497 opts->unsafe_attach = 1;
498 #else /* !FAST_RESTART */
499 opts->unsafe_attach = 0;
500 #endif /* !FAST_RESTART */
504 opts->canScheduleSalvage = 1;
505 opts->canUseSALVSYNC = 1;
509 opts->canUseFSSYNC = 1;
513 opts->nLargeVnodes = 0;
514 opts->nSmallVnodes = 0;
516 opts->canScheduleSalvage = 1;
517 opts->canUseFSSYNC = 1;
527 * Set VInit to a certain value, and signal waiters.
529 * @param[in] value the value to set VInit to
534 VSetVInit_r(int value)
537 opr_cv_broadcast(&vol_vinit_cond);
541 VLogOfflineTimeout(const char *type, afs_int32 timeout)
547 Log("VInitVolumePackage: Interrupting clients accessing %s "
548 "immediately\n", type);
550 Log("VInitVolumePackage: Interrupting clients accessing %s "
551 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
556 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
558 int errors = 0; /* Number of errors while finding vice partitions. */
563 #ifndef AFS_PTHREAD_ENV
564 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
565 Log("VInitVolumePackage: offline_timeout and/or "
566 "offline_shutdown_timeout was specified, but the volume package "
567 "does not support these for LWP builds\n");
571 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
572 VLogOfflineTimeout("volumes going offline during shutdown",
573 opts->offline_shutdown_timeout);
575 memset(&VStats, 0, sizeof(VStats));
576 VStats.hdr_cache_size = 200;
578 VInitPartitionPackage();
580 #ifdef AFS_DEMAND_ATTACH_FS
581 if (programType == fileServer) {
584 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
586 opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
589 opr_mutex_init(&vol_glock_mutex);
590 opr_mutex_init(&vol_trans_mutex);
591 opr_cv_init(&vol_put_volume_cond);
592 opr_cv_init(&vol_sleep_cond);
593 opr_cv_init(&vol_init_attach_cond);
594 opr_cv_init(&vol_vinit_cond);
595 #ifndef AFS_PTHREAD_ENV
597 #endif /* AFS_PTHREAD_ENV */
598 Lock_Init(&vol_listLock);
600 srandom(time(0)); /* For VGetVolumeInfo */
602 #ifdef AFS_DEMAND_ATTACH_FS
603 opr_mutex_init(&vol_salvsync_mutex);
604 #endif /* AFS_DEMAND_ATTACH_FS */
606 /* Ok, we have done enough initialization that fileserver can
607 * start accepting calls, even though the volumes may not be
608 * available just yet.
612 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
613 if (programType == salvageServer) {
616 #endif /* AFS_DEMAND_ATTACH_FS */
617 #ifdef FSSYNC_BUILD_SERVER
618 if (programType == fileServer) {
622 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
623 if (VCanUseSALVSYNC()) {
624 /* establish a connection to the salvager at this point */
625 opr_Verify(VConnectSALV() != 0);
627 #endif /* AFS_DEMAND_ATTACH_FS */
629 if (opts->volcache > VStats.hdr_cache_size)
630 VStats.hdr_cache_size = opts->volcache;
631 VInitVolumeHeaderCache(VStats.hdr_cache_size);
633 VInitVnodes(vLarge, opts->nLargeVnodes);
634 VInitVnodes(vSmall, opts->nSmallVnodes);
637 errors = VAttachPartitions();
641 if (programType != fileServer) {
642 errors = VInitAttachVolumes(programType);
648 #ifdef FSSYNC_BUILD_CLIENT
649 if (VCanUseFSSYNC()) {
651 #ifdef AFS_DEMAND_ATTACH_FS
652 if (programType == salvageServer) {
653 Log("Unable to connect to file server; aborted\n");
656 #endif /* AFS_DEMAND_ATTACH_FS */
657 Log("Unable to connect to file server; will retry at need\n");
660 #endif /* FSSYNC_BUILD_CLIENT */
665 #if !defined(AFS_PTHREAD_ENV)
667 * Attach volumes in vice partitions
669 * @param[in] pt calling program type
672 * @note This is the original, non-threaded version of attach parititions.
674 * @post VInit state is 2
677 VInitAttachVolumes(ProgramType pt)
679 opr_Assert(VInit==1);
680 if (pt == fileServer) {
681 struct DiskPartition64 *diskP;
682 /* Attach all the volumes in this partition */
683 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
684 int nAttached = 0, nUnattached = 0;
685 opr_Verify(VAttachVolumesByPartition(diskP,
686 &nAttached, &nUnattached)
691 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
692 LWP_NoYieldSignal(VInitAttachVolumes);
696 #endif /* !AFS_PTHREAD_ENV */
698 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
700 * Attach volumes in vice partitions
702 * @param[in] pt calling program type
705 * @note Threaded version of attach parititions.
707 * @post VInit state is 2
710 VInitAttachVolumes(ProgramType pt)
712 opr_Assert(VInit==1);
713 if (pt == fileServer) {
714 struct DiskPartition64 *diskP;
715 struct vinitvolumepackage_thread_t params;
716 struct diskpartition_queue_t * dpq;
717 int i, threads, parts;
719 pthread_attr_t attrs;
721 opr_cv_init(¶ms.thread_done_cv);
723 params.n_threads_complete = 0;
725 /* create partition work queue */
726 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
727 dpq = malloc(sizeof(struct diskpartition_queue_t));
728 opr_Assert(dpq != NULL);
730 queue_Append(¶ms,dpq);
733 threads = min(parts, vol_attach_threads);
736 /* spawn off a bunch of initialization threads */
737 opr_Verify(pthread_attr_init(&attrs) == 0);
738 opr_Verify(pthread_attr_setdetachstate(&attrs,
739 PTHREAD_CREATE_DETACHED)
742 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
743 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
747 for (i=0; i < threads; i++) {
750 opr_Verify(pthread_create(&tid, &attrs,
751 &VInitVolumePackageThread,
753 AFS_SIGSET_RESTORE();
756 while(params.n_threads_complete < threads) {
757 VOL_CV_WAIT(¶ms.thread_done_cv);
761 opr_Verify(pthread_attr_destroy(&attrs) == 0);
763 /* if we're only going to run one init thread, don't bother creating
765 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
766 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
769 VInitVolumePackageThread(¶ms);
772 opr_cv_destroy(¶ms.thread_done_cv);
775 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
776 opr_cv_broadcast(&vol_init_attach_cond);
782 VInitVolumePackageThread(void * args) {
784 struct DiskPartition64 *diskP;
785 struct vinitvolumepackage_thread_t * params;
786 struct diskpartition_queue_t * dpq;
788 params = (vinitvolumepackage_thread_t *) args;
792 /* Attach all the volumes in this partition */
793 while (queue_IsNotEmpty(params)) {
794 int nAttached = 0, nUnattached = 0;
796 if (vinit_attach_abort) {
797 Log("Aborting initialization\n");
801 dpq = queue_First(params,diskpartition_queue_t);
807 opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
814 params->n_threads_complete++;
815 opr_cv_signal(¶ms->thread_done_cv);
819 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
821 #if defined(AFS_DEMAND_ATTACH_FS)
823 * Attach volumes in vice partitions
825 * @param[in] pt calling program type
828 * @note Threaded version of attach partitions.
830 * @post VInit state is 2
833 VInitAttachVolumes(ProgramType pt)
835 opr_Assert(VInit==1);
836 if (pt == fileServer) {
838 struct DiskPartition64 *diskP;
839 struct partition_queue pq;
840 struct volume_init_queue vq;
842 int i, threads, parts;
844 pthread_attr_t attrs;
846 /* create partition work queue */
849 opr_mutex_init(&pq.mutex);
850 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
851 struct diskpartition_queue_t *dp;
852 dp = malloc(sizeof(struct diskpartition_queue_t));
853 opr_Assert(dp != NULL);
855 queue_Append(&pq, dp);
858 /* number of worker threads; at least one, not to exceed the number of partitions */
859 threads = min(parts, vol_attach_threads);
861 /* create volume work queue */
864 opr_mutex_init(&vq.mutex);
866 opr_Verify(pthread_attr_init(&attrs) == 0);
867 opr_Verify(pthread_attr_setdetachstate(&attrs,
868 PTHREAD_CREATE_DETACHED) == 0);
870 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
871 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
874 /* create threads to scan disk partitions. */
875 for (i=0; i < threads; i++) {
876 struct vinitvolumepackage_thread_param *params;
879 params = malloc(sizeof(struct vinitvolumepackage_thread_param));
883 params->nthreads = threads;
884 params->thread = i+1;
887 opr_Verify(pthread_create(&tid, &attrs,
888 &VInitVolumePackageThread,
889 (void*)params) == 0);
890 AFS_SIGSET_RESTORE();
893 VInitPreAttachVolumes(threads, &vq);
895 opr_Verify(pthread_attr_destroy(&attrs) == 0);
896 opr_cv_destroy(&pq.cv);
897 opr_mutex_destroy(&pq.mutex);
898 opr_cv_destroy(&vq.cv);
899 opr_mutex_destroy(&vq.mutex);
903 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
904 opr_cv_broadcast(&vol_init_attach_cond);
911 * Volume package initialization worker thread. Scan partitions for volume
912 * header files. Gather batches of volume ids and dispatch them to
913 * the main thread to be preattached. The volume preattachement is done
914 * in the main thread to avoid global volume lock contention.
917 VInitVolumePackageThread(void *args)
919 struct vinitvolumepackage_thread_param *params;
920 struct DiskPartition64 *partition;
921 struct partition_queue *pq;
922 struct volume_init_queue *vq;
923 struct volume_init_batch *vb;
926 params = (struct vinitvolumepackage_thread_param *)args;
932 vb = malloc(sizeof(struct volume_init_batch));
934 vb->thread = params->thread;
938 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
939 while((partition = VInitNextPartition(pq))) {
943 Log("Partition %s: pre-attaching volumes\n", partition->name);
944 dirp = opendir(VPartitionPath(partition));
946 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
949 while ((vid = VInitNextVolumeId(dirp))) {
950 Volume *vp = calloc(1, sizeof(Volume));
952 vp->device = partition->device;
953 vp->partition = partition;
955 queue_Init(&vp->vnode_list);
956 queue_Init(&vp->rx_call_list);
957 opr_cv_init(&V_attachCV(vp));
959 vb->batch[vb->size++] = vp;
960 if (vb->size == VINIT_BATCH_MAX_SIZE) {
961 opr_mutex_enter(&vq->mutex);
962 queue_Append(vq, vb);
963 opr_cv_broadcast(&vq->cv);
964 opr_mutex_exit(&vq->mutex);
966 vb = malloc(sizeof(struct volume_init_batch));
968 vb->thread = params->thread;
977 opr_mutex_enter(&vq->mutex);
978 queue_Append(vq, vb);
979 opr_cv_broadcast(&vq->cv);
980 opr_mutex_exit(&vq->mutex);
982 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
988 * Read next element from the pre-populated partition list.
990 static struct DiskPartition64*
991 VInitNextPartition(struct partition_queue *pq)
993 struct DiskPartition64 *partition;
994 struct diskpartition_queue_t *dp; /* queue element */
996 if (vinit_attach_abort) {
997 Log("Aborting volume preattach thread.\n");
1001 /* get next partition to scan */
1002 opr_mutex_enter(&pq->mutex);
1003 if (queue_IsEmpty(pq)) {
1004 opr_mutex_exit(&pq->mutex);
1007 dp = queue_First(pq, diskpartition_queue_t);
1009 opr_mutex_exit(&pq->mutex);
1012 opr_Assert(dp->diskP);
1014 partition = dp->diskP;
1020 * Find next volume id on the partition.
1023 VInitNextVolumeId(DIR *dirp)
1029 while((d = readdir(dirp))) {
1030 if (vinit_attach_abort) {
1031 Log("Aborting volume preattach thread.\n");
1034 ext = strrchr(d->d_name, '.');
1035 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1036 vid = VolumeNumber(d->d_name);
1040 Log("Warning: bogus volume header file: %s\n", d->d_name);
1047 * Preattach volumes in batches to avoid lock contention.
1050 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1052 struct volume_init_batch *vb;
1056 /* dequeue next volume */
1057 opr_mutex_enter(&vq->mutex);
1058 if (queue_IsEmpty(vq)) {
1059 opr_cv_wait(&vq->cv, &vq->mutex);
1061 vb = queue_First(vq, volume_init_batch);
1063 opr_mutex_exit(&vq->mutex);
1067 for (i = 0; i<vb->size; i++) {
1073 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1075 Log("Error looking up volume, code=%d\n", ec);
1078 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1081 /* put pre-attached volume onto the hash table
1082 * and bring it up to the pre-attached state */
1083 AddVolumeToHashTable(vp, vp->hashid);
1084 AddVolumeToVByPList_r(vp);
1085 VLRU_Init_Node_r(vp);
1086 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1099 #endif /* AFS_DEMAND_ATTACH_FS */
1101 #if !defined(AFS_DEMAND_ATTACH_FS)
1103 * attach all volumes on a given disk partition
1106 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1112 Log("Partition %s: attaching volumes\n", diskP->name);
1113 dirp = opendir(VPartitionPath(diskP));
1115 Log("opendir on Partition %s failed!\n", diskP->name);
1119 while ((dp = readdir(dirp))) {
1121 p = strrchr(dp->d_name, '.');
1123 if (vinit_attach_abort) {
1124 Log("Partition %s: abort attach volumes\n", diskP->name);
1128 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1131 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1133 (*(vp ? nAttached : nUnattached))++;
1134 if (error == VOFFLINE)
1135 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1136 else if (LogLevel >= 5) {
1137 Log("Partition %s: attached volume %d (%s)\n",
1138 diskP->name, VolumeNumber(dp->d_name),
1147 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1152 #endif /* !AFS_DEMAND_ATTACH_FS */
1154 /***************************************************/
1155 /* Shutdown routines */
1156 /***************************************************/
1160 * highly multithreaded volume package shutdown
1162 * with the demand attach fileserver extensions,
1163 * VShutdown has been modified to be multithreaded.
1164 * In order to achieve optimal use of many threads,
1165 * the shutdown code involves one control thread and
1166 * n shutdown worker threads. The control thread
1167 * periodically examines the number of volumes available
1168 * for shutdown on each partition, and produces a worker
1169 * thread allocation schedule. The idea is to eliminate
1170 * redundant scheduling computation on the workers by
1171 * having a single master scheduler.
1173 * The scheduler's objectives are:
1175 * each partition with volumes remaining gets allocated
1176 * at least 1 thread (assuming sufficient threads)
1178 * threads are allocated proportional to the number of
1179 * volumes remaining to be offlined. This ensures that
1180 * the OS I/O scheduler has many requests to elevator
1181 * seek on partitions that will (presumably) take the
1182 * longest amount of time (from now) to finish shutdown
1183 * (3) keep threads busy
1184 * when there are extra threads, they are assigned to
1185 * partitions using a simple round-robin algorithm
1187 * In the future, we may wish to add the ability to adapt
1188 * to the relative performance patterns of each disk
1193 * multi-step shutdown process
1195 * demand attach shutdown is a four-step process. Each
1196 * shutdown "pass" shuts down increasingly more difficult
1197 * volumes. The main purpose is to achieve better cache
1198 * utilization during shutdown.
1201 * shutdown volumes in the unattached, pre-attached
1204 * shutdown attached volumes with cached volume headers
1206 * shutdown all volumes in non-exclusive states
1208 * shutdown all remaining volumes
1211 #ifdef AFS_DEMAND_ATTACH_FS
1217 struct DiskPartition64 * diskP;
1218 struct diskpartition_queue_t * dpq;
1219 vshutdown_thread_t params;
1221 pthread_attr_t attrs;
1223 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1226 Log("VShutdown: aborting attach volumes\n");
1227 vinit_attach_abort = 1;
1228 VOL_CV_WAIT(&vol_init_attach_cond);
1231 for (params.n_parts=0, diskP = DiskPartitionList;
1232 diskP; diskP = diskP->next, params.n_parts++);
1234 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1235 params.n_parts, params.n_parts > 1 ? "s" : "");
1237 vol_shutting_down = 1;
1239 if (vol_attach_threads > 1) {
1240 /* prepare for parallel shutdown */
1241 params.n_threads = vol_attach_threads;
1242 opr_mutex_init(¶ms.lock);
1243 opr_cv_init(¶ms.cv);
1244 opr_cv_init(¶ms.master_cv);
1245 opr_Verify(pthread_attr_init(&attrs) == 0);
1246 opr_Verify(pthread_attr_setdetachstate(&attrs,
1247 PTHREAD_CREATE_DETACHED) == 0);
1248 queue_Init(¶ms);
1250 /* setup the basic partition information structures for
1251 * parallel shutdown */
1252 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1254 struct rx_queue * qp, * nqp;
1258 VVByPListWait_r(diskP);
1259 VVByPListBeginExclusive_r(diskP);
1262 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1263 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1267 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1268 VPartitionPath(diskP), count);
1271 /* build up the pass 0 shutdown work queue */
1272 dpq = malloc(sizeof(struct diskpartition_queue_t));
1273 opr_Assert(dpq != NULL);
1275 queue_Prepend(¶ms, dpq);
1277 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1280 Log("VShutdown: beginning parallel fileserver shutdown\n");
1281 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1282 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1284 /* do pass 0 shutdown */
1285 opr_mutex_enter(¶ms.lock);
1286 for (i=0; i < params.n_threads; i++) {
1287 opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1291 /* wait for all the pass 0 shutdowns to complete */
1292 while (params.n_threads_complete < params.n_threads) {
1293 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1295 params.n_threads_complete = 0;
1297 opr_cv_broadcast(¶ms.cv);
1298 opr_mutex_exit(¶ms.lock);
1300 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1301 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1303 /* run the parallel shutdown scheduler. it will drop the glock internally */
1304 ShutdownController(¶ms);
1306 /* wait for all the workers to finish pass 3 and terminate */
1307 while (params.pass < 4) {
1308 VOL_CV_WAIT(¶ms.cv);
1311 opr_Verify(pthread_attr_destroy(&attrs) == 0);
1312 opr_cv_destroy(¶ms.cv);
1313 opr_cv_destroy(¶ms.master_cv);
1314 opr_mutex_destroy(¶ms.lock);
1316 /* drop the VByPList exclusive reservations */
1317 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1318 VVByPListEndExclusive_r(diskP);
1319 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1320 VPartitionPath(diskP),
1321 params.stats[0][diskP->index],
1322 params.stats[1][diskP->index],
1323 params.stats[2][diskP->index],
1324 params.stats[3][diskP->index]);
1327 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1329 /* if we're only going to run one shutdown thread, don't bother creating
1331 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1333 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1334 VShutdownByPartition_r(diskP);
1338 Log("VShutdown: complete.\n");
1341 #else /* AFS_DEMAND_ATTACH_FS */
1351 Log("VShutdown: aborting attach volumes\n");
1352 vinit_attach_abort = 1;
1353 #ifdef AFS_PTHREAD_ENV
1354 VOL_CV_WAIT(&vol_init_attach_cond);
1356 LWP_WaitProcess(VInitAttachVolumes);
1357 #endif /* AFS_PTHREAD_ENV */
1360 Log("VShutdown: shutting down on-line volumes...\n");
1361 vol_shutting_down = 1;
1362 for (i = 0; i < VolumeHashTable.Size; i++) {
1363 /* try to hold first volume in the hash table */
1364 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1368 Log("VShutdown: Attempting to take volume %u offline.\n",
1371 /* next, take the volume offline (drops reference count) */
1372 VOffline_r(vp, "File server was shut down");
1376 Log("VShutdown: complete.\n");
1378 #endif /* AFS_DEMAND_ATTACH_FS */
1384 opr_Assert(VInit>0);
1391 * stop new activity (e.g. SALVSYNC) from occurring
1393 * Use this to make the volume package less busy; for example, during
1394 * shutdown. This doesn't actually shutdown/detach anything in the
1395 * volume package, but prevents certain processes from ocurring. For
1396 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1397 * could also use this to prevent new volume attachment, or prevent
1398 * other programs from checking out volumes, etc.
1403 #ifdef AFS_DEMAND_ATTACH_FS
1404 /* make sure we don't try to contact the salvageserver, since it may
1405 * not be around anymore */
1406 vol_disallow_salvsync = 1;
1410 #ifdef AFS_DEMAND_ATTACH_FS
1413 * shutdown control thread
1416 ShutdownController(vshutdown_thread_t * params)
1419 struct DiskPartition64 * diskP;
1421 vshutdown_thread_t shadow;
1423 ShutdownCreateSchedule(params);
1425 while ((params->pass < 4) &&
1426 (params->n_threads_complete < params->n_threads)) {
1427 /* recompute schedule once per second */
1429 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1433 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1434 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1435 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1436 shadow.n_threads_complete, shadow.n_parts_done_pass);
1437 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1439 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1441 diskP->vol_list.len,
1442 shadow.part_thread_target[id],
1443 shadow.part_done_pass[id],
1444 shadow.part_pass_head[id]);
1450 ShutdownCreateSchedule(params);
1454 /* create the shutdown thread work schedule.
1455 * this scheduler tries to implement fairness
1456 * by allocating at least 1 thread to each
1457 * partition with volumes to be shutdown,
1458 * and then it attempts to allocate remaining
1459 * threads based upon the amount of work left
1462 ShutdownCreateSchedule(vshutdown_thread_t * params)
1464 struct DiskPartition64 * diskP;
1465 int sum, thr_workload, thr_left;
1466 int part_residue[VOLMAXPARTS+1];
1469 /* compute the total number of outstanding volumes */
1471 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1472 sum += diskP->vol_list.len;
1475 params->schedule_version++;
1476 params->vol_remaining = sum;
1481 /* compute average per-thread workload */
1482 thr_workload = sum / params->n_threads;
1483 if (sum % params->n_threads)
1486 thr_left = params->n_threads;
1487 memset(&part_residue, 0, sizeof(part_residue));
1489 /* for fairness, give every partition with volumes remaining
1490 * at least one thread */
1491 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1493 if (diskP->vol_list.len) {
1494 params->part_thread_target[id] = 1;
1497 params->part_thread_target[id] = 0;
1501 if (thr_left && thr_workload) {
1502 /* compute length-weighted workloads */
1505 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1507 delta = (diskP->vol_list.len / thr_workload) -
1508 params->part_thread_target[id];
1512 if (delta < thr_left) {
1513 params->part_thread_target[id] += delta;
1516 params->part_thread_target[id] += thr_left;
1524 /* try to assign any leftover threads to partitions that
1525 * had volume lengths closer to needing thread_target+1 */
1526 int max_residue, max_id = 0;
1528 /* compute the residues */
1529 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1531 part_residue[id] = diskP->vol_list.len -
1532 (params->part_thread_target[id] * thr_workload);
1535 /* now try to allocate remaining threads to partitions with the
1536 * highest residues */
1539 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1541 if (part_residue[id] > max_residue) {
1542 max_residue = part_residue[id];
1551 params->part_thread_target[max_id]++;
1553 part_residue[max_id] = 0;
1558 /* punt and give any remaining threads equally to each partition */
1560 if (thr_left >= params->n_parts) {
1561 alloc = thr_left / params->n_parts;
1562 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1564 params->part_thread_target[id] += alloc;
1569 /* finish off the last of the threads */
1570 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1572 params->part_thread_target[id]++;
1578 /* worker thread for parallel shutdown */
1580 VShutdownThread(void * args)
1582 vshutdown_thread_t * params;
1583 int found, pass, schedule_version_save, count;
1584 struct DiskPartition64 *diskP;
1585 struct diskpartition_queue_t * dpq;
1588 params = (vshutdown_thread_t *) args;
1590 /* acquire the shutdown pass 0 lock */
1591 opr_mutex_enter(¶ms->lock);
1593 /* if there's still pass 0 work to be done,
1594 * get a work entry, and do a pass 0 shutdown */
1595 if (queue_IsNotEmpty(params)) {
1596 dpq = queue_First(params, diskpartition_queue_t);
1598 opr_mutex_exit(¶ms->lock);
1604 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1606 params->stats[0][diskP->index] = count;
1607 opr_mutex_enter(¶ms->lock);
1610 params->n_threads_complete++;
1611 if (params->n_threads_complete == params->n_threads) {
1612 /* notify control thread that all workers have completed pass 0 */
1613 opr_cv_signal(¶ms->master_cv);
1615 while (params->pass == 0) {
1616 opr_cv_wait(¶ms->cv, ¶ms->lock);
1620 opr_mutex_exit(¶ms->lock);
1623 pass = params->pass;
1624 opr_Assert(pass > 0);
1626 /* now escalate through the more complicated shutdowns */
1628 schedule_version_save = params->schedule_version;
1630 /* find a disk partition to work on */
1631 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1633 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1634 params->part_thread_target[id]--;
1641 /* hmm. for some reason the controller thread couldn't find anything for
1642 * us to do. let's see if there's anything we can do */
1643 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1645 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1648 } else if (!params->part_done_pass[id]) {
1649 params->part_done_pass[id] = 1;
1650 params->n_parts_done_pass++;
1652 Log("VShutdown: done shutting down volumes on partition %s.\n",
1653 VPartitionPath(diskP));
1659 /* do work on this partition until either the controller
1660 * creates a new schedule, or we run out of things to do
1661 * on this partition */
1664 while (!params->part_done_pass[id] &&
1665 (schedule_version_save == params->schedule_version)) {
1666 /* ShutdownVolumeWalk_r will drop the glock internally */
1667 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1668 if (!params->part_done_pass[id]) {
1669 params->part_done_pass[id] = 1;
1670 params->n_parts_done_pass++;
1672 Log("VShutdown: done shutting down volumes on partition %s.\n",
1673 VPartitionPath(diskP));
1681 params->stats[pass][id] += count;
1683 /* ok, everyone is done this pass, proceed */
1686 params->n_threads_complete++;
1687 while (params->pass == pass) {
1688 if (params->n_threads_complete == params->n_threads) {
1689 /* we are the last thread to complete, so we will
1690 * reinitialize worker pool state for the next pass */
1691 params->n_threads_complete = 0;
1692 params->n_parts_done_pass = 0;
1694 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1696 params->part_done_pass[id] = 0;
1697 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1700 /* compute a new thread schedule before releasing all the workers */
1701 ShutdownCreateSchedule(params);
1703 /* wake up all the workers */
1704 opr_cv_broadcast(¶ms->cv);
1707 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1708 pass, params->n_threads, params->n_parts);
1711 VOL_CV_WAIT(¶ms->cv);
1714 pass = params->pass;
1728 /* shut down all volumes on a given disk partition
1730 * note that this function will not allow mp-fast
1731 * shutdown of a partition */
1733 VShutdownByPartition_r(struct DiskPartition64 * dp)
1739 /* wait for other exclusive ops to finish */
1740 VVByPListWait_r(dp);
1742 /* begin exclusive access */
1743 VVByPListBeginExclusive_r(dp);
1745 /* pick the low-hanging fruit first,
1746 * then do the complicated ones last
1747 * (has the advantage of keeping
1748 * in-use volumes up until the bitter end) */
1749 for (pass = 0, total=0; pass < 4; pass++) {
1750 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1751 total += pass_stats[pass];
1754 /* end exclusive access */
1755 VVByPListEndExclusive_r(dp);
1757 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1758 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1763 /* internal shutdown functionality
1765 * for multi-pass shutdown:
1766 * 0 to only "shutdown" {pre,un}attached and error state volumes
1767 * 1 to also shutdown attached volumes w/ volume header loaded
1768 * 2 to also shutdown attached volumes w/o volume header loaded
1769 * 3 to also shutdown exclusive state volumes
1771 * caller MUST hold exclusive access on the hash chain
1772 * because we drop vol_glock_mutex internally
1774 * this function is reentrant for passes 1--3
1775 * (e.g. multiple threads can cooperate to
1776 * shutdown a partition mp-fast)
1778 * pass 0 is not scaleable because the volume state data is
1779 * synchronized by vol_glock mutex, and the locking overhead
1780 * is too high to drop the lock long enough to do linked list
1784 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1786 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1789 while (ShutdownVolumeWalk_r(dp, pass, &q))
1795 /* conditionally shutdown one volume on partition dp
1796 * returns 1 if a volume was shutdown in this pass,
1799 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1800 struct rx_queue ** idx)
1802 struct rx_queue *qp, *nqp;
1807 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1808 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1812 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1813 (V_attachState(vp) != VOL_STATE_ERROR) &&
1814 (V_attachState(vp) != VOL_STATE_DELETED) &&
1815 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1819 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1820 (vp->header == NULL)) {
1824 if (VIsExclusiveState(V_attachState(vp))) {
1829 DeleteVolumeFromVByPList_r(vp);
1830 VShutdownVolume_r(vp);
1840 * shutdown a specific volume
1842 /* caller MUST NOT hold a heavyweight ref on vp */
1844 VShutdownVolume_r(Volume * vp)
1848 VCreateReservation_r(vp);
1850 if (LogLevel >= 5) {
1851 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1852 vp->hashid, vp->partition->device, V_attachState(vp));
1855 /* wait for other blocking ops to finish */
1856 VWaitExclusiveState_r(vp);
1858 opr_Assert(VIsValidState(V_attachState(vp)));
1860 switch(V_attachState(vp)) {
1861 case VOL_STATE_SALVAGING:
1862 /* Leave salvaging volumes alone. Any in-progress salvages will
1863 * continue working after viced shuts down. This is intentional.
1866 case VOL_STATE_PREATTACHED:
1867 case VOL_STATE_ERROR:
1868 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1869 case VOL_STATE_UNATTACHED:
1870 case VOL_STATE_DELETED:
1872 case VOL_STATE_GOING_OFFLINE:
1873 case VOL_STATE_SHUTTING_DOWN:
1874 case VOL_STATE_ATTACHED:
1878 Log("VShutdown: Attempting to take volume %u offline.\n",
1881 /* take the volume offline (drops reference count) */
1882 VOffline_r(vp, "File server was shut down");
1889 VCancelReservation_r(vp);
1893 #endif /* AFS_DEMAND_ATTACH_FS */
1896 /***************************************************/
1897 /* Header I/O routines */
1898 /***************************************************/
1901 HeaderName(bit32 magic)
1904 case VOLUMEINFOMAGIC:
1905 return "volume info";
1906 case SMALLINDEXMAGIC:
1907 return "small index";
1908 case LARGEINDEXMAGIC:
1909 return "large index";
1910 case LINKTABLEMAGIC:
1911 return "link table";
1916 /* open a descriptor for the inode (h),
1917 * read in an on-disk structure into buffer (to) of size (size),
1918 * verify versionstamp in structure has magic (magic) and
1919 * optionally verify version (version) if (version) is nonzero
1922 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1925 struct versionStamp *vsn;
1927 afs_sfsize_t nbytes;
1932 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1940 Log("ReadHeader: Failed to open %s header file "
1941 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1942 PrintInode(stmp, h->ih_ino), errno);
1947 vsn = (struct versionStamp *)to;
1948 nbytes = FDH_PREAD(fdP, to, size, 0);
1950 Log("ReadHeader: Failed to read %s header file "
1951 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1952 PrintInode(stmp, h->ih_ino), errno);
1954 FDH_REALLYCLOSE(fdP);
1957 if (nbytes != size) {
1958 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1959 "(volume=%u, inode=%s); expected=%d, read=%d\n",
1960 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), size,
1963 FDH_REALLYCLOSE(fdP);
1966 if (vsn->magic != magic) {
1967 Log("ReadHeader: Incorrect magic for %s header file "
1968 "(volume=%u, inode=%s); expected=0x%x, read=0x%x\n",
1969 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), magic,
1972 FDH_REALLYCLOSE(fdP);
1978 /* Check is conditional, in case caller wants to inspect version himself */
1979 if (version && vsn->version != version) {
1980 Log("ReadHeader: Incorrect version for %s header file "
1981 "(volume=%u, inode=%s); expected=%x, read=%x\n",
1982 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino),
1983 version, vsn->version);
1989 WriteVolumeHeader_r(Error * ec, Volume * vp)
1991 IHandle_t *h = V_diskDataHandle(vp);
2001 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
2002 != sizeof(V_disk(vp))) {
2004 FDH_REALLYCLOSE(fdP);
2010 /* VolumeHeaderToDisk
2011 * Allows for storing 64 bit inode numbers in on-disk volume header
2014 /* convert in-memory representation of a volume header to the
2015 * on-disk representation of a volume header */
2017 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2020 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2021 dh->stamp = h->stamp;
2023 dh->parent = h->parent;
2025 #ifdef AFS_64BIT_IOPS_ENV
2026 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2027 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2028 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2029 dh->smallVnodeIndex_hi =
2030 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2031 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2032 dh->largeVnodeIndex_hi =
2033 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2034 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2035 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2037 dh->volumeInfo_lo = h->volumeInfo;
2038 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2039 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2040 dh->linkTable_lo = h->linkTable;
2044 /* DiskToVolumeHeader
2045 * Converts an on-disk representation of a volume header to
2046 * the in-memory representation of a volume header.
2048 * Makes the assumption that AFS has *always*
2049 * zero'd the volume header file so that high parts of inode
2050 * numbers are 0 in older (SGI EFS) volume header files.
2053 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2055 memset(h, 0, sizeof(VolumeHeader_t));
2056 h->stamp = dh->stamp;
2058 h->parent = dh->parent;
2060 #ifdef AFS_64BIT_IOPS_ENV
2062 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2064 h->smallVnodeIndex =
2065 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2066 smallVnodeIndex_hi << 32);
2068 h->largeVnodeIndex =
2069 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2070 largeVnodeIndex_hi << 32);
2072 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2074 h->volumeInfo = dh->volumeInfo_lo;
2075 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2076 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2077 h->linkTable = dh->linkTable_lo;
2082 /***************************************************/
2083 /* Volume Attachment routines */
2084 /***************************************************/
2086 #ifdef AFS_DEMAND_ATTACH_FS
2088 * pre-attach a volume given its path.
2090 * @param[out] ec outbound error code
2091 * @param[in] partition partition path string
2092 * @param[in] name volume id string
2094 * @return volume object pointer
2096 * @note A pre-attached volume will only have its partition
2097 * and hashid fields initialized. At first call to
2098 * VGetVolume, the volume will be fully attached.
2102 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2106 vp = VPreAttachVolumeByName_r(ec, partition, name);
2112 * pre-attach a volume given its path.
2114 * @param[out] ec outbound error code
2115 * @param[in] partition path to vice partition
2116 * @param[in] name volume id string
2118 * @return volume object pointer
2120 * @pre VOL_LOCK held
2122 * @internal volume package internal use only.
2125 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2127 return VPreAttachVolumeById_r(ec,
2129 VolumeNumber(name));
2133 * pre-attach a volume given its path and numeric volume id.
2135 * @param[out] ec error code return
2136 * @param[in] partition path to vice partition
2137 * @param[in] volumeId numeric volume id
2139 * @return volume object pointer
2141 * @pre VOL_LOCK held
2143 * @internal volume package internal use only.
2146 VPreAttachVolumeById_r(Error * ec,
2151 struct DiskPartition64 *partp;
2155 opr_Assert(programType == fileServer);
2157 if (!(partp = VGetPartition_r(partition, 0))) {
2159 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2163 vp = VLookupVolume_r(ec, volumeId, NULL);
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 * @warning Returned volume object pointer does not have to
2184 * equal the pointer passed in as argument vp. There
2185 * are potential race conditions which can result in
2186 * the pointers having different values. It is up to
2187 * the caller to make sure that references are handled
2188 * properly in this case.
2190 * @note If there is already a volume object registered with
2191 * the same volume id, its pointer MUST be passed as
2192 * argument vp. Failure to do so will result in a silent
2193 * failure to preattach.
2195 * @internal volume package internal use only.
2198 VPreAttachVolumeByVp_r(Error * ec,
2199 struct DiskPartition64 * partp,
2207 /* check to see if pre-attach already happened */
2209 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2210 (V_attachState(vp) != VOL_STATE_DELETED) &&
2211 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2212 !VIsErrorState(V_attachState(vp))) {
2214 * pre-attach is a no-op in all but the following cases:
2216 * - volume is unattached
2217 * - volume is in an error state
2218 * - volume is pre-attached
2220 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state (state %u flags 0x%x)\n",
2221 vid, V_attachState(vp), V_attachFlags(vp));
2224 /* we're re-attaching a volume; clear out some old state */
2225 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2227 if (V_partition(vp) != partp) {
2228 /* XXX potential race */
2229 DeleteVolumeFromVByPList_r(vp);
2232 /* if we need to allocate a new Volume struct,
2233 * go ahead and drop the vol glock, otherwise
2234 * do the basic setup synchronised, as it's
2235 * probably not worth dropping the lock */
2238 /* allocate the volume structure */
2239 vp = nvp = calloc(1, sizeof(Volume));
2240 opr_Assert(vp != NULL);
2241 queue_Init(&vp->vnode_list);
2242 queue_Init(&vp->rx_call_list);
2243 opr_cv_init(&V_attachCV(vp));
2246 /* link the volume with its associated vice partition */
2247 vp->device = partp->device;
2248 vp->partition = partp;
2251 vp->specialStatus = 0;
2253 /* if we dropped the lock, reacquire the lock,
2254 * check for pre-attach races, and then add
2255 * the volume to the hash table */
2258 nvp = VLookupVolume_r(ec, vid, NULL);
2263 } else if (nvp) { /* race detected */
2268 /* hack to make up for VChangeState_r() decrementing
2269 * the old state counter */
2270 VStats.state_levels[0]++;
2274 /* put pre-attached volume onto the hash table
2275 * and bring it up to the pre-attached state */
2276 AddVolumeToHashTable(vp, vp->hashid);
2277 AddVolumeToVByPList_r(vp);
2278 VLRU_Init_Node_r(vp);
2279 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2282 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2290 #endif /* AFS_DEMAND_ATTACH_FS */
2292 /* Attach an existing volume, given its pathname, and return a
2293 pointer to the volume header information. The volume also
2294 normally goes online at this time. An offline volume
2295 must be reattached to make it go online */
2297 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2301 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2307 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2310 struct DiskPartition64 *partp;
2315 #ifdef AFS_DEMAND_ATTACH_FS
2316 VolumeStats stats_save;
2318 #endif /* AFS_DEMAND_ATTACH_FS */
2322 volumeId = VolumeNumber(name);
2324 if (!(partp = VGetPartition_r(partition, 0))) {
2326 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2330 if (VRequiresPartLock()) {
2331 opr_Assert(VInit == 3);
2332 VLockPartition_r(partition);
2333 } else if (programType == fileServer) {
2334 #ifdef AFS_DEMAND_ATTACH_FS
2335 /* lookup the volume in the hash table */
2336 vp = VLookupVolume_r(ec, volumeId, NULL);
2342 /* save any counters that are supposed to
2343 * be monotonically increasing over the
2344 * lifetime of the fileserver */
2345 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2347 memset(&stats_save, 0, sizeof(VolumeStats));
2350 /* if there's something in the hash table, and it's not
2351 * in the pre-attach state, then we may need to detach
2352 * it before proceeding */
2353 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2354 VCreateReservation_r(vp);
2355 VWaitExclusiveState_r(vp);
2357 /* at this point state must be one of:
2367 if (vp->specialStatus == VBUSY)
2370 /* if it's already attached, see if we can return it */
2371 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2372 VGetVolumeByVp_r(ec, vp);
2373 if (V_inUse(vp) == fileServer) {
2374 VCancelReservation_r(vp);
2378 /* otherwise, we need to detach, and attempt to re-attach */
2379 VDetachVolume_r(ec, vp);
2381 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2384 /* if it isn't fully attached, delete from the hash tables,
2385 and let the refcounter handle the rest */
2386 DeleteVolumeFromHashTable(vp);
2387 DeleteVolumeFromVByPList_r(vp);
2390 VCancelReservation_r(vp);
2394 /* pre-attach volume if it hasn't been done yet */
2396 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2397 (V_attachState(vp) == VOL_STATE_DELETED) ||
2398 (V_attachState(vp) == VOL_STATE_ERROR)) {
2400 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2406 opr_Assert(vp != NULL);
2408 /* handle pre-attach races
2410 * multiple threads can race to pre-attach a volume,
2411 * but we can't let them race beyond that
2413 * our solution is to let the first thread to bring
2414 * the volume into an exclusive state win; the other
2415 * threads just wait until it finishes bringing the
2416 * volume online, and then they do a vgetvolumebyvp
2418 if (svp && (svp != vp)) {
2419 /* wait for other exclusive ops to finish */
2420 VCreateReservation_r(vp);
2421 VWaitExclusiveState_r(vp);
2423 /* get a heavyweight ref, kill the lightweight ref, and return */
2424 VGetVolumeByVp_r(ec, vp);
2425 VCancelReservation_r(vp);
2429 /* at this point, we are chosen as the thread to do
2430 * demand attachment for this volume. all other threads
2431 * doing a getvolume on vp->hashid will block until we finish */
2433 /* make sure any old header cache entries are invalidated
2434 * before proceeding */
2435 FreeVolumeHeader(vp);
2437 VChangeState_r(vp, VOL_STATE_ATTACHING);
2439 /* restore any saved counters */
2440 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2441 #else /* AFS_DEMAND_ATTACH_FS */
2442 vp = VGetVolume_r(ec, volumeId);
2444 if (V_inUse(vp) == fileServer)
2446 if (vp->specialStatus == VBUSY)
2448 VDetachVolume_r(ec, vp);
2450 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2454 #endif /* AFS_DEMAND_ATTACH_FS */
2458 strcpy(path, VPartitionPath(partp));
2462 strcat(path, OS_DIRSEP);
2466 vp = (Volume *) calloc(1, sizeof(Volume));
2467 opr_Assert(vp != NULL);
2468 vp->hashid = volumeId;
2469 vp->device = partp->device;
2470 vp->partition = partp;
2471 queue_Init(&vp->vnode_list);
2472 queue_Init(&vp->rx_call_list);
2473 #ifdef AFS_DEMAND_ATTACH_FS
2474 opr_cv_init(&V_attachCV(vp));
2475 #endif /* AFS_DEMAND_ATTACH_FS */
2478 /* attach2 is entered without any locks, and returns
2479 * with vol_glock_mutex held */
2480 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2482 if (VCanUseFSSYNC() && vp) {
2483 #ifdef AFS_DEMAND_ATTACH_FS
2484 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2485 /* mark volume header as in use so that volser crashes lead to a
2486 * salvage attempt */
2487 VUpdateVolume_r(ec, vp, 0);
2489 /* for dafs, we should tell the fileserver, except for V_PEEK
2490 * where we know it is not necessary */
2491 if (mode == V_PEEK) {
2492 vp->needsPutBack = 0;
2494 vp->needsPutBack = VOL_PUTBACK;
2496 #else /* !AFS_DEMAND_ATTACH_FS */
2497 /* duplicate computation in fssync.c about whether the server
2498 * takes the volume offline or not. If the volume isn't
2499 * offline, we must not return it when we detach the volume,
2500 * or the server will abort */
2501 if (mode == V_READONLY || mode == V_PEEK
2502 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2503 vp->needsPutBack = 0;
2505 vp->needsPutBack = VOL_PUTBACK;
2506 #endif /* !AFS_DEMAND_ATTACH_FS */
2508 #ifdef FSSYNC_BUILD_CLIENT
2509 /* Only give back the vol to the fileserver if we checked it out; attach2
2510 * will set checkedOut only if we successfully checked it out from the
2512 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2514 #ifdef AFS_DEMAND_ATTACH_FS
2515 /* If we couldn't attach but we scheduled a salvage, we already
2516 * notified the fileserver; don't online it now */
2517 if (*ec != VSALVAGING)
2518 #endif /* AFS_DEMAND_ATTACH_FS */
2519 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2522 if (programType == fileServer && vp) {
2523 #ifdef AFS_DEMAND_ATTACH_FS
2525 * we can get here in cases where we don't "own"
2526 * the volume (e.g. volume owned by a utility).
2527 * short circuit around potential disk header races.
2529 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2533 VUpdateVolume_r(ec, vp, 0);
2535 Log("VAttachVolume: Error updating volume\n");
2540 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2541 #ifndef AFS_DEMAND_ATTACH_FS
2542 /* This is a hack: by temporarily setting the incore
2543 * dontSalvage flag ON, the volume will be put back on the
2544 * Update list (with dontSalvage OFF again). It will then
2545 * come back in N minutes with DONT_SALVAGE eventually
2546 * set. This is the way that volumes that have never had
2547 * it set get it set; or that volumes that have been
2548 * offline without DONT SALVAGE having been set also
2549 * eventually get it set */
2550 V_dontSalvage(vp) = DONT_SALVAGE;
2551 #endif /* !AFS_DEMAND_ATTACH_FS */
2552 VAddToVolumeUpdateList_r(ec, vp);
2554 Log("VAttachVolume: Error adding volume to update list\n");
2561 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2566 if (VRequiresPartLock()) {
2567 VUnlockPartition_r(partition);
2570 #ifdef AFS_DEMAND_ATTACH_FS
2571 /* attach failed; make sure we're in error state */
2572 if (vp && !VIsErrorState(V_attachState(vp))) {
2573 VChangeState_r(vp, VOL_STATE_ERROR);
2575 #endif /* AFS_DEMAND_ATTACH_FS */
2582 #ifdef AFS_DEMAND_ATTACH_FS
2583 /* VAttachVolumeByVp_r
2585 * finish attaching a volume that is
2586 * in a less than fully attached state
2588 /* caller MUST hold a ref count on vp */
2590 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2592 char name[VMAXPATHLEN];
2594 struct DiskPartition64 *partp;
2598 Volume * nvp = NULL;
2599 VolumeStats stats_save;
2603 /* volume utility should never call AttachByVp */
2604 opr_Assert(programType == fileServer);
2606 volumeId = vp->hashid;
2607 partp = vp->partition;
2608 VolumeExternalName_r(volumeId, name, sizeof(name));
2611 /* if another thread is performing a blocking op, wait */
2612 VWaitExclusiveState_r(vp);
2614 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2616 /* if it's already attached, see if we can return it */
2617 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2618 VGetVolumeByVp_r(ec, vp);
2619 if (V_inUse(vp) == fileServer) {
2622 if (vp->specialStatus == VBUSY)
2624 VDetachVolume_r(ec, vp);
2626 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2632 /* pre-attach volume if it hasn't been done yet */
2634 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2635 (V_attachState(vp) == VOL_STATE_DELETED) ||
2636 (V_attachState(vp) == VOL_STATE_ERROR)) {
2637 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2643 VCreateReservation_r(nvp);
2648 opr_Assert(vp != NULL);
2649 VChangeState_r(vp, VOL_STATE_ATTACHING);
2651 /* restore monotonically increasing stats */
2652 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2656 /* compute path to disk header */
2657 strcpy(path, VPartitionPath(partp));
2661 strcat(path, OS_DIRSEP);
2666 * NOTE: attach2 is entered without any locks, and returns
2667 * with vol_glock_mutex held */
2668 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2671 * the event that an error was encountered, or
2672 * the volume was not brought to an attached state
2673 * for any reason, skip to the end. We cannot
2674 * safely call VUpdateVolume unless we "own" it.
2678 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2682 VUpdateVolume_r(ec, vp, 0);
2684 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2688 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2689 #ifndef AFS_DEMAND_ATTACH_FS
2690 /* This is a hack: by temporarily setting the incore
2691 * dontSalvage flag ON, the volume will be put back on the
2692 * Update list (with dontSalvage OFF again). It will then
2693 * come back in N minutes with DONT_SALVAGE eventually
2694 * set. This is the way that volumes that have never had
2695 * it set get it set; or that volumes that have been
2696 * offline without DONT SALVAGE having been set also
2697 * eventually get it set */
2698 V_dontSalvage(vp) = DONT_SALVAGE;
2699 #endif /* !AFS_DEMAND_ATTACH_FS */
2700 VAddToVolumeUpdateList_r(ec, vp);
2702 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2709 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2713 VCancelReservation_r(nvp);
2716 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2717 if (vp && !VIsErrorState(V_attachState(vp))) {
2718 VChangeState_r(vp, VOL_STATE_ERROR);
2727 * lock a volume on disk (non-blocking).
2729 * @param[in] vp The volume to lock
2730 * @param[in] locktype READ_LOCK or WRITE_LOCK
2732 * @return operation status
2733 * @retval 0 success, lock was obtained
2734 * @retval EBUSY a conflicting lock was held by another process
2735 * @retval EIO error acquiring lock
2737 * @pre If we're in the fileserver, vp is in an exclusive state
2739 * @pre vp is not already locked
2742 VLockVolumeNB(Volume *vp, int locktype)
2746 opr_Assert(programType != fileServer
2747 || VIsExclusiveState(V_attachState(vp)));
2748 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2750 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2752 V_attachFlags(vp) |= VOL_LOCKED;
2759 * unlock a volume on disk that was locked with VLockVolumeNB.
2761 * @param[in] vp volume to unlock
2763 * @pre If we're in the fileserver, vp is in an exclusive state
2765 * @pre vp has already been locked
2768 VUnlockVolume(Volume *vp)
2770 opr_Assert(programType != fileServer
2771 || VIsExclusiveState(V_attachState(vp)));
2772 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2774 VUnlockVolumeById(vp->hashid, vp->partition);
2776 V_attachFlags(vp) &= ~VOL_LOCKED;
2778 #endif /* AFS_DEMAND_ATTACH_FS */
2781 * read in a vol header, possibly lock the vol header, and possibly check out
2782 * the vol header from the fileserver, as part of volume attachment.
2784 * @param[out] ec error code
2785 * @param[in] vp volume pointer object
2786 * @param[in] partp disk partition object of the attaching partition
2787 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2789 * @param[in] peek 1 to just try to read in the volume header and make sure
2790 * we don't try to lock the vol, or check it out from
2791 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2793 * @param[out] acheckedOut If we successfully checked-out the volume from
2794 * the fileserver (if we needed to), this is set
2795 * to 1, otherwise it is untouched.
2797 * @note As part of DAFS volume attachment, the volume header may be either
2798 * read- or write-locked to ensure mutual exclusion of certain volume
2799 * operations. In some cases in order to determine whether we need to
2800 * read- or write-lock the header, we need to read in the header to see
2801 * if the volume is RW or not. So, if we read in the header under a
2802 * read-lock and determine that we actually need a write-lock on the
2803 * volume header, this function will drop the read lock, acquire a write
2804 * lock, and read the header in again.
2807 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2808 int mode, int peek, int *acheckedOut)
2810 struct VolumeDiskHeader diskHeader;
2811 struct VolumeHeader header;
2814 int lock_tries = 0, checkout_tries = 0;
2816 VolumeId volid = vp->hashid;
2817 #ifdef FSSYNC_BUILD_CLIENT
2818 int checkout, done_checkout = 0;
2819 #endif /* FSSYNC_BUILD_CLIENT */
2820 #ifdef AFS_DEMAND_ATTACH_FS
2821 int locktype = 0, use_locktype = -1;
2822 #endif /* AFS_DEMAND_ATTACH_FS */
2828 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2829 Log("VAttachVolume: retried too many times trying to lock header for "
2830 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2831 VPartitionPath(partp));
2835 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2836 Log("VAttachVolume: retried too many times trying to checkout "
2837 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2838 VPartitionPath(partp));
2843 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2844 /* short-circuit the 'volume does not exist' case */
2849 #ifdef FSSYNC_BUILD_CLIENT
2850 checkout = !done_checkout;
2852 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2854 memset(&res, 0, sizeof(res));
2856 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2859 if (res.hdr.reason == FSYNC_SALVAGE) {
2860 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2861 afs_printable_uint32_lu(volid));
2864 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2865 afs_printable_uint32_lu(volid));
2866 *ec = VNOVOL; /* XXXX */
2874 #ifdef AFS_DEMAND_ATTACH_FS
2875 if (use_locktype < 0) {
2876 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2877 * if it turns out to be RW */
2878 locktype = VVolLockType(mode, 0);
2881 /* a previous try says we should use use_locktype to lock the volume,
2883 locktype = use_locktype;
2886 if (!peek && locktype) {
2887 code = VLockVolumeNB(vp, locktype);
2889 if (code == EBUSY) {
2890 Log("VAttachVolume: another program has vol %lu locked\n",
2891 afs_printable_uint32_lu(volid));
2893 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2894 code, afs_printable_uint32_lu(volid));
2901 #endif /* AFS_DEMAND_ATTACH_FS */
2903 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2913 DiskToVolumeHeader(&header, &diskHeader);
2915 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2916 header.largeVnodeIndex);
2917 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2918 header.smallVnodeIndex);
2919 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2921 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2924 /* only need to do this once */
2926 GetVolumeHeader(vp);
2930 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2931 /* demand attach changes the V_PEEK mechanism
2933 * we can now suck the current disk data structure over
2934 * the fssync interface without going to disk
2936 * (technically, we don't need to restrict this feature
2937 * to demand attach fileservers. However, I'm trying
2938 * to limit the number of common code changes)
2940 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2942 res.payload.len = sizeof(VolumeDiskData);
2943 res.payload.buf = &vp->header->diskstuff;
2945 if (FSYNC_VolOp(vp->hashid,
2947 FSYNC_VOL_QUERY_HDR,
2950 goto disk_header_loaded;
2953 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2954 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2955 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2957 #ifdef AFS_DEMAND_ATTACH_FS
2960 IncUInt64(&VStats.hdr_loads);
2961 IncUInt64(&vp->stats.hdr_loads);
2963 #endif /* AFS_DEMAND_ATTACH_FS */
2966 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2967 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2971 #ifdef AFS_DEMAND_ATTACH_FS
2972 # ifdef FSSYNC_BUILD_CLIENT
2974 # endif /* FSSYNC_BUILD_CLIENT */
2976 /* if the lock type we actually used to lock the volume is different than
2977 * the lock type we should have used, retry with the lock type we should
2979 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2980 if (locktype != use_locktype) {
2984 #endif /* AFS_DEMAND_ATTACH_FS */
2989 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2990 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2992 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2994 if (code == SYNC_DENIED) {
2995 /* must retry checkout; fileserver no longer thinks we have
3001 } else if (code != SYNC_OK) {
3005 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3008 /* either we are going to be called again for a second pass, or we
3009 * encountered an error; clean up in either case */
3011 #ifdef AFS_DEMAND_ATTACH_FS
3012 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3015 #endif /* AFS_DEMAND_ATTACH_FS */
3016 if (vp->linkHandle) {
3017 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3018 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3019 IH_RELEASE(vp->diskDataHandle);
3020 IH_RELEASE(vp->linkHandle);
3026 FreeVolumeHeader(vp);
3036 #ifdef AFS_DEMAND_ATTACH_FS
3038 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3039 Volume *vp, int *acheckedOut)
3043 if (vp->pending_vol_op) {
3047 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3049 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3051 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3052 } else if (code == 0) {
3053 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3056 /* we need the vol header to determine if the volume can be
3057 * left online for the vop, so... get the header */
3061 /* attach header with peek=1 to avoid checking out the volume
3062 * or locking it; we just want the header info, we're not
3063 * messing with the volume itself at all */
3064 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3071 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3072 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3074 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3077 /* make sure we grab a new vol header and re-open stuff on
3078 * actual attachment; we can't keep the data we grabbed, since
3079 * it was not done under a lock and thus not safe */
3080 FreeVolumeHeader(vp);
3081 VReleaseVolumeHandles_r(vp);
3084 /* see if the pending volume op requires exclusive access */
3085 switch (vp->pending_vol_op->vol_op_state) {
3086 case FSSYNC_VolOpPending:
3087 /* this should never happen */
3088 opr_Assert(vp->pending_vol_op->vol_op_state
3089 != FSSYNC_VolOpPending);
3092 case FSSYNC_VolOpRunningUnknown:
3093 /* this should never happen; we resolved 'unknown' above */
3094 opr_Assert(vp->pending_vol_op->vol_op_state
3095 != FSSYNC_VolOpRunningUnknown);
3098 case FSSYNC_VolOpRunningOffline:
3099 /* mark the volume down */
3101 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3103 /* do not set V_offlineMessage here; we don't have ownership of
3104 * the volume (and probably do not have the header loaded), so we
3105 * can't alter the disk header */
3107 /* check to see if we should set the specialStatus flag */
3108 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3109 /* don't overwrite specialStatus if it was already set to
3110 * something else (e.g. VMOVED) */
3111 if (!vp->specialStatus) {
3112 vp->specialStatus = VBUSY;
3124 #endif /* AFS_DEMAND_ATTACH_FS */
3127 * volume attachment helper function.
3129 * @param[out] ec error code
3130 * @param[in] volumeId volume ID of the attaching volume
3131 * @param[in] path full path to the volume header .vol file
3132 * @param[in] partp disk partition object for the attaching partition
3133 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3134 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3135 * DAFS) should already be initialized
3136 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3137 * if there is a volume operation running for this volume
3138 * that should set the volume to VBUSY during its run. 0
3139 * otherwise. (see VVolOpSetVBusy_r)
3140 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3142 * @param[out] acheckedOut If we successfully checked-out the volume from
3143 * the fileserver (if we needed to), this is set
3144 * to 1, otherwise it is 0.
3146 * @return pointer to the semi-attached volume pointer
3147 * @retval NULL an error occurred (check value of *ec)
3148 * @retval vp volume successfully attaching
3150 * @pre no locks held
3152 * @post VOL_LOCK held
3155 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3156 Volume * vp, int isbusy, int mode, int *acheckedOut)
3158 /* have we read in the header successfully? */
3159 int read_header = 0;
3161 #ifdef AFS_DEMAND_ATTACH_FS
3162 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3166 /* in the case of an error, to what state should the volume be
3168 VolState error_state = VOL_STATE_ERROR;
3169 #endif /* AFS_DEMAND_ATTACH_FS */
3173 vp->vnodeIndex[vLarge].handle = NULL;
3174 vp->vnodeIndex[vSmall].handle = NULL;
3175 vp->diskDataHandle = NULL;
3176 vp->linkHandle = NULL;
3180 #ifdef AFS_DEMAND_ATTACH_FS
3181 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3183 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3186 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3187 #endif /* !AFS_DEMAND_ATTACH_FS */
3189 if (*ec == VNOVOL) {
3190 /* if the volume doesn't exist, skip straight to 'error' so we don't
3191 * request a salvage */
3192 goto unlocked_error;
3198 /* ensure that we don't override specialStatus if it was set to
3199 * something else (e.g. VMOVED) */
3200 if (isbusy && !vp->specialStatus) {
3201 vp->specialStatus = VBUSY;
3203 vp->shuttingDown = 0;
3204 vp->goingOffline = 0;
3206 #ifdef AFS_DEMAND_ATTACH_FS
3207 vp->stats.last_attach = FT_ApproxTime();
3208 vp->stats.attaches++;
3212 IncUInt64(&VStats.attaches);
3213 vp->cacheCheck = ++VolumeCacheCheck;
3214 /* just in case this ever rolls over */
3215 if (!vp->cacheCheck)
3216 vp->cacheCheck = ++VolumeCacheCheck;
3219 #ifdef AFS_DEMAND_ATTACH_FS
3220 V_attachFlags(vp) |= VOL_HDR_LOADED;
3221 vp->stats.last_hdr_load = vp->stats.last_attach;
3222 #endif /* AFS_DEMAND_ATTACH_FS */
3226 struct IndexFileHeader iHead;
3229 * We just read in the diskstuff part of the header. If the detailed
3230 * volume stats area has not yet been initialized, we should bzero the
3231 * area and mark it as initialized.
3233 if (!(V_stat_initialized(vp))) {
3234 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3235 V_stat_initialized(vp) = 1;
3238 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3239 (char *)&iHead, sizeof(iHead),
3240 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3243 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3248 struct IndexFileHeader iHead;
3250 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3251 (char *)&iHead, sizeof(iHead),
3252 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3255 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3259 #ifdef AFS_NAMEI_ENV
3261 struct versionStamp stamp;
3263 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3264 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3267 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3270 #endif /* AFS_NAMEI_ENV */
3272 #if defined(AFS_DEMAND_ATTACH_FS)
3273 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3275 if (!VCanScheduleSalvage()) {
3276 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3278 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3283 /* volume operation in progress */
3285 /* we have already transitioned the vp away from ATTACHING state, so we
3286 * can go right to the end of attach2, and we do not need to transition
3288 goto error_notbroken;
3290 #else /* AFS_DEMAND_ATTACH_FS */
3292 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3293 goto unlocked_error;
3295 #endif /* AFS_DEMAND_ATTACH_FS */
3297 if (V_needsSalvaged(vp)) {
3298 if (vp->specialStatus)
3299 vp->specialStatus = 0;
3301 #if defined(AFS_DEMAND_ATTACH_FS)
3302 if (!VCanScheduleSalvage()) {
3303 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3305 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3308 #else /* AFS_DEMAND_ATTACH_FS */
3310 #endif /* AFS_DEMAND_ATTACH_FS */
3316 vp->nextVnodeUnique = V_uniquifier(vp);
3318 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3319 if (!V_needsSalvaged(vp)) {
3320 V_needsSalvaged(vp) = 1;
3321 VUpdateVolume_r(ec, vp, 0);
3323 #if defined(AFS_DEMAND_ATTACH_FS)
3324 if (!VCanScheduleSalvage()) {
3325 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3327 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3330 #else /* AFS_DEMAND_ATTACH_FS */
3331 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3333 #endif /* AFS_DEMAND_ATTACH_FS */
3338 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3339 /* Only check destroyMe if we are the fileserver, since the
3340 * volserver et al sometimes need to work with volumes with
3341 * destroyMe set. Examples are 'temporary' volumes the
3342 * volserver creates, and when we create a volume (destroyMe
3343 * is set on creation; sometimes a separate volserver
3344 * transaction is created to clear destroyMe).
3347 #if defined(AFS_DEMAND_ATTACH_FS)
3348 /* schedule a salvage so the volume goes away on disk */
3349 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3350 VChangeState_r(vp, VOL_STATE_ERROR);
3353 #endif /* AFS_DEMAND_ATTACH_FS */
3354 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3359 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3360 #ifndef BITMAP_LATER
3361 if (programType == fileServer && VolumeWriteable(vp)) {
3363 for (i = 0; i < nVNODECLASSES; i++) {
3364 VGetBitmap_r(ec, vp, i);
3366 #ifdef AFS_DEMAND_ATTACH_FS
3367 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3369 #endif /* AFS_DEMAND_ATTACH_FS */
3370 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3376 #endif /* BITMAP_LATER */
3378 if (VInit >= 2 && V_needsCallback(vp)) {
3379 if (V_BreakVolumeCallbacks) {
3380 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3381 afs_printable_uint32_lu(V_id(vp)));
3382 V_needsCallback(vp) = 0;
3384 (*V_BreakVolumeCallbacks) (V_id(vp));
3387 VUpdateVolume_r(ec, vp, 0);
3389 #ifdef FSSYNC_BUILD_CLIENT
3390 else if (VCanUseFSSYNC()) {
3391 afs_int32 fsync_code;
3393 V_needsCallback(vp) = 0;
3395 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3399 V_needsCallback(vp) = 1;
3400 Log("Error trying to tell the fileserver to break callbacks for "
3401 "changed volume %lu; error code %ld\n",
3402 afs_printable_uint32_lu(V_id(vp)),
3403 afs_printable_int32_ld(fsync_code));
3405 VUpdateVolume_r(ec, vp, 0);
3408 #endif /* FSSYNC_BUILD_CLIENT */
3411 Log("VAttachVolume: error %d clearing needsCallback on volume "
3412 "%lu; needs salvage\n", (int)*ec,
3413 afs_printable_uint32_lu(V_id(vp)));
3414 #ifdef AFS_DEMAND_ATTACH_FS
3415 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3417 #else /* !AFS_DEMAND_ATTACH_FS */
3419 #endif /* !AFS_DEMAND_ATTACh_FS */
3424 if (programType == fileServer) {
3425 if (vp->specialStatus)
3426 vp->specialStatus = 0;
3427 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3428 V_inUse(vp) = fileServer;
3429 V_offlineMessage(vp)[0] = '\0';
3433 #ifdef AFS_DEMAND_ATTACH_FS
3434 /* Put the vol into PREATTACHED state, so if someone tries to
3435 * access it again, we try to attach, see that we're not blessed,
3436 * and give a VNOVOL error again. Putting it into UNATTACHED state
3437 * would result in a VOFFLINE error instead. */
3438 error_state = VOL_STATE_PREATTACHED;
3439 #endif /* AFS_DEMAND_ATTACH_FS */
3441 /* mimic e.g. GetVolume errors */
3442 if (!V_blessed(vp)) {
3443 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3444 FreeVolumeHeader(vp);
3445 } else if (!V_inService(vp)) {
3446 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3447 FreeVolumeHeader(vp);
3449 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3451 #ifdef AFS_DEMAND_ATTACH_FS
3452 error_state = VOL_STATE_ERROR;
3453 /* see if we can recover */
3454 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3457 #ifdef AFS_DEMAND_ATTACH_FS
3463 #ifdef AFS_DEMAND_ATTACH_FS
3464 if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3465 V_inUse(vp) = programType;
3466 #endif /* AFS_DEMAND_ATTACH_FS */
3467 V_checkoutMode(vp) = mode;
3470 AddVolumeToHashTable(vp, V_id(vp));
3471 #ifdef AFS_DEMAND_ATTACH_FS
3472 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3475 if ((programType != fileServer) ||
3476 (V_inUse(vp) == fileServer)) {
3477 AddVolumeToVByPList_r(vp);
3479 VChangeState_r(vp, VOL_STATE_ATTACHED);
3481 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3490 #ifdef AFS_DEMAND_ATTACH_FS
3491 if (!VIsErrorState(V_attachState(vp))) {
3492 if (VIsErrorState(error_state)) {
3493 Log("attach2: forcing vol %u to error state (state %u flags 0x%x ec %d)\n",
3494 vp->hashid, V_attachState(vp), V_attachFlags(vp), *ec);
3496 VChangeState_r(vp, error_state);
3498 #endif /* AFS_DEMAND_ATTACH_FS */
3501 VReleaseVolumeHandles_r(vp);
3504 #ifdef AFS_DEMAND_ATTACH_FS
3506 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3507 /* The salvage could not be scheduled with the salvage server
3508 * due to a hard error. Reset the error code to prevent retry loops by
3510 if (*ec == VSALVAGING) {
3519 #else /* !AFS_DEMAND_ATTACH_FS */
3521 #endif /* !AFS_DEMAND_ATTACH_FS */
3525 /* Attach an existing volume.
3526 The volume also normally goes online at this time.
3527 An offline volume must be reattached to make it go online.
3531 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3535 retVal = VAttachVolume_r(ec, volumeId, mode);
3541 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3544 VGetVolumePath(ec, volumeId, &part, &name);
3548 vp = VGetVolume_r(&error, volumeId);
3550 opr_Assert(V_inUse(vp) == 0);
3551 VDetachVolume_r(ec, vp);
3555 return VAttachVolumeByName_r(ec, part, name, mode);
3558 /* Increment a reference count to a volume, sans context swaps. Requires
3559 * possibly reading the volume header in from the disk, since there's
3560 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3562 * N.B. This call can fail if we can't read in the header!! In this case
3563 * we still guarantee we won't context swap, but the ref count won't be
3564 * incremented (otherwise we'd violate the invariant).
3566 /* NOTE: with the demand attach fileserver extensions, the global lock
3567 * is dropped within VHold */
3568 #ifdef AFS_DEMAND_ATTACH_FS
3570 VHold_r(Volume * vp)
3574 VCreateReservation_r(vp);
3575 VWaitExclusiveState_r(vp);
3577 LoadVolumeHeader(&error, vp);
3579 VCancelReservation_r(vp);
3583 VCancelReservation_r(vp);
3586 #else /* AFS_DEMAND_ATTACH_FS */
3588 VHold_r(Volume * vp)
3592 LoadVolumeHeader(&error, vp);
3598 #endif /* AFS_DEMAND_ATTACH_FS */
3600 /**** volume timeout-related stuff ****/
3602 #ifdef AFS_PTHREAD_ENV
3604 static struct timespec *shutdown_timeout;
3605 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3608 VTimedOut(const struct timespec *ts)
3613 if (ts->tv_sec == 0) {
3614 /* short-circuit; this will have always timed out */
3618 code = gettimeofday(&tv, NULL);
3620 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3621 /* assume no timeout; failure mode is we just wait longer than normal
3622 * instead of returning errors when we shouldn't */
3626 if (tv.tv_sec < ts->tv_sec ||
3627 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3636 * Calculate an absolute timeout.
3638 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3639 * NULL, the memory is not touched
3640 * @param[in] timeout How long the timeout should be from now
3642 * @return timeout to use
3643 * @retval NULL no timeout; wait forever
3644 * @retval non-NULL the given value for "ts"
3648 static struct timespec *
3649 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3659 ts->tv_sec = ts->tv_nsec = 0;
3663 code = gettimeofday(&now, NULL);
3665 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3669 ts->tv_sec = now.tv_sec + timeout;
3670 ts->tv_nsec = now.tv_usec * 1000;
3676 * Initialize the shutdown_timeout global.
3679 VShutdownTimeoutInit(void)
3681 struct timespec *ts;
3683 ts = malloc(sizeof(*ts));
3685 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3687 if (!shutdown_timeout) {
3693 * Figure out the timeout that should be used for waiting for offline volumes.
3695 * @param[out] ats Storage space for a local timeout value if needed
3697 * @return The timeout value that should be used
3698 * @retval NULL No timeout; wait forever for offlining volumes
3699 * @retval non-NULL A pointer to the absolute time that should be used as
3700 * the deadline for waiting for offlining volumes.
3702 * @note If we return non-NULL, the pointer we return may or may not be the
3705 static const struct timespec *
3706 VOfflineTimeout(struct timespec *ats)
3708 if (vol_shutting_down) {
3709 opr_Verify(pthread_once(&shutdown_timeout_once,
3710 VShutdownTimeoutInit) == 0);
3711 return shutdown_timeout;
3713 return VCalcTimeout(ats, vol_opts.offline_timeout);
3717 #else /* AFS_PTHREAD_ENV */
3719 /* Waiting a certain amount of time for offlining volumes is not supported
3720 * for LWP due to a lack of primitives. So, we never time out */
3721 # define VTimedOut(x) (0)
3722 # define VOfflineTimeout(x) (NULL)
3724 #endif /* !AFS_PTHREAD_ENV */
3732 retVal = VHold_r(vp);
3739 VIsGoingOffline_r(struct Volume *vp)
3743 if (vp->goingOffline) {
3744 if (vp->specialStatus) {
3745 code = vp->specialStatus;
3746 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3757 * Tell the caller if a volume is waiting to go offline.
3759 * @param[in] vp The volume we want to know about
3761 * @return volume status
3762 * @retval 0 volume is not waiting to go offline, go ahead and use it
3763 * @retval nonzero volume is waiting to offline, and give the returned code
3764 * as an error to anyone accessing the volume
3766 * @pre VOL_LOCK is NOT held
3767 * @pre caller holds a heavyweight reference on vp
3770 VIsGoingOffline(struct Volume *vp)
3775 code = VIsGoingOffline_r(vp);
3782 * Register an RX call with a volume.
3784 * @param[inout] ec Error code; if unset when passed in, may be set if
3785 * the volume starts going offline
3786 * @param[out] client_ec @see GetVolume
3787 * @param[in] vp Volume struct
3788 * @param[in] cbv VCallByVol struct containing the RX call to register
3790 * @pre VOL_LOCK held
3791 * @pre caller holds heavy ref on vp
3796 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3799 #ifdef AFS_DEMAND_ATTACH_FS
3801 /* just in case the volume started going offline after we got the
3802 * reference to it... otherwise, if the volume started going
3803 * offline right at the end of GetVolume(), we might race with the
3804 * RX call scanner, and return success and add our cbv to the
3805 * rx_call_list _after_ the scanner has scanned the list. */
3806 *ec = VIsGoingOffline_r(vp);
3812 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3813 VWaitStateChange_r(vp);
3815 #endif /* AFS_DEMAND_ATTACH_FS */
3817 queue_Prepend(&vp->rx_call_list, cbv);
3822 * Deregister an RX call with a volume.
3824 * @param[in] vp Volume struct
3825 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3827 * @pre VOL_LOCK held
3828 * @pre caller holds heavy ref on vp
3833 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3835 if (cbv && queue_IsOnQueue(cbv)) {
3836 #ifdef AFS_DEMAND_ATTACH_FS
3837 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3838 VWaitStateChange_r(vp);
3840 #endif /* AFS_DEMAND_ATTACH_FS */
3846 /***************************************************/
3847 /* get and put volume routines */
3848 /***************************************************/
3851 * put back a heavyweight reference to a volume object.
3853 * @param[in] vp volume object pointer
3855 * @pre VOL_LOCK held
3857 * @post heavyweight volume reference put back.
3858 * depending on state, volume may have been taken offline,
3859 * detached, salvaged, freed, etc.
3861 * @internal volume package internal use only
3864 VPutVolume_r(Volume * vp)
3866 opr_Verify(--vp->nUsers >= 0);
3867 if (vp->nUsers == 0) {
3869 ReleaseVolumeHeader(vp->header);
3870 #ifdef AFS_DEMAND_ATTACH_FS
3871 if (!VCheckDetach(vp)) {
3875 #else /* AFS_DEMAND_ATTACH_FS */
3877 #endif /* AFS_DEMAND_ATTACH_FS */
3882 VPutVolume(Volume * vp)
3890 * Puts a volume reference obtained with VGetVolumeWithCall.
3892 * @param[in] vp Volume struct
3893 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3895 * @pre VOL_LOCK is NOT held
3898 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3901 VDeregisterCall_r(vp, cbv);
3906 /* Get a pointer to an attached volume. The pointer is returned regardless
3907 of whether or not the volume is in service or on/off line. An error
3908 code, however, is returned with an indication of the volume's status */
3910 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3914 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3920 * Get a volume reference associated with an RX call.
3922 * @param[out] ec @see GetVolume
3923 * @param[out] client_ec @see GetVolume
3924 * @param[in] volumeId @see GetVolume
3925 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3926 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3927 * with an error if the volume is going offline.
3928 * @param[in] cbv Contains an RX call to be associated with this volume
3929 * reference. This call may be interrupted if the volume is
3930 * requested to go offline while we hold a ref on it. Give NULL
3931 * to not associate an RX call with this reference.
3933 * @return @see GetVolume
3935 * @note for LWP builds, ts must be NULL
3937 * @note A reference obtained with this function MUST be put back with
3938 * VPutVolumeWithCall
3941 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3942 const struct timespec *ts, struct VCallByVol *cbv)
3946 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3947 VRegisterCall_r(ec, client_ec, retVal, cbv);
3953 VGetVolume_r(Error * ec, VolId volumeId)
3955 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3958 /* try to get a volume we've previously looked up */
3959 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3961 VGetVolumeByVp_r(Error * ec, Volume * vp)
3963 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3967 * private interface for getting a volume handle
3969 * @param[out] ec error code (0 if no error)
3970 * @param[out] client_ec wire error code to be given to clients
3971 * @param[in] volumeId ID of the volume we want
3972 * @param[in] hint optional hint for hash lookups, or NULL
3973 * @param[in] timeout absolute deadline for waiting for the volume to go
3974 * offline, if it is going offline. NULL to wait forever.
3976 * @return a volume handle for the specified volume
3977 * @retval NULL an error occurred, or the volume is in such a state that
3978 * we cannot load a header or return any volume struct
3980 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3982 * @note 'timeout' is only checked if the volume is actually going offline; so
3983 * if you pass timeout->tv_sec = 0, this will exhibit typical
3984 * nonblocking behavior.
3986 * @note for LWP builds, 'timeout' must be NULL
3989 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3990 const struct timespec *timeout)
3993 /* pull this profiling/debugging code out of regular builds */
3995 #define VGET_CTR_INC(x) x++
3996 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3997 0, V7 = 0, V8 = 0, V9 = 0;
3998 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
4000 #define VGET_CTR_INC(x)
4002 #ifdef AFS_DEMAND_ATTACH_FS
4003 Volume *avp, * rvp = hint;
4007 * if VInit is zero, the volume package dynamic
4008 * data structures have not been initialized yet,
4009 * and we must immediately return an error
4015 *client_ec = VOFFLINE;
4020 #ifdef AFS_DEMAND_ATTACH_FS
4022 VCreateReservation_r(rvp);
4024 #endif /* AFS_DEMAND_ATTACH_FS */
4032 vp = VLookupVolume_r(ec, volumeId, vp);
4038 #ifdef AFS_DEMAND_ATTACH_FS
4039 if (rvp && (rvp != vp)) {
4040 /* break reservation on old vp */
4041 VCancelReservation_r(rvp);
4044 #endif /* AFS_DEMAND_ATTACH_FS */
4050 /* Until we have reached an initialization level of 2
4051 * we don't know whether this volume exists or not.
4052 * We can't sleep and retry later because before a volume
4053 * is attached, the caller tries to get it first. Just
4054 * return VOFFLINE and the caller can choose whether to
4055 * retry the command or not. */
4065 IncUInt64(&VStats.hdr_gets);
4067 #ifdef AFS_DEMAND_ATTACH_FS
4068 /* block if someone else is performing an exclusive op on this volume */
4071 VCreateReservation_r(rvp);
4073 VWaitExclusiveState_r(vp);
4075 /* short circuit with VNOVOL in the following circumstances:
4078 * - VOL_STATE_SHUTTING_DOWN
4080 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4081 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4088 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4089 * VNOVOL for VOL_STATE_DELETED
4091 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4092 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4093 (V_attachState(vp) == VOL_STATE_DELETED)) {
4094 if (vp->specialStatus) {
4095 *ec = vp->specialStatus;
4096 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4105 /* allowable states:
4112 if (vp->salvage.requested) {
4113 VUpdateSalvagePriority_r(vp);
4116 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4117 if (vp->specialStatus) {
4118 *ec = vp->specialStatus;
4122 avp = VAttachVolumeByVp_r(ec, vp, 0);
4125 /* VAttachVolumeByVp_r can return a pointer
4126 * != the vp passed to it under certain
4127 * conditions; make sure we don't leak
4128 * reservations if that happens */
4130 VCancelReservation_r(rvp);
4132 VCreateReservation_r(rvp);
4143 if (vp->specialStatus) {
4144 *ec = vp->specialStatus;
4149 if (vp->specialStatus) {
4150 *ec = vp->specialStatus;
4163 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4165 /* see CheckVnode() in afsfileprocs.c for an explanation
4166 * of this error code logic */
4167 afs_uint32 now = FT_ApproxTime();
4168 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4171 *client_ec = VRESTARTING;
4179 if (VIsErrorState(V_attachState(vp))) {
4180 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4181 * it, or transition it out of that state */
4190 * this test MUST happen after VAttachVolymeByVp, so we have no
4191 * conflicting vol op. (attach2 would have errored out if we had one;
4192 * specifically attach_check_vop must have detected a conflicting vop)
4194 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4196 #endif /* AFS_DEMAND_ATTACH_FS */
4198 LoadVolumeHeader(ec, vp);
4201 /* Only log the error if it was a totally unexpected error. Simply
4202 * a missing inode is likely to be caused by the volume being deleted */
4203 if (errno != ENXIO || LogLevel)
4204 Log("Volume %u: couldn't reread volume header\n",
4206 #ifdef AFS_DEMAND_ATTACH_FS
4207 if (VCanScheduleSalvage()) {
4208 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4213 #else /* AFS_DEMAND_ATTACH_FS */
4216 #endif /* AFS_DEMAND_ATTACH_FS */
4221 if (vp->shuttingDown) {
4228 if (programType == fileServer) {
4230 if (vp->goingOffline) {
4231 if (timeout && VTimedOut(timeout)) {
4232 /* we've timed out; don't wait for the vol */
4235 #ifdef AFS_DEMAND_ATTACH_FS
4236 /* wait for the volume to go offline */
4237 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4238 VTimedWaitStateChange_r(vp, timeout, NULL);
4240 #elif defined(AFS_PTHREAD_ENV)
4241 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4242 #else /* AFS_PTHREAD_ENV */
4243 /* LWP has no timed wait, so the caller better not be
4245 opr_Assert(!timeout);
4246 LWP_WaitProcess(VPutVolume);
4247 #endif /* AFS_PTHREAD_ENV */
4251 if (vp->specialStatus) {
4253 *ec = vp->specialStatus;
4254 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4257 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4268 #ifdef AFS_DEMAND_ATTACH_FS
4269 /* if no error, bump nUsers */
4272 VLRU_UpdateAccess_r(vp);
4275 VCancelReservation_r(rvp);
4278 if (client_ec && !*client_ec) {
4281 #else /* AFS_DEMAND_ATTACH_FS */
4282 /* if no error, bump nUsers */
4289 #endif /* AFS_DEMAND_ATTACH_FS */
4292 opr_Assert(vp || *ec);
4297 /***************************************************/
4298 /* Volume offline/detach routines */
4299 /***************************************************/
4301 /* caller MUST hold a heavyweight ref on vp */
4302 #ifdef AFS_DEMAND_ATTACH_FS
4304 VTakeOffline_r(Volume * vp)
4308 opr_Assert(vp->nUsers > 0);
4309 opr_Assert(programType == fileServer);
4311 VCreateReservation_r(vp);
4312 VWaitExclusiveState_r(vp);
4314 vp->goingOffline = 1;
4315 V_needsSalvaged(vp) = 1;
4317 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4318 VCancelReservation_r(vp);
4320 #else /* AFS_DEMAND_ATTACH_FS */
4322 VTakeOffline_r(Volume * vp)
4324 opr_Assert(vp->nUsers > 0);
4325 opr_Assert(programType == fileServer);
4327 vp->goingOffline = 1;
4328 V_needsSalvaged(vp) = 1;
4330 #endif /* AFS_DEMAND_ATTACH_FS */
4333 VTakeOffline(Volume * vp)
4341 * force a volume offline.
4343 * @param[in] vp volume object pointer
4344 * @param[in] flags flags (see note below)
4346 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4347 * used when VUpdateVolume_r needs to call VForceOffline_r
4348 * (which in turn would normally call VUpdateVolume_r)
4350 * @see VUpdateVolume_r
4352 * @pre VOL_LOCK must be held.
4353 * for DAFS, caller must hold ref.
4355 * @note for DAFS, it _is safe_ to call this function from an
4358 * @post needsSalvaged flag is set.
4359 * for DAFS, salvage is requested.
4360 * no further references to the volume through the volume
4361 * package will be honored.
4362 * all file descriptor and vnode caches are invalidated.
4364 * @warning this is a heavy-handed interface. it results in
4365 * a volume going offline regardless of the current
4366 * reference count state.
4368 * @internal volume package internal use only
4371 VForceOffline_r(Volume * vp, int flags)
4375 #ifdef AFS_DEMAND_ATTACH_FS
4376 VChangeState_r(vp, VOL_STATE_ERROR);
4381 strcpy(V_offlineMessage(vp),
4382 "Forced offline due to internal error: volume needs to be salvaged");
4383 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4386 vp->goingOffline = 0;
4387 V_needsSalvaged(vp) = 1;
4388 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4389 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4392 #ifdef AFS_DEMAND_ATTACH_FS
4393 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4394 #endif /* AFS_DEMAND_ATTACH_FS */
4396 #ifdef AFS_PTHREAD_ENV
4397 opr_cv_broadcast(&vol_put_volume_cond);
4398 #else /* AFS_PTHREAD_ENV */
4399 LWP_NoYieldSignal(VPutVolume);
4400 #endif /* AFS_PTHREAD_ENV */
4402 VReleaseVolumeHandles_r(vp);
4406 * force a volume offline.
4408 * @param[in] vp volume object pointer
4410 * @see VForceOffline_r
4413 VForceOffline(Volume * vp)
4416 VForceOffline_r(vp, 0);
4421 * Iterate over the RX calls associated with a volume, and interrupt them.
4423 * @param[in] vp The volume whose RX calls we want to scan
4425 * @pre VOL_LOCK held
4428 VScanCalls_r(struct Volume *vp)
4430 struct VCallByVol *cbv, *ncbv;
4432 #ifdef AFS_DEMAND_ATTACH_FS
4433 VolState state_save;
4436 if (queue_IsEmpty(&vp->rx_call_list))
4437 return; /* no calls to interrupt */
4438 if (!vol_opts.interrupt_rxcall)
4439 return; /* we have no function with which to interrupt calls */
4440 err = VIsGoingOffline_r(vp);
4442 return; /* we're not going offline anymore */
4444 #ifdef AFS_DEMAND_ATTACH_FS
4445 VWaitExclusiveState_r(vp);
4446 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4448 #endif /* AFS_DEMAND_ATTACH_FS */
4450 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4452 struct rx_peer *peer;
4454 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4456 Log("Offlining volume %lu while client %s:%u is trying to read "
4457 "from it; kicking client off with error %ld\n",
4458 (long unsigned) vp->hashid,
4459 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4460 (unsigned) ntohs(rx_PortOf(peer)),
4463 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4466 #ifdef AFS_DEMAND_ATTACH_FS
4468 VChangeState_r(vp, state_save);
4469 #endif /* AFS_DEMAND_ATTACH_FS */
4472 #ifdef AFS_DEMAND_ATTACH_FS
4474 * Wait for a vp to go offline.
4476 * @param[out] ec 1 if a salvage on the volume has been requested and
4477 * salvok == 0, 0 otherwise
4478 * @param[in] vp The volume to wait for
4479 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4480 * has been requested to salvage. Otherwise we keep waiting
4481 * until the volume has gone offline.
4483 * @pre VOL_LOCK held
4484 * @pre caller holds a lightweight ref on vp
4489 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4491 struct timespec timeout_ts;
4492 const struct timespec *ts;
4495 ts = VOfflineTimeout(&timeout_ts);
4499 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4500 if (!salvok && vp->salvage.requested) {
4504 VTimedWaitStateChange_r(vp, ts, &timedout);
4507 /* we didn't time out, so the volume must be offline, so we're done */
4511 /* If we got here, we timed out waiting for the volume to go offline.
4512 * Kick off the accessing RX calls and wait again */
4516 while (!VIsOfflineState(V_attachState(vp))) {
4517 if (!salvok && vp->salvage.requested) {
4522 VWaitStateChange_r(vp);
4526 #else /* AFS_DEMAND_ATTACH_FS */
4529 * Wait for a volume to go offline.
4531 * @pre VOL_LOCK held
4533 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4536 VWaitForOffline_r(Error *ec, VolumeId volid)
4539 const struct timespec *ts;
4540 #ifdef AFS_PTHREAD_ENV
4541 struct timespec timeout_ts;
4544 ts = VOfflineTimeout(&timeout_ts);
4546 vp = GetVolume(ec, NULL, volid, NULL, ts);
4548 /* error occurred so bad that we can't even get a vp; we have no
4549 * information on the vol so we don't know whether to wait, so just
4553 if (!VIsGoingOffline_r(vp)) {
4554 /* volume is no longer going offline, so we're done */
4559 /* If we got here, we timed out waiting for the volume to go offline.
4560 * Kick off the accessing RX calls and wait again */
4566 vp = VGetVolume_r(ec, volid);
4568 /* In case it was reattached... */
4572 #endif /* !AFS_DEMAND_ATTACH_FS */
4574 /* The opposite of VAttachVolume. The volume header is written to disk, with
4575 the inUse bit turned off. A copy of the header is maintained in memory,
4576 however (which is why this is VOffline, not VDetach).
4579 VOffline_r(Volume * vp, char *message)
4582 #ifndef AFS_DEMAND_ATTACH_FS
4583 VolumeId vid = V_id(vp);
4586 opr_Assert(programType != volumeUtility && programType != volumeServer);
4591 if (V_offlineMessage(vp)[0] == '\0')
4592 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4593 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4595 vp->goingOffline = 1;
4596 #ifdef AFS_DEMAND_ATTACH_FS
4597 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4598 VCreateReservation_r(vp);
4600 VWaitForOfflineByVp_r(&error, vp, 1);
4601 VCancelReservation_r(vp);
4602 #else /* AFS_DEMAND_ATTACH_FS */
4604 VWaitForOffline_r(&error, vid);
4605 #endif /* AFS_DEMAND_ATTACH_FS */
4608 #ifdef AFS_DEMAND_ATTACH_FS
4610 * Take a volume offline in order to perform a volume operation.
4612 * @param[inout] ec address in which to store error code
4613 * @param[in] vp volume object pointer
4614 * @param[in] message volume offline status message
4617 * - VOL_LOCK is held
4618 * - caller MUST hold a heavyweight ref on vp
4621 * - volume is taken offline
4622 * - if possible, volume operation is promoted to running state
4623 * - on failure, *ec is set to nonzero
4625 * @note Although this function does not return any value, it may
4626 * still fail to promote our pending volume operation to
4627 * a running state. Any caller MUST check the value of *ec,
4628 * and MUST NOT blindly assume success.
4630 * @warning if the caller does not hold a lightweight ref on vp,
4631 * then it MUST NOT reference vp after this function
4632 * returns to the caller.
4634 * @internal volume package internal use only
4637 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4640 opr_Assert(vp->pending_vol_op);
4646 if (V_offlineMessage(vp)[0] == '\0')
4647 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4648 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4650 vp->goingOffline = 1;
4651 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4652 VCreateReservation_r(vp);
4655 if (vp->pending_vol_op->com.programType != salvageServer) {
4656 /* do not give corrupted volumes to the volserver */
4661 VWaitForOfflineByVp_r(ec, vp, salvok);
4663 VCancelReservation_r(vp);
4665 #endif /* AFS_DEMAND_ATTACH_FS */
4668 VOffline(Volume * vp, char *message)
4671 VOffline_r(vp, message);
4675 /* This gets used for the most part by utility routines that don't want
4676 * to keep all the volume headers around. Generally, the file server won't
4677 * call this routine, because then the offline message in the volume header
4678 * (or other information) won't be available to clients. For NAMEI, also
4679 * close the file handles. However, the fileserver does call this during
4680 * an attach following a volume operation.
4683 VDetachVolume_r(Error * ec, Volume * vp)
4685 #ifdef FSSYNC_BUILD_CLIENT
4687 struct DiskPartition64 *tpartp;
4688 int notifyServer = 0;
4689 int useDone = FSYNC_VOL_ON;
4691 if (VCanUseFSSYNC()) {
4692 notifyServer = vp->needsPutBack;
4693 if (V_destroyMe(vp) == DESTROY_ME)
4694 useDone = FSYNC_VOL_LEAVE_OFF;
4695 # ifdef AFS_DEMAND_ATTACH_FS
4696 else if (!V_blessed(vp) || !V_inService(vp))
4697 useDone = FSYNC_VOL_LEAVE_OFF;
4700 # ifdef AFS_DEMAND_ATTACH_FS
4701 if (V_needsSalvaged(vp)) {
4703 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4706 tpartp = vp->partition;
4708 #endif /* FSSYNC_BUILD_CLIENT */
4710 *ec = 0; /* always "succeeds" */
4711 DeleteVolumeFromHashTable(vp);
4712 vp->shuttingDown = 1;
4713 #ifdef AFS_DEMAND_ATTACH_FS
4714 DeleteVolumeFromVByPList_r(vp);
4716 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4718 if (programType != fileServer)
4720 #endif /* AFS_DEMAND_ATTACH_FS */
4722 /* Will be detached sometime in the future--this is OK since volume is offline */
4724 /* XXX the following code should really be moved to VCheckDetach() since the volume
4725 * is not technically detached until the refcounts reach zero
4727 #ifdef FSSYNC_BUILD_CLIENT
4728 if (VCanUseFSSYNC() && notifyServer) {
4729 if (notifyServer == VOL_PUTBACK_DELETE) {
4730 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4731 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4732 * to signify a deleted volume. */
4733 useDone = FSYNC_VOL_DONE;
4736 * Note: The server is not notified in the case of a bogus volume
4737 * explicitly to make it possible to create a volume, do a partial
4738 * restore, then abort the operation without ever putting the volume
4739 * online. This is essential in the case of a volume move operation
4740 * between two partitions on the same server. In that case, there
4741 * would be two instances of the same volume, one of them bogus,
4742 * which the file server would attempt to put on line
4744 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4745 /* XXX this code path is only hit by volume utilities, thus
4746 * V_BreakVolumeCallbacks will always be NULL. if we really
4747 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4749 /* Dettaching it so break all callbacks on it */
4750 if (V_BreakVolumeCallbacks) {
4751 Log("volume %u detached; breaking all call backs\n", volume);
4752 (*V_BreakVolumeCallbacks) (volume);
4756 #endif /* FSSYNC_BUILD_CLIENT */
4760 VDetachVolume(Error * ec, Volume * vp)
4763 VDetachVolume_r(ec, vp);
4768 /***************************************************/
4769 /* Volume fd/inode handle closing routines */
4770 /***************************************************/
4772 /* For VDetachVolume, we close all cached file descriptors, but keep
4773 * the Inode handles in case we need to read from a busy volume.
4775 /* for demand attach, caller MUST hold ref count on vp */
4777 VCloseVolumeHandles_r(Volume * vp)
4779 #ifdef AFS_DEMAND_ATTACH_FS
4780 VolState state_save;
4782 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4787 DFlushVolume(vp->hashid);
4789 #ifdef AFS_DEMAND_ATTACH_FS
4793 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4794 VCloseVnodeFiles_r(vp);
4796 #ifdef AFS_DEMAND_ATTACH_FS
4800 /* Too time consuming and unnecessary for the volserver */
4801 if (programType == fileServer) {
4802 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4803 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4804 IH_CONDSYNC(vp->diskDataHandle);
4806 IH_CONDSYNC(vp->linkHandle);
4807 #endif /* AFS_NT40_ENV */
4810 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4811 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4812 IH_REALLYCLOSE(vp->diskDataHandle);
4813 IH_REALLYCLOSE(vp->linkHandle);
4815 #ifdef AFS_DEMAND_ATTACH_FS
4816 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4821 VChangeState_r(vp, state_save);
4825 /* For both VForceOffline and VOffline, we close all relevant handles.
4826 * For VOffline, if we re-attach the volume, the files may possible be
4827 * different than before.
4829 /* for demand attach, caller MUST hold a ref count on vp */
4831 VReleaseVolumeHandles_r(Volume * vp)
4833 #ifdef AFS_DEMAND_ATTACH_FS
4834 VolState state_save;
4836 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4841 DFlushVolume(vp->hashid);
4843 #ifdef AFS_DEMAND_ATTACH_FS
4847 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4849 #ifdef AFS_DEMAND_ATTACH_FS
4853 /* Too time consuming and unnecessary for the volserver */
4854 if (programType == fileServer) {
4855 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4856 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4857 IH_CONDSYNC(vp->diskDataHandle);
4859 IH_CONDSYNC(vp->linkHandle);
4860 #endif /* AFS_NT40_ENV */
4863 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4864 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4865 IH_RELEASE(vp->diskDataHandle);
4866 IH_RELEASE(vp->linkHandle);
4868 #ifdef AFS_DEMAND_ATTACH_FS
4869 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4874 VChangeState_r(vp, state_save);
4879 /***************************************************/
4880 /* Volume write and fsync routines */
4881 /***************************************************/
4884 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4886 #ifdef AFS_DEMAND_ATTACH_FS
4887 VolState state_save;
4889 if (flags & VOL_UPDATE_WAIT) {
4890 VCreateReservation_r(vp);
4891 VWaitExclusiveState_r(vp);
4896 if (programType == fileServer)
4898 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4899 200 : V_nextVnodeUnique(vp));
4901 #ifdef AFS_DEMAND_ATTACH_FS
4902 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4906 WriteVolumeHeader_r(ec, vp);
4908 #ifdef AFS_DEMAND_ATTACH_FS
4910 VChangeState_r(vp, state_save);
4911 if (flags & VOL_UPDATE_WAIT) {
4912 VCancelReservation_r(vp);
4917 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4918 V_id(vp), V_name(vp));
4919 /* try to update on-disk header,
4920 * while preventing infinite recursion */
4921 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4922 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4928 VUpdateVolume(Error * ec, Volume * vp)
4931 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4936 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4940 #ifdef AFS_DEMAND_ATTACH_FS
4941 VolState state_save;
4944 if (flags & VOL_SYNC_WAIT) {
4945 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4947 VUpdateVolume_r(ec, vp, 0);
4950 #ifdef AFS_DEMAND_ATTACH_FS
4951 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4954 fdP = IH_OPEN(V_diskDataHandle(vp));
4955 opr_Assert(fdP != NULL);
4956 code = FDH_SYNC(fdP);
4957 opr_Assert(code == 0);
4959 #ifdef AFS_DEMAND_ATTACH_FS
4961 VChangeState_r(vp, state_save);
4967 VSyncVolume(Error * ec, Volume * vp)
4970 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4975 /***************************************************/
4976 /* Volume dealloaction routines */
4977 /***************************************************/
4979 #ifdef AFS_DEMAND_ATTACH_FS
4981 FreeVolume(Volume * vp)
4983 /* free the heap space, iff it's safe.
4984 * otherwise, pull it out of the hash table, so it
4985 * will get deallocated when all refs to it go away */
4986 if (!VCheckFree(vp)) {
4987 DeleteVolumeFromHashTable(vp);
4988 DeleteVolumeFromVByPList_r(vp);
4990 /* make sure we invalidate the header cache entry */
4991 FreeVolumeHeader(vp);
4994 #endif /* AFS_DEMAND_ATTACH_FS */
4997 ReallyFreeVolume(Volume * vp)
5002 #ifdef AFS_DEMAND_ATTACH_FS
5004 VChangeState_r(vp, VOL_STATE_FREED);
5005 if (vp->pending_vol_op)
5006 free(vp->pending_vol_op);
5007 #endif /* AFS_DEMAND_ATTACH_FS */
5008 for (i = 0; i < nVNODECLASSES; i++)
5009 if (vp->vnodeIndex[i].bitmap)
5010 free(vp->vnodeIndex[i].bitmap);
5011 FreeVolumeHeader(vp);
5012 #ifndef AFS_DEMAND_ATTACH_FS
5013 DeleteVolumeFromHashTable(vp);
5014 #endif /* AFS_DEMAND_ATTACH_FS */
5018 /* check to see if we should shutdown this volume
5019 * returns 1 if volume was freed, 0 otherwise */
5020 #ifdef AFS_DEMAND_ATTACH_FS
5022 VCheckDetach(Volume * vp)
5027 if (vp->nUsers || vp->nWaiters)
5030 if (vp->shuttingDown) {
5032 if ((programType != fileServer) &&
5033 (V_inUse(vp) == programType) &&
5034 ((V_checkoutMode(vp) == V_VOLUPD) ||
5035 (V_checkoutMode(vp) == V_SECRETLY) ||
5036 ((V_checkoutMode(vp) == V_CLONE) &&
5037 (VolumeWriteable(vp))))) {
5039 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5041 Log("VCheckDetach: volume header update for volume %u "
5042 "failed with errno %d\n", vp->hashid, errno);
5045 VReleaseVolumeHandles_r(vp);
5047 ReallyFreeVolume(vp);
5048 if (programType == fileServer) {
5049 opr_cv_broadcast(&vol_put_volume_cond);
5054 #else /* AFS_DEMAND_ATTACH_FS */
5056 VCheckDetach(Volume * vp)
5064 if (vp->shuttingDown) {
5066 if ((programType != fileServer) &&
5067 (V_inUse(vp) == programType) &&
5068 ((V_checkoutMode(vp) == V_VOLUPD) ||
5069 (V_checkoutMode(vp) == V_SECRETLY) ||
5070 ((V_checkoutMode(vp) == V_CLONE) &&
5071 (VolumeWriteable(vp))))) {
5073 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5075 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5079 VReleaseVolumeHandles_r(vp);
5080 ReallyFreeVolume(vp);
5081 if (programType == fileServer) {
5082 #if defined(AFS_PTHREAD_ENV)
5083 opr_cv_broadcast(&vol_put_volume_cond);
5084 #else /* AFS_PTHREAD_ENV */
5085 LWP_NoYieldSignal(VPutVolume);
5086 #endif /* AFS_PTHREAD_ENV */
5091 #endif /* AFS_DEMAND_ATTACH_FS */
5093 /* check to see if we should offline this volume
5094 * return 1 if volume went offline, 0 otherwise */
5095 #ifdef AFS_DEMAND_ATTACH_FS
5097 VCheckOffline(Volume * vp)
5101 if (vp->goingOffline && !vp->nUsers) {
5103 opr_Assert(programType == fileServer);
5104 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5105 (V_attachState(vp) != VOL_STATE_FREED) &&
5106 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5107 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5108 (V_attachState(vp) != VOL_STATE_DELETED));
5112 * VOL_STATE_GOING_OFFLINE
5113 * VOL_STATE_SHUTTING_DOWN
5114 * VIsErrorState(V_attachState(vp))
5115 * VIsExclusiveState(V_attachState(vp))
5118 VCreateReservation_r(vp);
5119 VChangeState_r(vp, VOL_STATE_OFFLINING);
5122 /* must clear the goingOffline flag before we drop the glock */
5123 vp->goingOffline = 0;
5128 /* perform async operations */
5129 VUpdateVolume_r(&error, vp, 0);
5130 VCloseVolumeHandles_r(vp);
5133 if (V_offlineMessage(vp)[0]) {
5134 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5135 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5136 V_offlineMessage(vp));
5138 Log("VOffline: Volume %lu (%s) is now offline\n",
5139 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5143 /* invalidate the volume header cache entry */
5144 FreeVolumeHeader(vp);
5146 /* if nothing changed state to error or salvaging,
5147 * drop state to unattached */
5148 if (!VIsErrorState(V_attachState(vp))) {
5149 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5151 VCancelReservation_r(vp);
5152 /* no usage of vp is safe beyond this point */
5156 #else /* AFS_DEMAND_ATTACH_FS */
5158 VCheckOffline(Volume * vp)
5162 if (vp->goingOffline && !vp->nUsers) {
5164 opr_Assert(programType == fileServer);
5167 vp->goingOffline = 0;
5169 VUpdateVolume_r(&error, vp, 0);
5170 VCloseVolumeHandles_r(vp);
5172 if (V_offlineMessage(vp)[0]) {
5173 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5174 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5175 V_offlineMessage(vp));
5177 Log("VOffline: Volume %lu (%s) is now offline\n",
5178 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5181 FreeVolumeHeader(vp);
5182 #ifdef AFS_PTHREAD_ENV
5183 opr_cv_broadcast(&vol_put_volume_cond);
5184 #else /* AFS_PTHREAD_ENV */
5185 LWP_NoYieldSignal(VPutVolume);
5186 #endif /* AFS_PTHREAD_ENV */
5190 #endif /* AFS_DEMAND_ATTACH_FS */
5192 /***************************************************/
5193 /* demand attach fs ref counting routines */
5194 /***************************************************/
5196 #ifdef AFS_DEMAND_ATTACH_FS
5197 /* the following two functions handle reference counting for
5198 * asynchronous operations on volume structs.
5200 * their purpose is to prevent a VDetachVolume or VShutdown
5201 * from free()ing the Volume struct during an async i/o op */
5203 /* register with the async volume op ref counter */
5204 /* VCreateReservation_r moved into inline code header because it
5205 * is now needed in vnode.c -- tkeiser 11/20/2007
5209 * decrement volume-package internal refcount.
5211 * @param vp volume object pointer
5213 * @internal volume package internal use only
5216 * @arg VOL_LOCK is held
5217 * @arg lightweight refcount held
5219 * @post volume waiters refcount is decremented; volume may
5220 * have been deallocated/shutdown/offlined/salvaged/
5221 * whatever during the process
5223 * @warning once you have tossed your last reference (you can acquire
5224 * lightweight refs recursively) it is NOT SAFE to reference
5225 * a volume object pointer ever again
5227 * @see VCreateReservation_r
5229 * @note DEMAND_ATTACH_FS only
5232 VCancelReservation_r(Volume * vp)
5234 opr_Verify(--vp->nWaiters >= 0);
5235 if (vp->nWaiters == 0) {
5237 if (!VCheckDetach(vp)) {
5244 /* check to see if we should free this volume now
5245 * return 1 if volume was freed, 0 otherwise */
5247 VCheckFree(Volume * vp)
5250 if ((vp->nUsers == 0) &&
5251 (vp->nWaiters == 0) &&
5252 !(V_attachFlags(vp) & (VOL_IN_HASH |
5256 ReallyFreeVolume(vp);
5261 #endif /* AFS_DEMAND_ATTACH_FS */
5264 /***************************************************/
5265 /* online volume operations routines */
5266 /***************************************************/
5268 #ifdef AFS_DEMAND_ATTACH_FS
5270 * register a volume operation on a given volume.
5272 * @param[in] vp volume object
5273 * @param[in] vopinfo volume operation info object
5275 * @pre VOL_LOCK is held
5277 * @post volume operation info object attached to volume object.
5278 * volume operation statistics updated.
5280 * @note by "attached" we mean a copy of the passed in object is made
5282 * @internal volume package internal use only
5285 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5287 FSSYNC_VolOp_info * info;
5289 /* attach a vol op info node to the volume struct */
5290 info = malloc(sizeof(FSSYNC_VolOp_info));
5291 opr_Assert(info != NULL);
5292 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5293 vp->pending_vol_op = info;
5296 vp->stats.last_vol_op = FT_ApproxTime();
5297 vp->stats.vol_ops++;
5298 IncUInt64(&VStats.vol_ops);
5304 * deregister the volume operation attached to this volume.
5306 * @param[in] vp volume object pointer
5308 * @pre VOL_LOCK is held
5310 * @post the volume operation info object is detached from the volume object
5312 * @internal volume package internal use only
5315 VDeregisterVolOp_r(Volume * vp)
5317 if (vp->pending_vol_op) {
5318 free(vp->pending_vol_op);
5319 vp->pending_vol_op = NULL;
5323 #endif /* AFS_DEMAND_ATTACH_FS */
5326 * determine whether it is safe to leave a volume online during
5327 * the volume operation described by the vopinfo object.
5329 * @param[in] vp volume object
5330 * @param[in] vopinfo volume operation info object
5332 * @return whether it is safe to leave volume online
5333 * @retval 0 it is NOT SAFE to leave the volume online
5334 * @retval 1 it is safe to leave the volume online during the operation
5337 * @arg VOL_LOCK is held
5338 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5339 * this condition is met)
5341 * @internal volume package internal use only
5344 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5346 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5347 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5348 (vopinfo->com.reason == V_READONLY ||
5349 (!VolumeWriteable(vp) &&
5350 (vopinfo->com.reason == V_CLONE ||
5351 vopinfo->com.reason == V_DUMP)))));
5355 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5358 * @param[in] vp volume object
5359 * @param[in] vopinfo volume operation info object
5361 * @return whether it is safe to leave volume online
5362 * @retval 0 it is NOT SAFE to leave the volume online
5363 * @retval 1 it is safe to leave the volume online during the operation
5364 * @retval -1 unsure; volume header is required in order to know whether or
5365 * not is is safe to leave the volume online
5367 * @pre VOL_LOCK is held
5369 * @internal volume package internal use only
5372 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5374 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5375 * assume that we don't know VolumeWriteable; return -1 if the answer
5376 * depends on VolumeWriteable */
5378 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5381 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5382 vopinfo->com.reason == V_READONLY) {
5386 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5387 (vopinfo->com.reason == V_CLONE ||
5388 vopinfo->com.reason == V_DUMP)) {
5390 /* must know VolumeWriteable */
5397 * determine whether VBUSY should be set during this volume operation.
5399 * @param[in] vp volume object
5400 * @param[in] vopinfo volume operation info object
5402 * @return whether VBUSY should be set
5403 * @retval 0 VBUSY does NOT need to be set
5404 * @retval 1 VBUSY SHOULD be set
5406 * @pre VOL_LOCK is held
5408 * @internal volume package internal use only
5411 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5413 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5414 vopinfo->com.reason == FSYNC_SALVAGE) ||
5415 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5416 (vopinfo->com.reason == V_CLONE ||
5417 vopinfo->com.reason == V_DUMP)));
5421 /***************************************************/
5422 /* online salvager routines */
5423 /***************************************************/
5424 #if defined(AFS_DEMAND_ATTACH_FS)
5427 * offline a volume to let it be salvaged.
5429 * @param[in] vp Volume to offline
5431 * @return whether we offlined the volume successfully
5432 * @retval 0 volume was not offlined
5433 * @retval 1 volume is now offline
5435 * @note This is similar to VCheckOffline, but slightly different. We do not
5436 * deal with vp->goingOffline, and we try to avoid touching the volume
5437 * header except just to set needsSalvaged
5439 * @pre VOL_LOCK held
5440 * @pre vp->nUsers == 0
5441 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5444 VOfflineForSalvage_r(struct Volume *vp)
5448 VCreateReservation_r(vp);
5449 VWaitExclusiveState_r(vp);
5451 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5452 /* Someone's using the volume, or someone got to scheduling the salvage
5453 * before us. I don't think either of these should be possible, as we
5454 * should gain no new heavyweight references while we're trying to
5455 * salvage, but just to be sure... */
5456 VCancelReservation_r(vp);
5460 VChangeState_r(vp, VOL_STATE_OFFLINING);
5464 V_needsSalvaged(vp) = 1;
5465 /* ignore error; updating needsSalvaged is just best effort */
5466 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5468 VCloseVolumeHandles_r(vp);
5470 FreeVolumeHeader(vp);
5472 /* volume has been effectively offlined; we can mark it in the SALVAGING
5473 * state now, which lets FSSYNC give it away */
5474 VChangeState_r(vp, VOL_STATE_SALVAGING);
5476 VCancelReservation_r(vp);
5482 * check whether a salvage needs to be performed on this volume.
5484 * @param[in] vp pointer to volume object
5486 * @return status code
5487 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5488 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5489 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5490 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5491 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5493 * @pre VOL_LOCK is held
5495 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5496 * then a salvage will be requested
5498 * @note this is one of the event handlers called by VCancelReservation_r
5500 * @note the caller must check if the volume needs to be freed after calling
5501 * this; the volume may not have any references or be on any lists after
5502 * we return, and we do not free it
5504 * @see VCancelReservation_r
5506 * @internal volume package internal use only.
5509 VCheckSalvage(Volume * vp)
5511 int ret = VCHECK_SALVAGE_OK;
5513 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5514 if (!vp->salvage.requested) {
5515 return VCHECK_SALVAGE_OK;
5518 return VCHECK_SALVAGE_ASYNC;
5521 /* prevent recursion; some of the code below creates and removes
5522 * lightweight refs, which can call VCheckSalvage */
5523 if (vp->salvage.scheduling) {
5524 return VCHECK_SALVAGE_ASYNC;
5526 vp->salvage.scheduling = 1;
5528 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5529 if (!VOfflineForSalvage_r(vp)) {
5530 vp->salvage.scheduling = 0;
5531 return VCHECK_SALVAGE_FAIL;
5535 if (vp->salvage.requested) {
5536 ret = VScheduleSalvage_r(vp);
5538 vp->salvage.scheduling = 0;
5539 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5544 * request volume salvage.
5546 * @param[out] ec computed client error code
5547 * @param[in] vp volume object pointer
5548 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5549 * @param[in] flags see flags note below
5552 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5553 * not been fully attached
5555 * @pre VOL_LOCK is held.
5557 * @post volume state is changed.
5558 * for fileserver, salvage will be requested once refcount reaches zero.
5560 * @return operation status code
5561 * @retval 0 volume salvage will occur
5562 * @retval 1 volume salvage could not be scheduled
5566 * @note in the fileserver, this call does not synchronously schedule a volume
5567 * salvage. rather, it sets volume state so that when volume refcounts
5568 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5569 * nUsers and nWaiters must be zero.
5571 * @internal volume package internal use only.
5574 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5578 * for DAFS volume utilities that are not supposed to schedule salvages,
5579 * just transition to error state instead
5581 if (!VCanScheduleSalvage()) {
5582 VChangeState_r(vp, VOL_STATE_ERROR);
5587 if (programType != fileServer && !VCanUseFSSYNC()) {
5588 VChangeState_r(vp, VOL_STATE_ERROR);
5593 if (!vp->salvage.requested) {
5594 vp->salvage.requested = 1;
5595 vp->salvage.reason = reason;
5596 vp->stats.last_salvage = FT_ApproxTime();
5598 /* Note that it is not possible for us to reach this point if a
5599 * salvage is already running on this volume (even if the fileserver
5600 * was restarted during the salvage). If a salvage were running, the
5601 * salvager would have write-locked the volume header file, so when
5602 * we tried to lock the volume header, the lock would have failed,
5603 * and we would have failed during attachment prior to calling
5604 * VRequestSalvage. So we know that we can schedule salvages without
5605 * fear of a salvage already running for this volume. */
5607 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5609 /* if we don't need to offline the volume, we can go directly
5610 * to SALVAGING. SALVAGING says the volume is offline and is
5611 * either salvaging or ready to be handed to the salvager.
5612 * SALVAGE_REQ says that we want to salvage the volume, but we
5613 * are waiting for it to go offline first. */
5614 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5615 VChangeState_r(vp, VOL_STATE_SALVAGING);
5617 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5618 if (vp->nUsers == 0) {
5619 /* normally VOfflineForSalvage_r would be called from
5620 * PutVolume et al when nUsers reaches 0, but if
5621 * it's already 0, just do it ourselves, since PutVolume
5622 * isn't going to get called */
5623 VOfflineForSalvage_r(vp);
5626 /* If we are non-fileserver, we're telling the fileserver to
5627 * salvage the vol, so we don't need to give it back separately. */
5628 vp->needsPutBack = 0;
5632 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5634 /* make sure neither VScheduleSalvage_r nor
5635 * VUpdateSalvagePriority_r try to schedule another salvage */
5636 vp->salvage.requested = vp->salvage.scheduled = 0;
5638 VChangeState_r(vp, VOL_STATE_ERROR);
5647 * update salvageserver scheduling priority for a volume.
5649 * @param[in] vp pointer to volume object
5651 * @return operation status
5653 * @retval 1 request denied, or SALVSYNC communications failure
5655 * @pre VOL_LOCK is held.
5657 * @post in-core salvage priority counter is incremented. if at least
5658 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5659 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5660 * to update its priority queue. if no salvage is scheduled,
5661 * this function is a no-op.
5663 * @note DAFS fileserver only
5665 * @note this should be called whenever a VGetVolume fails due to a
5666 * pending salvage request
5668 * @todo should set exclusive state and drop glock around salvsync call
5670 * @internal volume package internal use only.
5673 VUpdateSalvagePriority_r(Volume * vp)
5677 #ifdef SALVSYNC_BUILD_CLIENT
5682 now = FT_ApproxTime();
5684 /* update the salvageserver priority queue occasionally so that
5685 * frequently requested volumes get moved to the head of the queue
5687 if ((vp->salvage.scheduled) &&
5688 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5689 code = SALVSYNC_SalvageVolume(vp->hashid,
5690 VPartitionPath(vp->partition),
5695 vp->stats.last_salvage_req = now;
5696 if (code != SYNC_OK) {
5700 #endif /* SALVSYNC_BUILD_CLIENT */
5705 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5707 /* A couple of little helper functions. These return true if we tried to
5708 * use this mechanism to schedule a salvage, false if we haven't tried.
5709 * If we did try a salvage then the results are contained in code.
5713 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5714 #ifdef SALVSYNC_BUILD_CLIENT
5715 if (VCanUseSALVSYNC()) {
5716 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5717 afs_printable_uint32_lu(vp->hashid), partName);
5719 /* can't use V_id() since there's no guarantee
5720 * we have the disk data header at this point */
5721 *code = SALVSYNC_SalvageVolume(vp->hashid,
5734 try_FSSYNC(Volume *vp, char *partName, int *code) {
5735 #ifdef FSSYNC_BUILD_CLIENT
5736 if (VCanUseFSSYNC()) {
5737 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5738 afs_printable_uint32_lu(vp->hashid), partName);
5741 * If we aren't the fileserver, tell the fileserver the volume
5742 * needs to be salvaged. We could directly tell the
5743 * salvageserver, but the fileserver keeps track of some stats
5744 * related to salvages, and handles some other salvage-related
5745 * complications for us.
5747 *code = FSYNC_VolOp(vp->hashid, partName,
5748 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5751 #endif /* FSSYNC_BUILD_CLIENT */
5756 * schedule a salvage with the salvage server or fileserver.
5758 * @param[in] vp pointer to volume object
5760 * @return operation status
5761 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5762 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5763 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5764 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5765 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5768 * @arg VOL_LOCK is held.
5769 * @arg nUsers and nWaiters should be zero.
5771 * @post salvageserver or fileserver is sent a salvage request
5773 * @note If we are the fileserver, the request will be sent to the salvage
5774 * server over SALVSYNC. If we are not the fileserver, the request will be
5775 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5777 * @note the caller must check if the volume needs to be freed after calling
5778 * this; the volume may not have any references or be on any lists after
5779 * we return, and we do not free it
5783 * @internal volume package internal use only.
5786 VScheduleSalvage_r(Volume * vp)
5788 int ret = VCHECK_SALVAGE_SCHEDULED;
5790 VolState state_save;
5791 VThreadOptions_t * thread_opts;
5794 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5796 if (vp->nWaiters || vp->nUsers) {
5797 return VCHECK_SALVAGE_ASYNC;
5800 /* prevent endless salvage,attach,salvage,attach,... loops */
5801 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5802 return VCHECK_SALVAGE_FAIL;
5806 * don't perform salvsync ops on certain threads
5808 thread_opts = pthread_getspecific(VThread_key);
5809 if (thread_opts == NULL) {
5810 thread_opts = &VThread_defaults;
5812 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5813 return VCHECK_SALVAGE_ASYNC;
5816 if (vp->salvage.scheduled) {
5817 return VCHECK_SALVAGE_SCHEDULED;
5820 VCreateReservation_r(vp);
5821 VWaitExclusiveState_r(vp);
5824 * XXX the scheduling process should really be done asynchronously
5825 * to avoid fssync deadlocks
5827 if (vp->salvage.scheduled) {
5828 ret = VCHECK_SALVAGE_SCHEDULED;
5830 /* if we haven't previously scheduled a salvage, do so now
5832 * set the volume to an exclusive state and drop the lock
5833 * around the SALVSYNC call
5835 strlcpy(partName, vp->partition->name, sizeof(partName));
5836 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5839 opr_Verify(try_SALVSYNC(vp, partName, &code)
5840 || try_FSSYNC(vp, partName, &code));
5843 VChangeState_r(vp, state_save);
5845 if (code == SYNC_OK) {
5846 ret = VCHECK_SALVAGE_SCHEDULED;
5847 vp->salvage.scheduled = 1;
5848 vp->stats.last_salvage_req = FT_ApproxTime();
5849 if (VCanUseSALVSYNC()) {
5850 /* don't record these stats for non-fileservers; let the
5851 * fileserver take care of these */
5852 vp->stats.salvages++;
5853 IncUInt64(&VStats.salvages);
5857 case SYNC_BAD_COMMAND:
5858 case SYNC_COM_ERROR:
5859 ret = VCHECK_SALVAGE_FAIL;
5862 ret = VCHECK_SALVAGE_DENIED;
5863 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5864 "denied\n", afs_printable_uint32_lu(vp->hashid));
5867 ret = VCHECK_SALVAGE_FAIL;
5868 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5869 "failed\n", afs_printable_uint32_lu(vp->hashid));
5872 ret = VCHECK_SALVAGE_FAIL;
5873 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5874 "received unknown protocol error %d\n",
5875 afs_printable_uint32_lu(vp->hashid), code);
5879 if (VCanUseFSSYNC()) {
5880 VChangeState_r(vp, VOL_STATE_ERROR);
5885 /* NB: this is cancelling the reservation we obtained above, but we do
5886 * not call VCancelReservation_r, since that may trigger the vp dtor,
5887 * possibly free'ing the vp. We need to keep the vp around after
5888 * this, as the caller may reference vp without any refs. Instead, it
5889 * is the duty of the caller to inspect 'vp' after we return to see if
5890 * needs to be freed. */
5891 opr_Verify(--vp->nWaiters >= 0);
5894 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5896 #ifdef SALVSYNC_BUILD_CLIENT
5899 * connect to the salvageserver SYNC service.
5901 * @return operation status
5905 * @post connection to salvageserver SYNC service established
5907 * @see VConnectSALV_r
5908 * @see VDisconnectSALV
5909 * @see VReconnectSALV
5916 retVal = VConnectSALV_r();
5922 * connect to the salvageserver SYNC service.
5924 * @return operation status
5928 * @pre VOL_LOCK is held.
5930 * @post connection to salvageserver SYNC service established
5933 * @see VDisconnectSALV_r
5934 * @see VReconnectSALV_r
5935 * @see SALVSYNC_clientInit
5937 * @internal volume package internal use only.
5940 VConnectSALV_r(void)
5942 return SALVSYNC_clientInit();
5946 * disconnect from the salvageserver SYNC service.
5948 * @return operation status
5951 * @pre client should have a live connection to the salvageserver
5953 * @post connection to salvageserver SYNC service destroyed
5955 * @see VDisconnectSALV_r
5957 * @see VReconnectSALV
5960 VDisconnectSALV(void)
5963 VDisconnectSALV_r();
5969 * disconnect from the salvageserver SYNC service.
5971 * @return operation status
5975 * @arg VOL_LOCK is held.
5976 * @arg client should have a live connection to the salvageserver.
5978 * @post connection to salvageserver SYNC service destroyed
5980 * @see VDisconnectSALV
5981 * @see VConnectSALV_r
5982 * @see VReconnectSALV_r
5983 * @see SALVSYNC_clientFinis
5985 * @internal volume package internal use only.
5988 VDisconnectSALV_r(void)
5990 return SALVSYNC_clientFinis();
5994 * disconnect and then re-connect to the salvageserver SYNC service.
5996 * @return operation status
6000 * @pre client should have a live connection to the salvageserver
6002 * @post old connection is dropped, and a new one is established
6005 * @see VDisconnectSALV
6006 * @see VReconnectSALV_r
6009 VReconnectSALV(void)
6013 retVal = VReconnectSALV_r();
6019 * disconnect and then re-connect to the salvageserver SYNC service.
6021 * @return operation status
6026 * @arg VOL_LOCK is held.
6027 * @arg client should have a live connection to the salvageserver.
6029 * @post old connection is dropped, and a new one is established
6031 * @see VConnectSALV_r
6032 * @see VDisconnectSALV
6033 * @see VReconnectSALV
6034 * @see SALVSYNC_clientReconnect
6036 * @internal volume package internal use only.
6039 VReconnectSALV_r(void)
6041 return SALVSYNC_clientReconnect();
6043 #endif /* SALVSYNC_BUILD_CLIENT */
6044 #endif /* AFS_DEMAND_ATTACH_FS */
6047 /***************************************************/
6048 /* FSSYNC routines */
6049 /***************************************************/
6051 /* This must be called by any volume utility which needs to run while the
6052 file server is also running. This is separated from VInitVolumePackage2 so
6053 that a utility can fork--and each of the children can independently
6054 initialize communication with the file server */
6055 #ifdef FSSYNC_BUILD_CLIENT
6057 * connect to the fileserver SYNC service.
6059 * @return operation status
6064 * @arg VInit must equal 2.
6065 * @arg Program Type must not be fileserver or salvager.
6067 * @post connection to fileserver SYNC service established
6070 * @see VDisconnectFS
6071 * @see VChildProcReconnectFS
6078 retVal = VConnectFS_r();
6084 * connect to the fileserver SYNC service.
6086 * @return operation status
6091 * @arg VInit must equal 2.
6092 * @arg Program Type must not be fileserver or salvager.
6093 * @arg VOL_LOCK is held.
6095 * @post connection to fileserver SYNC service established
6098 * @see VDisconnectFS_r
6099 * @see VChildProcReconnectFS_r
6101 * @internal volume package internal use only.
6107 opr_Assert((VInit == 2) &&
6108 (programType != fileServer) &&
6109 (programType != salvager));
6110 rc = FSYNC_clientInit();
6118 * disconnect from the fileserver SYNC service.
6121 * @arg client should have a live connection to the fileserver.
6122 * @arg VOL_LOCK is held.
6123 * @arg Program Type must not be fileserver or salvager.
6125 * @post connection to fileserver SYNC service destroyed
6127 * @see VDisconnectFS
6129 * @see VChildProcReconnectFS_r
6131 * @internal volume package internal use only.
6134 VDisconnectFS_r(void)
6136 opr_Assert((programType != fileServer) &&
6137 (programType != salvager));
6138 FSYNC_clientFinis();
6143 * disconnect from the fileserver SYNC service.
6146 * @arg client should have a live connection to the fileserver.
6147 * @arg Program Type must not be fileserver or salvager.
6149 * @post connection to fileserver SYNC service destroyed
6151 * @see VDisconnectFS_r
6153 * @see VChildProcReconnectFS
6164 * connect to the fileserver SYNC service from a child process following a fork.
6166 * @return operation status
6171 * @arg VOL_LOCK is held.
6172 * @arg current FSYNC handle is shared with a parent process
6174 * @post current FSYNC handle is discarded and a new connection to the
6175 * fileserver SYNC service is established
6177 * @see VChildProcReconnectFS
6179 * @see VDisconnectFS_r
6181 * @internal volume package internal use only.
6184 VChildProcReconnectFS_r(void)
6186 return FSYNC_clientChildProcReconnect();
6190 * connect to the fileserver SYNC service from a child process following a fork.
6192 * @return operation status
6196 * @pre current FSYNC handle is shared with a parent process
6198 * @post current FSYNC handle is discarded and a new connection to the
6199 * fileserver SYNC service is established
6201 * @see VChildProcReconnectFS_r
6203 * @see VDisconnectFS
6206 VChildProcReconnectFS(void)
6210 ret = VChildProcReconnectFS_r();
6214 #endif /* FSSYNC_BUILD_CLIENT */
6217 /***************************************************/
6218 /* volume bitmap routines */
6219 /***************************************************/
6222 * Grow the bitmap by the defined increment
6225 VGrowBitmap(struct vnodeIndex *index)
6229 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6230 osi_Assert(bp != NULL);
6232 bp += index->bitmapSize;
6233 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6234 index->bitmapOffset = index->bitmapSize;
6235 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6241 * allocate a vnode bitmap number for the vnode
6243 * @param[out] ec error code
6244 * @param[in] vp volume object pointer
6245 * @param[in] index vnode index number for the vnode
6246 * @param[in] flags flag values described in note
6248 * @note for DAFS, flags parameter controls locking behavior.
6249 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6250 * will create a reservation and block on any other exclusive
6251 * operations. Otherwise, this function assumes the caller
6252 * already has exclusive access to vp, and we just change the
6255 * @pre VOL_LOCK held
6257 * @return bit number allocated
6263 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6264 struct vnodeIndex *index, int flags)
6268 #ifdef AFS_DEMAND_ATTACH_FS
6269 VolState state_save;
6270 #endif /* AFS_DEMAND_ATTACH_FS */
6274 /* This test is probably redundant */
6275 if (!VolumeWriteable(vp)) {
6276 *ec = (bit32) VREADONLY;
6280 #ifdef AFS_DEMAND_ATTACH_FS
6281 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6282 VCreateReservation_r(vp);
6283 VWaitExclusiveState_r(vp);
6285 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6286 #endif /* AFS_DEMAND_ATTACH_FS */
6289 if ((programType == fileServer) && !index->bitmap) {
6291 #ifndef AFS_DEMAND_ATTACH_FS
6292 /* demand attach fs uses the volume state to avoid races.
6293 * specialStatus field is not used at all */
6295 if (vp->specialStatus == VBUSY) {
6296 if (vp->goingOffline) { /* vos dump waiting for the volume to
6297 * go offline. We probably come here
6298 * from AddNewReadableResidency */
6301 while (vp->specialStatus == VBUSY) {
6302 #ifdef AFS_PTHREAD_ENV
6306 #else /* !AFS_PTHREAD_ENV */
6308 #endif /* !AFS_PTHREAD_ENV */
6312 #endif /* !AFS_DEMAND_ATTACH_FS */
6314 if (!index->bitmap) {
6315 #ifndef AFS_DEMAND_ATTACH_FS
6316 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6317 #endif /* AFS_DEMAND_ATTACH_FS */
6318 for (i = 0; i < nVNODECLASSES; i++) {
6319 VGetBitmap_r(ec, vp, i);
6321 #ifdef AFS_DEMAND_ATTACH_FS
6322 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6323 #else /* AFS_DEMAND_ATTACH_FS */
6324 DeleteVolumeFromHashTable(vp);
6325 vp->shuttingDown = 1; /* Let who has it free it. */
6326 vp->specialStatus = 0;
6327 #endif /* AFS_DEMAND_ATTACH_FS */
6331 #ifndef AFS_DEMAND_ATTACH_FS
6333 vp->specialStatus = 0; /* Allow others to have access. */
6334 #endif /* AFS_DEMAND_ATTACH_FS */
6337 #endif /* BITMAP_LATER */
6339 #ifdef AFS_DEMAND_ATTACH_FS
6341 #endif /* AFS_DEMAND_ATTACH_FS */
6342 bp = index->bitmap + index->bitmapOffset;
6343 ep = index->bitmap + index->bitmapSize;
6345 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6347 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6350 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6352 ret = ((bp - index->bitmap) * 8 + o);
6353 #ifdef AFS_DEMAND_ATTACH_FS
6355 #endif /* AFS_DEMAND_ATTACH_FS */
6358 bp += sizeof(bit32) /* i.e. 4 */ ;
6360 /* No bit map entry--must grow bitmap */
6362 bp = index->bitmap + index->bitmapOffset;
6364 ret = index->bitmapOffset * 8;
6365 #ifdef AFS_DEMAND_ATTACH_FS
6367 #endif /* AFS_DEMAND_ATTACH_FS */
6370 #ifdef AFS_DEMAND_ATTACH_FS
6371 VChangeState_r(vp, state_save);
6372 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6373 VCancelReservation_r(vp);
6375 #endif /* AFS_DEMAND_ATTACH_FS */
6380 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6384 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6390 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6391 unsigned bitNumber, int flags)
6393 unsigned int offset;
6397 #ifdef AFS_DEMAND_ATTACH_FS
6398 if (flags & VOL_FREE_BITMAP_WAIT) {
6399 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6400 * state, so ensure we're not in an exclusive volume state when we update
6402 VCreateReservation_r(vp);
6403 VWaitExclusiveState_r(vp);
6410 #endif /* BITMAP_LATER */
6412 offset = bitNumber >> 3;
6413 if (offset >= index->bitmapSize) {
6417 if (offset < index->bitmapOffset)
6418 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6419 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6422 #ifdef AFS_DEMAND_ATTACH_FS
6423 VCancelReservation_r(vp);
6425 return; /* make the compiler happy for non-DAFS */
6429 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6433 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6437 /* this function will drop the glock internally.
6438 * for old pthread fileservers, this is safe thanks to vbusy.
6440 * for demand attach fs, caller must have already called
6441 * VCreateReservation_r and VWaitExclusiveState_r */
6443 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6445 StreamHandle_t *file;
6446 afs_sfsize_t nVnodes, size;
6447 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6448 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6449 struct VnodeDiskObject *vnode;
6450 unsigned int unique = 0;
6454 #endif /* BITMAP_LATER */
6455 #ifdef AFS_DEMAND_ATTACH_FS
6456 VolState state_save;
6457 #endif /* AFS_DEMAND_ATTACH_FS */
6461 #ifdef AFS_DEMAND_ATTACH_FS
6462 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6463 #endif /* AFS_DEMAND_ATTACH_FS */
6466 fdP = IH_OPEN(vip->handle);
6467 opr_Assert(fdP != NULL);
6468 file = FDH_FDOPEN(fdP, "r");
6469 opr_Assert(file != NULL);
6470 vnode = malloc(vcp->diskSize);
6471 opr_Assert(vnode != NULL);
6472 size = OS_SIZE(fdP->fd_fd);
6473 opr_Assert(size != -1);
6474 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6476 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6477 * a few files can be created in this volume,
6478 * the whole thing is rounded up to nearest 4
6479 * bytes, because the bit map allocator likes
6482 BitMap = (byte *) calloc(1, vip->bitmapSize);
6483 opr_Assert(BitMap != NULL);
6484 #else /* BITMAP_LATER */
6485 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6486 opr_Assert(vip->bitmap != NULL);
6487 vip->bitmapOffset = 0;
6488 #endif /* BITMAP_LATER */
6489 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6491 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6492 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6494 if (vnode->type != vNull) {
6495 if (vnode->vnodeMagic != vcp->magic) {
6496 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6501 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6502 #else /* BITMAP_LATER */
6503 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6504 #endif /* BITMAP_LATER */
6505 if (unique <= vnode->uniquifier)
6506 unique = vnode->uniquifier + 1;
6508 #ifndef AFS_PTHREAD_ENV
6509 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6512 #endif /* !AFS_PTHREAD_ENV */
6515 if (vp->nextVnodeUnique < unique) {
6516 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6519 /* Paranoia, partly justified--I think fclose after fdopen
6520 * doesn't seem to close fd. In any event, the documentation
6521 * doesn't specify, so it's safer to close it twice.
6529 /* There may have been a racing condition with some other thread, both
6530 * creating the bitmaps for this volume. If the other thread was faster
6531 * the pointer to bitmap should already be filled and we can free ours.
6533 if (vip->bitmap == NULL) {
6534 vip->bitmap = BitMap;
6535 vip->bitmapOffset = 0;
6538 #endif /* BITMAP_LATER */
6539 #ifdef AFS_DEMAND_ATTACH_FS
6540 VChangeState_r(vp, state_save);
6541 #endif /* AFS_DEMAND_ATTACH_FS */
6545 /***************************************************/
6546 /* Volume Path and Volume Number utility routines */
6547 /***************************************************/
6550 * find the first occurrence of a volume header file and return the path.
6552 * @param[out] ec outbound error code
6553 * @param[in] volumeId volume id to find
6554 * @param[out] partitionp pointer to disk partition path string
6555 * @param[out] namep pointer to volume header file name string
6557 * @post path to first occurrence of volume header is returned in partitionp
6558 * and namep, or ec is set accordingly.
6560 * @warning this function is NOT re-entrant -- partitionp and namep point to
6561 * static data segments
6563 * @note if a volume utility inadvertently leaves behind a stale volume header
6564 * on a vice partition, it is possible for callers to get the wrong one,
6565 * depending on the order of the disk partition linked list.
6569 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6571 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6572 char path[VMAXPATHLEN];
6574 struct DiskPartition64 *dp;
6577 name[0] = OS_DIRSEPC;
6578 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6579 afs_printable_uint32_lu(volumeId));
6580 for (dp = DiskPartitionList; dp; dp = dp->next) {
6581 struct afs_stat_st status;
6582 strcpy(path, VPartitionPath(dp));
6584 if (afs_stat(path, &status) == 0) {
6585 strcpy(partition, dp->name);
6592 *partitionp = *namep = NULL;
6594 *partitionp = partition;
6600 * extract a volume number from a volume header filename string.
6602 * @param[in] name volume header filename string
6604 * @return volume number
6606 * @note the string must be of the form VFORMAT. the only permissible
6607 * deviation is a leading OS_DIRSEPC character.
6612 VolumeNumber(char *name)
6614 if (*name == OS_DIRSEPC)
6616 return strtoul(name + 1, NULL, 10);
6620 * compute the volume header filename.
6622 * @param[in] volumeId
6624 * @return volume header filename
6626 * @post volume header filename string is constructed
6628 * @warning this function is NOT re-entrant -- the returned string is
6629 * stored in a static char array. see VolumeExternalName_r
6630 * for a re-entrant equivalent.
6632 * @see VolumeExternalName_r
6634 * @deprecated due to the above re-entrancy warning, this interface should
6635 * be considered deprecated. Please use VolumeExternalName_r
6639 VolumeExternalName(VolumeId volumeId)
6641 static char name[VMAXPATHLEN];
6642 snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6647 * compute the volume header filename.
6649 * @param[in] volumeId
6650 * @param[inout] name array in which to store filename
6651 * @param[in] len length of name array
6653 * @return result code from afs_snprintf
6655 * @see VolumeExternalName
6658 * @note re-entrant equivalent of VolumeExternalName
6661 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6663 return snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6667 /***************************************************/
6668 /* Volume Usage Statistics routines */
6669 /***************************************************/
6671 #define OneDay (86400) /* 24 hours' worth of seconds */
6674 Midnight(time_t t) {
6675 struct tm local, *l;
6678 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6679 l = localtime_r(&t, &local);
6685 /* the following is strictly speaking problematic on the
6686 switching day to daylight saving time, after the switch,
6687 as tm_isdst does not match. Similarly, on the looong day when
6688 switching back the OneDay check will not do what naively expected!
6689 The effects are minor, though, and more a matter of interpreting
6691 #ifndef AFS_PTHREAD_ENV
6694 local.tm_hour = local.tm_min=local.tm_sec = 0;
6695 midnight = mktime(&local);
6696 if (midnight != (time_t) -1) return(midnight);
6698 return( (t/OneDay)*OneDay );
6702 /*------------------------------------------------------------------------
6703 * [export] VAdjustVolumeStatistics
6706 * If we've passed midnight, we need to update all the day use
6707 * statistics as well as zeroing the detailed volume statistics
6708 * (if we are implementing them).
6711 * vp : Pointer to the volume structure describing the lucky
6712 * volume being considered for update.
6718 * Nothing interesting.
6722 *------------------------------------------------------------------------*/
6725 VAdjustVolumeStatistics_r(Volume * vp)
6727 unsigned int now = FT_ApproxTime();
6729 if (now - V_dayUseDate(vp) > OneDay) {
6732 ndays = (now - V_dayUseDate(vp)) / OneDay;
6733 for (i = 6; i > ndays - 1; i--)
6734 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6735 for (i = 0; i < ndays - 1 && i < 7; i++)
6736 V_weekUse(vp)[i] = 0;
6738 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6740 V_dayUseDate(vp) = Midnight(now);
6743 * All we need to do is bzero the entire VOL_STATS_BYTES of
6744 * the detailed volume statistics area.
6746 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6749 /*It's been more than a day of collection */
6751 * Always return happily.
6754 } /*VAdjustVolumeStatistics */
6757 VAdjustVolumeStatistics(Volume * vp)
6761 retVal = VAdjustVolumeStatistics_r(vp);
6767 VBumpVolumeUsage_r(Volume * vp)
6769 unsigned int now = FT_ApproxTime();
6770 V_accessDate(vp) = now;
6771 if (now - V_dayUseDate(vp) > OneDay)
6772 VAdjustVolumeStatistics_r(vp);
6774 * Save the volume header image to disk after a threshold of bumps to dayUse,
6775 * at most every usage_rate_limit seconds.
6778 vp->usage_bumps_outstanding++;
6779 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6780 && vp->usage_bumps_next_write <= now) {
6782 vp->usage_bumps_outstanding = 0;
6783 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6784 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6789 VBumpVolumeUsage(Volume * vp)
6792 VBumpVolumeUsage_r(vp);
6797 VSetDiskUsage_r(void)
6799 #ifndef AFS_DEMAND_ATTACH_FS
6800 static int FifteenMinuteCounter = 0;
6804 /* NOTE: Don't attempt to access the partitions list until the
6805 * initialization level indicates that all volumes are attached,
6806 * which implies that all partitions are initialized. */
6807 #ifdef AFS_PTHREAD_ENV
6808 VOL_CV_WAIT(&vol_vinit_cond);
6809 #else /* AFS_PTHREAD_ENV */
6811 #endif /* AFS_PTHREAD_ENV */
6814 VResetDiskUsage_r();
6816 #ifndef AFS_DEMAND_ATTACH_FS
6817 if (++FifteenMinuteCounter == 3) {
6818 FifteenMinuteCounter = 0;
6821 #endif /* !AFS_DEMAND_ATTACH_FS */
6833 /***************************************************/
6834 /* Volume Update List routines */
6835 /***************************************************/
6837 /* The number of minutes that a volume hasn't been updated before the
6838 * "Dont salvage" flag in the volume header will be turned on */
6839 #define SALVAGE_INTERVAL (10*60)
6844 * volume update list functionality has been moved into the VLRU
6845 * the DONT_SALVAGE flag is now set during VLRU demotion
6848 #ifndef AFS_DEMAND_ATTACH_FS
6849 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6850 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6851 static int updateSize = 0; /* number of entries possible */
6852 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6853 #endif /* !AFS_DEMAND_ATTACH_FS */
6856 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6859 vp->updateTime = FT_ApproxTime();
6860 if (V_dontSalvage(vp) == 0)
6862 V_dontSalvage(vp) = 0;
6863 VSyncVolume_r(ec, vp, 0);
6864 #ifdef AFS_DEMAND_ATTACH_FS
6865 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6866 #else /* !AFS_DEMAND_ATTACH_FS */
6869 if (UpdateList == NULL) {
6870 updateSize = UPDATE_LIST_SIZE;
6871 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6873 if (nUpdatedVolumes == updateSize) {
6875 if (updateSize > 524288) {
6876 Log("warning: there is likely a bug in the volume update scanner\n");
6879 UpdateList = realloc(UpdateList,
6880 sizeof(VolumeId) * updateSize);
6883 opr_Assert(UpdateList != NULL);
6884 UpdateList[nUpdatedVolumes++] = V_id(vp);
6885 #endif /* !AFS_DEMAND_ATTACH_FS */
6888 #ifndef AFS_DEMAND_ATTACH_FS
6890 VScanUpdateList(void)
6895 afs_uint32 now = FT_ApproxTime();
6896 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6897 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6899 UpdateList[i - gap] = UpdateList[i];
6901 /* XXX this routine needlessly messes up the Volume LRU by
6902 * breaking the LRU temporal-locality assumptions.....
6903 * we should use a special volume header allocator here */
6904 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6907 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6908 V_dontSalvage(vp) = DONT_SALVAGE;
6909 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6917 #ifndef AFS_PTHREAD_ENV
6919 #endif /* !AFS_PTHREAD_ENV */
6921 nUpdatedVolumes -= gap;
6923 #endif /* !AFS_DEMAND_ATTACH_FS */
6926 /***************************************************/
6927 /* Volume LRU routines */
6928 /***************************************************/
6933 * with demand attach fs, we attempt to soft detach(1)
6934 * volumes which have not been accessed in a long time
6935 * in order to speed up fileserver shutdown
6937 * (1) by soft detach we mean a process very similar
6938 * to VOffline, except the final state of the
6939 * Volume will be VOL_STATE_PREATTACHED, instead
6940 * of the usual VOL_STATE_UNATTACHED
6942 #ifdef AFS_DEMAND_ATTACH_FS
6944 /* implementation is reminiscent of a generational GC
6946 * queue 0 is newly attached volumes. this queue is
6947 * sorted by attach timestamp
6949 * queue 1 is volumes that have been around a bit
6950 * longer than queue 0. this queue is sorted by
6953 * queue 2 is volumes tha have been around the longest.
6954 * this queue is unsorted
6956 * queue 3 is volumes that have been marked as
6957 * candidates for soft detachment. this queue is
6960 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6961 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6964 * definition of a VLRU queue.
6967 volatile struct rx_queue q;
6974 * main VLRU data structure.
6977 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6980 /** time interval (in seconds) between promotion passes for
6981 * each young generation queue. */
6982 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6984 /** time interval (in seconds) between soft detach candidate
6985 * scans for each generation queue.
6987 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6988 * we perform a soft detach pass. */
6989 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6991 /* scheduler state */
6992 int next_idx; /**< next queue to receive attention */
6993 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6994 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6996 int scanner_state; /**< state of scanner thread */
6997 pthread_cond_t cv; /**< state transition CV */
7000 /** global VLRU state */
7001 static struct VLRU volume_LRU;
7004 * defined states for VLRU scanner thread.
7007 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7008 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7009 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7010 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7011 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7012 } vlru_thread_state_t;
7014 /* vlru disk data header stuff */
7015 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7016 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7018 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7019 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7022 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7023 * soft detachment. */
7024 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7026 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7027 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7029 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7030 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7032 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7033 static afs_uint32 VLRU_enabled = 1;
7035 /* queue synchronization routines */
7036 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7037 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7038 static void VLRU_Wait_r(struct VLRU_q * q);
7041 * set VLRU subsystem tunable parameters.
7043 * @param[in] option tunable option to modify
7044 * @param[in] val new value for tunable parameter
7046 * @pre @c VInitVolumePackage2 has not yet been called.
7048 * @post tunable parameter is modified
7052 * @note valid option parameters are:
7053 * @arg @c VLRU_SET_THRESH
7054 * set the period of inactivity after which
7055 * volumes are eligible for soft detachment
7056 * @arg @c VLRU_SET_INTERVAL
7057 * set the time interval between calls
7058 * to the volume LRU "garbage collector"
7059 * @arg @c VLRU_SET_MAX
7060 * set the max number of volumes to deallocate
7064 VLRU_SetOptions(int option, afs_uint32 val)
7066 if (option == VLRU_SET_THRESH) {
7067 VLRU_offline_thresh = val;
7068 } else if (option == VLRU_SET_INTERVAL) {
7069 VLRU_offline_interval = val;
7070 } else if (option == VLRU_SET_MAX) {
7071 VLRU_offline_max = val;
7072 } else if (option == VLRU_SET_ENABLED) {
7075 VLRU_ComputeConstants();
7079 * compute VLRU internal timing parameters.
7081 * @post VLRU scanner thread internal timing parameters are computed
7083 * @note computes internal timing parameters based upon user-modifiable
7084 * tunable parameters.
7088 * @internal volume package internal use only.
7091 VLRU_ComputeConstants(void)
7093 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7095 /* compute the candidate scan interval */
7096 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7098 /* compute the promotion intervals */
7099 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7100 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7103 /* compute the gen 0 scan interval */
7104 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7106 /* compute the gen 0 scan interval */
7107 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7112 * initialize VLRU subsystem.
7114 * @pre this function has not yet been called
7116 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7120 * @internal volume package internal use only.
7126 pthread_attr_t attrs;
7129 if (!VLRU_enabled) {
7130 Log("VLRU: disabled\n");
7134 /* initialize each of the VLRU queues */
7135 for (i = 0; i < VLRU_QUEUES; i++) {
7136 queue_Init(&volume_LRU.q[i]);
7137 volume_LRU.q[i].len = 0;
7138 volume_LRU.q[i].busy = 0;
7139 opr_cv_init(&volume_LRU.q[i].cv);
7142 /* setup the timing constants */
7143 VLRU_ComputeConstants();
7145 /* XXX put inside LogLevel check? */
7146 Log("VLRU: starting scanner with the following configuration parameters:\n");
7147 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7148 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7149 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7150 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7151 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7152 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7154 /* start up the VLRU scanner */
7155 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7156 if (programType == fileServer) {
7157 opr_cv_init(&volume_LRU.cv);
7158 opr_Verify(pthread_attr_init(&attrs) == 0);
7159 opr_Verify(pthread_attr_setdetachstate(&attrs,
7160 PTHREAD_CREATE_DETACHED) == 0);
7161 opr_Verify(pthread_create(&tid, &attrs,
7162 &VLRU_ScannerThread, NULL) == 0);
7167 * initialize the VLRU-related fields of a newly allocated volume object.
7169 * @param[in] vp pointer to volume object
7172 * @arg @c VOL_LOCK is held.
7173 * @arg volume object is not on a VLRU queue.
7175 * @post VLRU fields are initialized to indicate that volume object is not
7176 * currently registered with the VLRU subsystem
7180 * @internal volume package interal use only.
7183 VLRU_Init_Node_r(Volume * vp)
7188 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7189 vp->vlru.idx = VLRU_QUEUE_INVALID;
7193 * add a volume object to a VLRU queue.
7195 * @param[in] vp pointer to volume object
7198 * @arg @c VOL_LOCK is held.
7199 * @arg caller MUST hold a lightweight ref on @p vp.
7200 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7202 * @post the volume object is added to the appropriate VLRU queue
7204 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7205 * then the volume is added to that queue. Otherwise, the value
7206 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7207 * volume is added to the NEW generation queue.
7209 * @note @c VOL_LOCK may be dropped internally
7211 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7212 * during the add operation, and is restored to the previous
7213 * state prior to return.
7217 * @internal volume package internal use only.
7220 VLRU_Add_r(Volume * vp)
7223 VolState state_save;
7228 if (queue_IsOnQueue(&vp->vlru))
7231 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7234 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7235 idx = VLRU_QUEUE_NEW;
7238 VLRU_Wait_r(&volume_LRU.q[idx]);
7240 /* repeat check since VLRU_Wait_r may have dropped
7242 if (queue_IsNotOnQueue(&vp->vlru)) {
7244 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7245 volume_LRU.q[idx].len++;
7246 V_attachFlags(vp) |= VOL_ON_VLRU;
7247 vp->stats.last_promote = FT_ApproxTime();
7250 VChangeState_r(vp, state_save);
7254 * delete a volume object from a VLRU queue.
7256 * @param[in] vp pointer to volume object
7259 * @arg @c VOL_LOCK is held.
7260 * @arg caller MUST hold a lightweight ref on @p vp.
7261 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7263 * @post volume object is removed from the VLRU queue
7265 * @note @c VOL_LOCK may be dropped internally
7269 * @todo We should probably set volume state to something exlcusive
7270 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7272 * @internal volume package internal use only.
7275 VLRU_Delete_r(Volume * vp)
7282 if (queue_IsNotOnQueue(&vp->vlru))
7288 if (idx == VLRU_QUEUE_INVALID)
7290 VLRU_Wait_r(&volume_LRU.q[idx]);
7291 } while (idx != vp->vlru.idx);
7293 /* now remove from the VLRU and update
7294 * the appropriate counter */
7295 queue_Remove(&vp->vlru);
7296 volume_LRU.q[idx].len--;
7297 vp->vlru.idx = VLRU_QUEUE_INVALID;
7298 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7302 * tell the VLRU subsystem that a volume was just accessed.
7304 * @param[in] vp pointer to volume object
7307 * @arg @c VOL_LOCK is held
7308 * @arg caller MUST hold a lightweight ref on @p vp
7309 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7311 * @post volume VLRU access statistics are updated. If the volume was on
7312 * the VLRU soft detach candidate queue, it is moved to the NEW
7315 * @note @c VOL_LOCK may be dropped internally
7319 * @internal volume package internal use only.
7322 VLRU_UpdateAccess_r(Volume * vp)
7324 Volume * rvp = NULL;
7329 if (queue_IsNotOnQueue(&vp->vlru))
7332 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7334 /* update the access timestamp */
7335 vp->stats.last_get = FT_ApproxTime();
7338 * if the volume is on the soft detach candidate
7339 * list, we need to safely move it back to a
7340 * regular generation. this has to be done
7341 * carefully so we don't race against the scanner
7345 /* if this volume is on the soft detach candidate queue,
7346 * then grab exclusive access to the necessary queues */
7347 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7349 VCreateReservation_r(rvp);
7351 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7352 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7353 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7354 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7357 /* make sure multiple threads don't race to update */
7358 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7359 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7363 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7364 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7365 VCancelReservation_r(rvp);
7370 * switch a volume between two VLRU queues.
7372 * @param[in] vp pointer to volume object
7373 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7374 * @param[in] append controls whether the volume will be appended or
7375 * prepended to the queue. A nonzero value means it will
7376 * be appended; zero means it will be prepended.
7378 * @pre The new (and old, if applicable) queue(s) must either be owned
7379 * exclusively by the calling thread for asynchronous manipulation,
7380 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7381 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7382 * for further details of the queue asynchronous processing mechanism.
7384 * @post If the volume object was already on a VLRU queue, it is
7385 * removed from the queue. Depending on the value of the append
7386 * parameter, the volume object is either appended or prepended
7387 * to the VLRU queue referenced by the new_idx parameter.
7391 * @see VLRU_BeginExclusive_r
7392 * @see VLRU_EndExclusive_r
7395 * @internal volume package internal use only.
7398 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7400 if (queue_IsNotOnQueue(&vp->vlru))
7403 queue_Remove(&vp->vlru);
7404 volume_LRU.q[vp->vlru.idx].len--;
7406 /* put the volume back on the correct generational queue */
7408 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7410 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7413 volume_LRU.q[new_idx].len++;
7414 vp->vlru.idx = new_idx;
7418 * VLRU background thread.
7420 * The VLRU Scanner Thread is responsible for periodically scanning through
7421 * each VLRU queue looking for volumes which should be moved to another
7422 * queue, or soft detached.
7424 * @param[in] args unused thread arguments parameter
7426 * @return unused thread return value
7427 * @retval NULL always
7429 * @internal volume package internal use only.
7432 VLRU_ScannerThread(void * args)
7434 afs_uint32 now, min_delay, delay;
7435 int i, min_idx, min_op, overdue, state;
7437 /* set t=0 for promotion cycle to be
7438 * fileserver startup */
7439 now = FT_ApproxTime();
7440 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7441 volume_LRU.last_promotion[i] = now;
7444 /* don't start the scanner until VLRU_offline_thresh
7445 * plus a small delay for VInitVolumePackage2 to finish
7448 sleep(VLRU_offline_thresh + 60);
7450 /* set t=0 for scan cycle to be now */
7451 now = FT_ApproxTime();
7452 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7453 volume_LRU.last_scan[i] = now;
7457 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7458 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7461 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7462 /* check to see if we've been asked to pause */
7463 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7464 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7465 opr_cv_broadcast(&volume_LRU.cv);
7467 VOL_CV_WAIT(&volume_LRU.cv);
7468 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7471 /* scheduling can happen outside the glock */
7474 /* figure out what is next on the schedule */
7476 /* figure out a potential schedule for the new generation first */
7478 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7481 if (min_delay > volume_LRU.scan_interval[0]) {
7482 /* unsigned overflow -- we're overdue to run this scan */
7487 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7489 i = VLRU_QUEUE_CANDIDATE;
7490 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7491 if (delay < min_delay) {
7495 if (delay > volume_LRU.scan_interval[i]) {
7496 /* unsigned overflow -- we're overdue to run this scan */
7503 /* if we're still not overdue for something, figure out schedules for promotions */
7504 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7505 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7506 if (delay < min_delay) {
7511 if (delay > volume_LRU.promotion_interval[i]) {
7512 /* unsigned overflow -- we're overdue to run this promotion */
7521 /* sleep as needed */
7526 /* do whatever is next */
7529 VLRU_Promote_r(min_idx);
7530 VLRU_Demote_r(min_idx+1);
7532 VLRU_Scan_r(min_idx);
7534 now = FT_ApproxTime();
7537 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7539 /* signal that scanner is down */
7540 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7541 opr_cv_broadcast(&volume_LRU.cv);
7547 * promote volumes from one VLRU generation to the next.
7549 * This routine scans a VLRU generation looking for volumes which are
7550 * eligible to be promoted to the next generation. All volumes which
7551 * meet the eligibility requirement are promoted.
7553 * Promotion eligibility is based upon meeting both of the following
7556 * @arg The volume has been accessed since the last promotion:
7557 * @c (vp->stats.last_get >= vp->stats.last_promote)
7558 * @arg The last promotion occurred at least
7559 * @c volume_LRU.promotion_interval[idx] seconds ago
7561 * As a performance optimization, promotions are "globbed". In other
7562 * words, we promote arbitrarily large contiguous sublists of elements
7565 * @param[in] idx VLRU queue index to scan
7569 * @internal VLRU internal use only.
7572 VLRU_Promote_r(int idx)
7574 int len, chaining, promote;
7575 afs_uint32 now, thresh;
7576 struct rx_queue *qp, *nqp;
7577 Volume * vp, *start = NULL, *end = NULL;
7579 /* get exclusive access to two chains, and drop the glock */
7580 VLRU_Wait_r(&volume_LRU.q[idx]);
7581 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7582 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7583 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7586 thresh = volume_LRU.promotion_interval[idx];
7587 now = FT_ApproxTime();
7590 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7591 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7592 promote = (((vp->stats.last_promote + thresh) <= now) &&
7593 (vp->stats.last_get >= vp->stats.last_promote));
7601 /* promote and prepend chain */
7602 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7616 /* promote and prepend */
7617 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7621 volume_LRU.q[idx].len -= len;
7622 volume_LRU.q[idx+1].len += len;
7625 /* release exclusive access to the two chains */
7627 volume_LRU.last_promotion[idx] = now;
7628 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7629 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7632 /* run the demotions */
7634 VLRU_Demote_r(int idx)
7637 int len, chaining, demote;
7638 afs_uint32 now, thresh;
7639 struct rx_queue *qp, *nqp;
7640 Volume * vp, *start = NULL, *end = NULL;
7641 Volume ** salv_flag_vec = NULL;
7642 int salv_vec_offset = 0;
7644 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7646 /* get exclusive access to two chains, and drop the glock */
7647 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7648 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7649 VLRU_Wait_r(&volume_LRU.q[idx]);
7650 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7653 /* no big deal if this allocation fails */
7654 if (volume_LRU.q[idx].len) {
7655 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7658 now = FT_ApproxTime();
7659 thresh = volume_LRU.promotion_interval[idx-1];
7662 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7663 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7664 demote = (((vp->stats.last_promote + thresh) <= now) &&
7665 (vp->stats.last_get < (now - thresh)));
7667 /* we now do volume update list DONT_SALVAGE flag setting during
7668 * demotion passes */
7669 if (salv_flag_vec &&
7670 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7672 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7673 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7674 salv_flag_vec[salv_vec_offset++] = vp;
7675 VCreateReservation_r(vp);
7684 /* demote and append chain */
7685 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7699 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7703 volume_LRU.q[idx].len -= len;
7704 volume_LRU.q[idx-1].len += len;
7707 /* release exclusive access to the two chains */
7709 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7710 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7712 /* now go back and set the DONT_SALVAGE flags as appropriate */
7713 if (salv_flag_vec) {
7715 for (i = 0; i < salv_vec_offset; i++) {
7716 vp = salv_flag_vec[i];
7717 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7718 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7719 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7722 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7723 V_dontSalvage(vp) = DONT_SALVAGE;
7724 VUpdateVolume_r(&ec, vp, 0);
7728 VCancelReservation_r(vp);
7730 free(salv_flag_vec);
7734 /* run a pass of the VLRU GC scanner */
7736 VLRU_Scan_r(int idx)
7738 afs_uint32 now, thresh;
7739 struct rx_queue *qp, *nqp;
7743 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7745 /* gain exclusive access to the idx VLRU */
7746 VLRU_Wait_r(&volume_LRU.q[idx]);
7747 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7749 if (idx != VLRU_QUEUE_CANDIDATE) {
7750 /* gain exclusive access to the candidate VLRU */
7751 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7752 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7755 now = FT_ApproxTime();
7756 thresh = now - VLRU_offline_thresh;
7758 /* perform candidate selection and soft detaching */
7759 if (idx == VLRU_QUEUE_CANDIDATE) {
7760 /* soft detach some volumes from the candidate pool */
7764 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7765 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7766 if (i >= VLRU_offline_max) {
7769 /* check timestamp to see if it's a candidate for soft detaching */
7770 if (vp->stats.last_get <= thresh) {
7772 if (VCheckSoftDetach(vp, thresh))
7778 /* scan for volumes to become soft detach candidates */
7779 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7780 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7782 /* check timestamp to see if it's a candidate for soft detaching */
7783 if (vp->stats.last_get <= thresh) {
7784 VCheckSoftDetachCandidate(vp, thresh);
7787 if (!(i&0x7f)) { /* lock coarsening optimization */
7795 /* relinquish exclusive access to the VLRU chains */
7799 volume_LRU.last_scan[idx] = now;
7800 if (idx != VLRU_QUEUE_CANDIDATE) {
7801 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7803 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7806 /* check whether volume is safe to soft detach
7807 * caller MUST NOT hold a ref count on vp */
7809 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7813 if (vp->nUsers || vp->nWaiters)
7816 if (vp->stats.last_get <= thresh) {
7817 ret = VSoftDetachVolume_r(vp, thresh);
7823 /* check whether volume should be made a
7824 * soft detach candidate */
7826 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7829 if (vp->nUsers || vp->nWaiters)
7834 opr_Assert(idx == VLRU_QUEUE_NEW);
7836 if (vp->stats.last_get <= thresh) {
7837 /* move to candidate pool */
7838 queue_Remove(&vp->vlru);
7839 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7840 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7841 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7842 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7850 /* begin exclusive access on VLRU */
7852 VLRU_BeginExclusive_r(struct VLRU_q * q)
7854 opr_Assert(q->busy == 0);
7858 /* end exclusive access on VLRU */
7860 VLRU_EndExclusive_r(struct VLRU_q * q)
7862 opr_Assert(q->busy);
7864 opr_cv_broadcast(&q->cv);
7867 /* wait for another thread to end exclusive access on VLRU */
7869 VLRU_Wait_r(struct VLRU_q * q)
7872 VOL_CV_WAIT(&q->cv);
7877 * volume soft detach
7879 * caller MUST NOT hold a ref count on vp */
7881 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7886 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7888 ts_save = vp->stats.last_get;
7889 if (ts_save > thresh)
7892 if (vp->nUsers || vp->nWaiters)
7895 if (VIsExclusiveState(V_attachState(vp))) {
7899 switch (V_attachState(vp)) {
7900 case VOL_STATE_UNATTACHED:
7901 case VOL_STATE_PREATTACHED:
7902 case VOL_STATE_ERROR:
7903 case VOL_STATE_GOING_OFFLINE:
7904 case VOL_STATE_SHUTTING_DOWN:
7905 case VOL_STATE_SALVAGING:
7906 case VOL_STATE_DELETED:
7907 volume_LRU.q[vp->vlru.idx].len--;
7909 /* create and cancel a reservation to
7910 * give the volume an opportunity to
7912 VCreateReservation_r(vp);
7913 queue_Remove(&vp->vlru);
7914 vp->vlru.idx = VLRU_QUEUE_INVALID;
7915 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7916 VCancelReservation_r(vp);
7922 /* hold the volume and take it offline.
7923 * no need for reservations, as VHold_r
7924 * takes care of that internally. */
7925 if (VHold_r(vp) == 0) {
7926 /* vhold drops the glock, so now we should
7927 * check to make sure we aren't racing against
7928 * other threads. if we are racing, offlining vp
7929 * would be wasteful, and block the scanner for a while
7933 (vp->shuttingDown) ||
7934 (vp->goingOffline) ||
7935 (vp->stats.last_get != ts_save)) {
7936 /* looks like we're racing someone else. bail */
7940 /* pull it off the VLRU */
7941 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7942 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7943 queue_Remove(&vp->vlru);
7944 vp->vlru.idx = VLRU_QUEUE_INVALID;
7945 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7947 /* take if offline */
7948 VOffline_r(vp, "volume has been soft detached");
7950 /* invalidate the volume header cache */
7951 FreeVolumeHeader(vp);
7954 IncUInt64(&VStats.soft_detaches);
7955 vp->stats.soft_detaches++;
7957 /* put in pre-attached state so demand
7958 * attacher can work on it */
7959 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7965 #endif /* AFS_DEMAND_ATTACH_FS */
7968 /***************************************************/
7969 /* Volume Header Cache routines */
7970 /***************************************************/
7973 * volume header cache.
7975 struct volume_hdr_LRU_t volume_hdr_LRU;
7978 * initialize the volume header cache.
7980 * @param[in] howMany number of header cache entries to preallocate
7982 * @pre VOL_LOCK held. Function has never been called before.
7984 * @post howMany cache entries are allocated, initialized, and added
7985 * to the LRU list. Header cache statistics are initialized.
7987 * @note only applicable to fileServer program type. Should only be
7988 * called once during volume package initialization.
7990 * @internal volume package internal use only.
7993 VInitVolumeHeaderCache(afs_uint32 howMany)
7995 struct volHeader *hp;
7996 if (programType != fileServer)
7998 queue_Init(&volume_hdr_LRU);
7999 volume_hdr_LRU.stats.free = 0;
8000 volume_hdr_LRU.stats.used = howMany;
8001 volume_hdr_LRU.stats.attached = 0;
8002 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8003 opr_Assert(hp != NULL);
8006 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8007 * to ensure they have the right values
8009 ReleaseVolumeHeader(hp++);
8012 /* get a volume header off of the volume header LRU.
8014 * @return volume header
8015 * @retval NULL no usable volume header is available on the LRU
8017 * @pre VOL_LOCK held
8019 * @post for DAFS, if the returned header is associated with a volume, that
8020 * volume is NOT in an exclusive state
8022 * @internal volume package internal use only.
8024 #ifdef AFS_DEMAND_ATTACH_FS
8025 static struct volHeader*
8026 GetVolHeaderFromLRU(void)
8028 struct volHeader *hd = NULL, *qh, *nqh;
8029 /* Usually, a volume in an exclusive state will not have its header on
8030 * the LRU. However, it is possible for this to occur when a salvage
8031 * request is received over FSSYNC, and possibly in other corner cases.
8032 * So just skip over headers whose volumes are in an exclusive state. We
8033 * could VWaitExclusiveState_r instead, but not waiting is faster and
8035 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8036 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8044 #else /* AFS_DEMAND_ATTACH_FS */
8045 static struct volHeader*
8046 GetVolHeaderFromLRU(void)
8048 struct volHeader *hd = NULL;
8049 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8050 hd = queue_First(&volume_hdr_LRU, volHeader);
8055 #endif /* !AFS_DEMAND_ATTACH_FS */
8058 * get a volume header and attach it to the volume object.
8060 * @param[in] vp pointer to volume object
8062 * @return cache entry status
8063 * @retval 0 volume header was newly attached; cache data is invalid
8064 * @retval 1 volume header was previously attached; cache data is valid
8066 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8068 * @post volume header attached to volume object. if necessary, header cache
8069 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8071 * @note VOL_LOCK may be dropped
8073 * @warning this interface does not load header data from disk. it merely
8074 * attaches a header object to the volume object, and may sync the old
8075 * header cache data out to disk in the process.
8077 * @internal volume package internal use only.
8080 GetVolumeHeader(Volume * vp)
8083 struct volHeader *hd;
8085 static int everLogged = 0;
8087 #ifdef AFS_DEMAND_ATTACH_FS
8088 VolState vp_save = 0, back_save = 0;
8090 /* XXX debug 9/19/05 we've apparently got
8091 * a ref counting bug somewhere that's
8092 * breaking the nUsers == 0 => header on LRU
8094 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8095 Log("nUsers == 0, but header not on LRU\n");
8100 old = (vp->header != NULL); /* old == volume already has a header */
8102 if (programType != fileServer) {
8103 /* for volume utilities, we allocate volHeaders as needed */
8105 hd = calloc(1, sizeof(*vp->header));
8106 opr_Assert(hd != NULL);
8109 #ifdef AFS_DEMAND_ATTACH_FS
8110 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8114 /* for the fileserver, we keep a volume header cache */
8116 /* the header we previously dropped in the lru is
8117 * still available. pull it off the lru and return */
8120 opr_Assert(hd->back == vp);
8121 #ifdef AFS_DEMAND_ATTACH_FS
8122 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8125 hd = GetVolHeaderFromLRU();
8127 /* LRU is empty, so allocate a new volHeader
8128 * this is probably indicative of a leak, so let the user know */
8129 hd = calloc(1, sizeof(struct volHeader));
8130 opr_Assert(hd != NULL);
8132 Log("****Allocated more volume headers, probably leak****\n");
8135 volume_hdr_LRU.stats.free++;
8138 /* this header used to belong to someone else.
8139 * we'll need to check if the header needs to
8140 * be sync'd out to disk */
8142 #ifdef AFS_DEMAND_ATTACH_FS
8143 /* GetVolHeaderFromLRU had better not give us back a header
8144 * with a volume in exclusive state... */
8145 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8148 if (hd->diskstuff.inUse) {
8149 /* volume was in use, so we'll need to sync
8150 * its header to disk */
8152 #ifdef AFS_DEMAND_ATTACH_FS
8153 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8154 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8155 VCreateReservation_r(hd->back);
8159 WriteVolumeHeader_r(&error, hd->back);
8160 /* Ignore errors; catch them later */
8162 #ifdef AFS_DEMAND_ATTACH_FS
8167 hd->back->header = NULL;
8168 #ifdef AFS_DEMAND_ATTACH_FS
8169 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8171 if (hd->diskstuff.inUse) {
8172 VChangeState_r(hd->back, back_save);
8173 VCancelReservation_r(hd->back);
8174 VChangeState_r(vp, vp_save);
8178 volume_hdr_LRU.stats.attached++;
8182 #ifdef AFS_DEMAND_ATTACH_FS
8183 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8186 volume_hdr_LRU.stats.free--;
8187 volume_hdr_LRU.stats.used++;
8189 IncUInt64(&VStats.hdr_gets);
8190 #ifdef AFS_DEMAND_ATTACH_FS
8191 IncUInt64(&vp->stats.hdr_gets);
8192 vp->stats.last_hdr_get = FT_ApproxTime();
8199 * make sure volume header is attached and contains valid cache data.
8201 * @param[out] ec outbound error code
8202 * @param[in] vp pointer to volume object
8204 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8206 * @post header cache entry attached, and loaded with valid data, or
8207 * *ec is nonzero, and the header is released back into the LRU.
8209 * @internal volume package internal use only.
8212 LoadVolumeHeader(Error * ec, Volume * vp)
8214 #ifdef AFS_DEMAND_ATTACH_FS
8215 VolState state_save;
8219 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8220 IncUInt64(&VStats.hdr_loads);
8221 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8224 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8225 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8227 IncUInt64(&vp->stats.hdr_loads);
8228 now = FT_ApproxTime();
8232 V_attachFlags(vp) |= VOL_HDR_LOADED;
8233 vp->stats.last_hdr_load = now;
8235 VChangeState_r(vp, state_save);
8237 #else /* AFS_DEMAND_ATTACH_FS */
8239 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8240 IncUInt64(&VStats.hdr_loads);
8242 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8243 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8246 #endif /* AFS_DEMAND_ATTACH_FS */
8248 /* maintain (nUsers==0) => header in LRU invariant */
8249 FreeVolumeHeader(vp);
8254 * release a header cache entry back into the LRU list.
8256 * @param[in] hd pointer to volume header cache object
8258 * @pre VOL_LOCK held.
8260 * @post header cache object appended onto end of LRU list.
8262 * @note only applicable to fileServer program type.
8264 * @note used to place a header cache entry back into the
8265 * LRU pool without invalidating it as a cache entry.
8267 * @internal volume package internal use only.
8270 ReleaseVolumeHeader(struct volHeader *hd)
8272 if (programType != fileServer)
8274 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8276 queue_Append(&volume_hdr_LRU, hd);
8277 #ifdef AFS_DEMAND_ATTACH_FS
8279 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8282 volume_hdr_LRU.stats.free++;
8283 volume_hdr_LRU.stats.used--;
8287 * free/invalidate a volume header cache entry.
8289 * @param[in] vp pointer to volume object
8291 * @pre VOL_LOCK is held.
8293 * @post For fileserver, header cache entry is returned to LRU, and it is
8294 * invalidated as a cache entry. For volume utilities, the header
8295 * cache entry is freed.
8297 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8298 * whenever it is necessary to invalidate the header cache entry.
8300 * @see ReleaseVolumeHeader
8302 * @internal volume package internal use only.
8305 FreeVolumeHeader(Volume * vp)
8307 struct volHeader *hd = vp->header;
8310 if (programType == fileServer) {
8311 ReleaseVolumeHeader(hd);
8316 #ifdef AFS_DEMAND_ATTACH_FS
8317 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8319 volume_hdr_LRU.stats.attached--;
8324 /***************************************************/
8325 /* Volume Hash Table routines */
8326 /***************************************************/
8329 * set size of volume object hash table.
8331 * @param[in] logsize log(2) of desired hash table size
8333 * @return operation status
8335 * @retval -1 failure
8337 * @pre MUST be called prior to VInitVolumePackage2
8339 * @post Volume Hash Table will have 2^logsize buckets
8342 VSetVolHashSize(int logsize)
8344 /* 64 to 268435456 hash buckets seems like a reasonable range */
8345 if ((logsize < 6 ) || (logsize > 28)) {
8350 VolumeHashTable.Size = 1 << logsize;
8351 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8353 /* we can't yet support runtime modification of this
8354 * parameter. we'll need a configuration rwlock to
8355 * make runtime modification feasible.... */
8362 * initialize dynamic data structures for volume hash table.
8364 * @post hash table is allocated, and fields are initialized.
8366 * @internal volume package internal use only.
8369 VInitVolumeHash(void)
8373 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8374 sizeof(VolumeHashChainHead));
8375 opr_Assert(VolumeHashTable.Table != NULL);
8377 for (i=0; i < VolumeHashTable.Size; i++) {
8378 queue_Init(&VolumeHashTable.Table[i]);
8379 #ifdef AFS_DEMAND_ATTACH_FS
8380 opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8381 #endif /* AFS_DEMAND_ATTACH_FS */
8386 * add a volume object to the hash table.
8388 * @param[in] vp pointer to volume object
8389 * @param[in] hashid hash of volume id
8391 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8394 * @post volume is added to hash chain.
8396 * @internal volume package internal use only.
8398 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8399 * asynchronous hash chain reordering to finish.
8402 AddVolumeToHashTable(Volume * vp, int hashid)
8404 VolumeHashChainHead * head;
8406 if (queue_IsOnQueue(vp))
8409 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8411 #ifdef AFS_DEMAND_ATTACH_FS
8412 /* wait for the hash chain to become available */
8415 V_attachFlags(vp) |= VOL_IN_HASH;
8416 vp->chainCacheCheck = ++head->cacheCheck;
8417 #endif /* AFS_DEMAND_ATTACH_FS */
8420 vp->hashid = hashid;
8421 queue_Append(head, vp);
8422 vp->vnodeHashOffset = VolumeHashOffset_r();
8426 * delete a volume object from the hash table.
8428 * @param[in] vp pointer to volume object
8430 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8433 * @post volume is removed from hash chain.
8435 * @internal volume package internal use only.
8437 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8438 * asynchronous hash chain reordering to finish.
8441 DeleteVolumeFromHashTable(Volume * vp)
8443 VolumeHashChainHead * head;
8445 if (!queue_IsOnQueue(vp))
8448 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8450 #ifdef AFS_DEMAND_ATTACH_FS
8451 /* wait for the hash chain to become available */
8454 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8456 #endif /* AFS_DEMAND_ATTACH_FS */
8460 /* do NOT reset hashid to zero, as the online
8461 * salvager package may need to know the volume id
8462 * after the volume is removed from the hash */
8466 * lookup a volume object in the hash table given a volume id.
8468 * @param[out] ec error code return
8469 * @param[in] volumeId volume id
8470 * @param[in] hint volume object which we believe could be the correct
8473 * @return volume object pointer
8474 * @retval NULL no such volume id is registered with the hash table.
8476 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8479 * @post volume object with the given id is returned. volume object and
8480 * hash chain access statistics are updated. hash chain may have
8483 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8484 * asynchronous hash chain reordering operation to finish, or
8485 * in order for us to perform an asynchronous chain reordering.
8487 * @note Hash chain reorderings occur when the access count for the
8488 * volume object being looked up exceeds the sum of the previous
8489 * node's (the node ahead of it in the hash chain linked list)
8490 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8492 * @note For DAFS, the hint parameter allows us to short-circuit if the
8493 * cacheCheck fields match between the hash chain head and the
8494 * hint volume object.
8497 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8501 #ifdef AFS_DEMAND_ATTACH_FS
8504 VolumeHashChainHead * head;
8507 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8509 #ifdef AFS_DEMAND_ATTACH_FS
8510 /* wait for the hash chain to become available */
8513 /* check to see if we can short circuit without walking the hash chain */
8514 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8515 IncUInt64(&hint->stats.hash_short_circuits);
8518 #endif /* AFS_DEMAND_ATTACH_FS */
8520 /* someday we need to either do per-chain locks, RWlocks,
8521 * or both for volhash access.
8522 * (and move to a data structure with better cache locality) */
8524 /* search the chain for this volume id */
8525 for(queue_Scan(head, vp, np, Volume)) {
8527 if (vp->hashid == volumeId) {
8532 if (queue_IsEnd(head, vp)) {
8536 #ifdef AFS_DEMAND_ATTACH_FS
8537 /* update hash chain statistics */
8540 FillInt64(lks, 0, looks);
8541 AddUInt64(head->looks, lks, &head->looks);
8542 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8543 IncUInt64(&head->gets);
8548 IncUInt64(&vp->stats.hash_lookups);
8550 /* for demand attach fileserver, we permit occasional hash chain reordering
8551 * so that frequently looked up volumes move towards the head of the chain */
8552 pp = queue_Prev(vp, Volume);
8553 if (!queue_IsEnd(head, pp)) {
8554 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8555 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8556 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8557 VReorderHash_r(head, pp, vp);
8561 /* update the short-circuit cache check */
8562 vp->chainCacheCheck = head->cacheCheck;
8564 #endif /* AFS_DEMAND_ATTACH_FS */
8569 #ifdef AFS_DEMAND_ATTACH_FS
8570 /* perform volume hash chain reordering.
8572 * advance a subchain beginning at vp ahead of
8573 * the adjacent subchain ending at pp */
8575 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8577 Volume *tp, *np, *lp;
8578 afs_uint64 move_thresh;
8580 /* this should never be called if the chain is already busy, so
8581 * no need to wait for other exclusive chain ops to finish */
8583 /* this is a rather heavy set of operations,
8584 * so let's set the chain busy flag and drop
8586 VHashBeginExclusive_r(head);
8589 /* scan forward in the chain from vp looking for the last element
8590 * in the chain we want to advance */
8591 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8592 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8593 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8594 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8598 lp = queue_Prev(tp, Volume);
8600 /* scan backwards from pp to determine where to splice and
8601 * insert the subchain we're advancing */
8602 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8603 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8607 tp = queue_Next(tp, Volume);
8609 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8610 queue_MoveChainBefore(tp,vp,lp);
8613 IncUInt64(&VStats.hash_reorders);
8615 IncUInt64(&head->reorders);
8617 /* wake up any threads waiting for the hash chain */
8618 VHashEndExclusive_r(head);
8622 /* demand-attach fs volume hash
8623 * asynchronous exclusive operations */
8626 * begin an asynchronous exclusive operation on a volume hash chain.
8628 * @param[in] head pointer to volume hash chain head object
8630 * @pre VOL_LOCK held. hash chain is quiescent.
8632 * @post hash chain marked busy.
8634 * @note this interface is used in conjunction with VHashEndExclusive_r and
8635 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8636 * volume hash chain. Its main use case is hash chain reordering, which
8637 * has the potential to be a highly latent operation.
8639 * @see VHashEndExclusive_r
8644 * @internal volume package internal use only.
8647 VHashBeginExclusive_r(VolumeHashChainHead * head)
8649 opr_Assert(head->busy == 0);
8654 * relinquish exclusive ownership of a volume hash chain.
8656 * @param[in] head pointer to volume hash chain head object
8658 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8660 * @post hash chain is marked quiescent. threads awaiting use of
8661 * chain are awakened.
8663 * @see VHashBeginExclusive_r
8668 * @internal volume package internal use only.
8671 VHashEndExclusive_r(VolumeHashChainHead * head)
8673 opr_Assert(head->busy);
8675 opr_cv_broadcast(&head->chain_busy_cv);
8679 * wait for all asynchronous operations on a hash chain to complete.
8681 * @param[in] head pointer to volume hash chain head object
8683 * @pre VOL_LOCK held.
8685 * @post hash chain object is quiescent.
8687 * @see VHashBeginExclusive_r
8688 * @see VHashEndExclusive_r
8692 * @note This interface should be called before any attempt to
8693 * traverse the hash chain. It is permissible for a thread
8694 * to gain exclusive access to the chain, and then perform
8695 * latent operations on the chain asynchronously wrt the
8698 * @warning if waiting is necessary, VOL_LOCK is dropped
8700 * @internal volume package internal use only.
8703 VHashWait_r(VolumeHashChainHead * head)
8705 while (head->busy) {
8706 VOL_CV_WAIT(&head->chain_busy_cv);
8709 #endif /* AFS_DEMAND_ATTACH_FS */
8712 /***************************************************/
8713 /* Volume by Partition List routines */
8714 /***************************************************/
8717 * demand attach fileserver adds a
8718 * linked list of volumes to each
8719 * partition object, thus allowing
8720 * for quick enumeration of all
8721 * volumes on a partition
8724 #ifdef AFS_DEMAND_ATTACH_FS
8726 * add a volume to its disk partition VByPList.
8728 * @param[in] vp pointer to volume object
8730 * @pre either the disk partition VByPList is owned exclusively
8731 * by the calling thread, or the list is quiescent and
8734 * @post volume is added to disk partition VByPList
8738 * @warning it is the caller's responsibility to ensure list
8741 * @see VVByPListWait_r
8742 * @see VVByPListBeginExclusive_r
8743 * @see VVByPListEndExclusive_r
8745 * @internal volume package internal use only.
8748 AddVolumeToVByPList_r(Volume * vp)
8750 if (queue_IsNotOnQueue(&vp->vol_list)) {
8751 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8752 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8753 vp->partition->vol_list.len++;
8758 * delete a volume from its disk partition VByPList.
8760 * @param[in] vp pointer to volume object
8762 * @pre either the disk partition VByPList is owned exclusively
8763 * by the calling thread, or the list is quiescent and
8766 * @post volume is removed from the disk partition VByPList
8770 * @warning it is the caller's responsibility to ensure list
8773 * @see VVByPListWait_r
8774 * @see VVByPListBeginExclusive_r
8775 * @see VVByPListEndExclusive_r
8777 * @internal volume package internal use only.
8780 DeleteVolumeFromVByPList_r(Volume * vp)
8782 if (queue_IsOnQueue(&vp->vol_list)) {
8783 queue_Remove(&vp->vol_list);
8784 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8785 vp->partition->vol_list.len--;
8790 * begin an asynchronous exclusive operation on a VByPList.
8792 * @param[in] dp pointer to disk partition object
8794 * @pre VOL_LOCK held. VByPList is quiescent.
8796 * @post VByPList marked busy.
8798 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8799 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8802 * @see VVByPListEndExclusive_r
8803 * @see VVByPListWait_r
8807 * @internal volume package internal use only.
8809 /* take exclusive control over the list */
8811 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8813 opr_Assert(dp->vol_list.busy == 0);
8814 dp->vol_list.busy = 1;
8818 * relinquish exclusive ownership of a VByPList.
8820 * @param[in] dp pointer to disk partition object
8822 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8824 * @post VByPList is marked quiescent. threads awaiting use of
8825 * the list are awakened.
8827 * @see VVByPListBeginExclusive_r
8828 * @see VVByPListWait_r
8832 * @internal volume package internal use only.
8835 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8837 opr_Assert(dp->vol_list.busy);
8838 dp->vol_list.busy = 0;
8839 opr_cv_broadcast(&dp->vol_list.cv);
8843 * wait for all asynchronous operations on a VByPList to complete.
8845 * @param[in] dp pointer to disk partition object
8847 * @pre VOL_LOCK is held.
8849 * @post disk partition's VByP list is quiescent
8853 * @note This interface should be called before any attempt to
8854 * traverse the VByPList. It is permissible for a thread
8855 * to gain exclusive access to the list, and then perform
8856 * latent operations on the list asynchronously wrt the
8859 * @warning if waiting is necessary, VOL_LOCK is dropped
8861 * @see VVByPListEndExclusive_r
8862 * @see VVByPListBeginExclusive_r
8864 * @internal volume package internal use only.
8867 VVByPListWait_r(struct DiskPartition64 * dp)
8869 while (dp->vol_list.busy) {
8870 VOL_CV_WAIT(&dp->vol_list.cv);
8873 #endif /* AFS_DEMAND_ATTACH_FS */
8875 /***************************************************/
8876 /* Volume Cache Statistics routines */
8877 /***************************************************/
8880 VPrintCacheStats_r(void)
8882 struct VnodeClassInfo *vcp;
8883 vcp = &VnodeClassInfo[vLarge];
8884 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);
8885 vcp = &VnodeClassInfo[vSmall];
8886 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);
8887 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8888 "%"AFS_INT64_FMT" replacements\n",
8889 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8893 VPrintCacheStats(void)
8896 VPrintCacheStats_r();
8900 #ifdef AFS_DEMAND_ATTACH_FS
8902 UInt64ToDouble(afs_uint64 * x)
8904 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8906 SplitInt64(*x, h, l);
8907 return (((double)h) * c32) + ((double) l);
8911 DoubleToPrintable(double x, char * buf, int len)
8913 static double billion = 1000000000.0;
8916 y[0] = (afs_uint32) (x / (billion * billion));
8917 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8918 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8921 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8923 snprintf(buf, len, "%d%09d", y[1], y[2]);
8925 snprintf(buf, len, "%d", y[2]);
8931 struct VLRUExtStatsEntry {
8935 struct VLRUExtStats {
8941 } queue_info[VLRU_QUEUE_INVALID];
8942 struct VLRUExtStatsEntry * vec;
8946 * add a 256-entry fudge factor onto the vector in case state changes
8947 * out from under us.
8949 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8952 * collect extended statistics for the VLRU subsystem.
8954 * @param[out] stats pointer to stats structure to be populated
8955 * @param[in] nvols number of volumes currently known to exist
8957 * @pre VOL_LOCK held
8959 * @post stats->vec allocated and populated
8961 * @return operation status
8966 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8968 afs_uint32 cur, idx, len;
8969 struct rx_queue * qp, * nqp;
8971 struct VLRUExtStatsEntry * vec;
8973 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8974 vec = stats->vec = calloc(len,
8975 sizeof(struct VLRUExtStatsEntry));
8981 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8982 VLRU_Wait_r(&volume_LRU.q[idx]);
8983 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8986 stats->queue_info[idx].start = cur;
8988 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8990 /* out of space in vec */
8993 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8994 vec[cur].volid = vp->hashid;
8998 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9001 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9009 #define ENUMTOSTRING(en) #en
9010 #define ENUMCASE(en) \
9011 case en: return ENUMTOSTRING(en)
9014 vlru_idx_to_string(int idx)
9017 ENUMCASE(VLRU_QUEUE_NEW);
9018 ENUMCASE(VLRU_QUEUE_MID);
9019 ENUMCASE(VLRU_QUEUE_OLD);
9020 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9021 ENUMCASE(VLRU_QUEUE_HELD);
9022 ENUMCASE(VLRU_QUEUE_INVALID);
9024 return "**UNKNOWN**";
9029 VPrintExtendedCacheStats_r(int flags)
9032 afs_uint32 vol_sum = 0;
9039 struct stats looks, gets, reorders, len;
9040 struct stats ch_looks, ch_gets, ch_reorders;
9042 VolumeHashChainHead *head;
9044 struct VLRUExtStats vlru_stats;
9046 /* zero out stats */
9047 memset(&looks, 0, sizeof(struct stats));
9048 memset(&gets, 0, sizeof(struct stats));
9049 memset(&reorders, 0, sizeof(struct stats));
9050 memset(&len, 0, sizeof(struct stats));
9051 memset(&ch_looks, 0, sizeof(struct stats));
9052 memset(&ch_gets, 0, sizeof(struct stats));
9053 memset(&ch_reorders, 0, sizeof(struct stats));
9055 for (i = 0; i < VolumeHashTable.Size; i++) {
9056 head = &VolumeHashTable.Table[i];
9059 VHashBeginExclusive_r(head);
9062 ch_looks.sum = UInt64ToDouble(&head->looks);
9063 ch_gets.sum = UInt64ToDouble(&head->gets);
9064 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9066 /* update global statistics */
9068 looks.sum += ch_looks.sum;
9069 gets.sum += ch_gets.sum;
9070 reorders.sum += ch_reorders.sum;
9071 len.sum += (double)head->len;
9072 vol_sum += head->len;
9075 len.min = (double) head->len;
9076 len.max = (double) head->len;
9077 looks.min = ch_looks.sum;
9078 looks.max = ch_looks.sum;
9079 gets.min = ch_gets.sum;
9080 gets.max = ch_gets.sum;
9081 reorders.min = ch_reorders.sum;
9082 reorders.max = ch_reorders.sum;
9084 if (((double)head->len) < len.min)
9085 len.min = (double) head->len;
9086 if (((double)head->len) > len.max)
9087 len.max = (double) head->len;
9088 if (ch_looks.sum < looks.min)
9089 looks.min = ch_looks.sum;
9090 else if (ch_looks.sum > looks.max)
9091 looks.max = ch_looks.sum;
9092 if (ch_gets.sum < gets.min)
9093 gets.min = ch_gets.sum;
9094 else if (ch_gets.sum > gets.max)
9095 gets.max = ch_gets.sum;
9096 if (ch_reorders.sum < reorders.min)
9097 reorders.min = ch_reorders.sum;
9098 else if (ch_reorders.sum > reorders.max)
9099 reorders.max = ch_reorders.sum;
9103 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9104 /* compute detailed per-chain stats */
9105 struct stats hdr_loads, hdr_gets;
9106 double v_looks, v_loads, v_gets;
9108 /* initialize stats with data from first element in chain */
9109 vp = queue_First(head, Volume);
9110 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9111 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9112 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9113 ch_gets.min = ch_gets.max = v_looks;
9114 hdr_loads.min = hdr_loads.max = v_loads;
9115 hdr_gets.min = hdr_gets.max = v_gets;
9116 hdr_loads.sum = hdr_gets.sum = 0;
9118 vp = queue_Next(vp, Volume);
9120 /* pull in stats from remaining elements in chain */
9121 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9122 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9123 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9124 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9126 hdr_loads.sum += v_loads;
9127 hdr_gets.sum += v_gets;
9129 if (v_looks < ch_gets.min)
9130 ch_gets.min = v_looks;
9131 else if (v_looks > ch_gets.max)
9132 ch_gets.max = v_looks;
9134 if (v_loads < hdr_loads.min)
9135 hdr_loads.min = v_loads;
9136 else if (v_loads > hdr_loads.max)
9137 hdr_loads.max = v_loads;
9139 if (v_gets < hdr_gets.min)
9140 hdr_gets.min = v_gets;
9141 else if (v_gets > hdr_gets.max)
9142 hdr_gets.max = v_gets;
9145 /* compute per-chain averages */
9146 ch_gets.avg = ch_gets.sum / ((double)head->len);
9147 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9148 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9150 /* dump per-chain stats */
9151 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9153 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9154 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9155 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9156 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9157 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9158 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9159 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9160 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9161 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9162 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9163 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9164 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9165 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9166 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9167 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9168 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9169 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9170 } else if (flags & VOL_STATS_PER_CHAIN) {
9171 /* dump simple per-chain stats */
9172 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9174 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9175 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9176 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9180 VHashEndExclusive_r(head);
9185 /* compute global averages */
9186 len.avg = len.sum / ((double)VolumeHashTable.Size);
9187 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9188 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9189 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9191 /* dump global stats */
9192 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9193 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9194 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9195 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9196 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9197 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9198 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9199 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9200 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9201 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9202 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9203 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9204 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9205 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9206 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9207 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9208 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9209 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9210 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9211 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9212 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9214 /* print extended disk related statistics */
9216 struct DiskPartition64 * diskP;
9217 afs_uint32 vol_count[VOLMAXPARTS+1];
9218 byte part_exists[VOLMAXPARTS+1];
9222 memset(vol_count, 0, sizeof(vol_count));
9223 memset(part_exists, 0, sizeof(part_exists));
9227 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9229 vol_count[id] = diskP->vol_list.len;
9230 part_exists[id] = 1;
9234 for (i = 0; i <= VOLMAXPARTS; i++) {
9235 if (part_exists[i]) {
9236 /* XXX while this is currently safe, it is a violation
9237 * of the VGetPartitionById_r interface contract. */
9238 diskP = VGetPartitionById_r(i, 0);
9240 Log("Partition %s has %d online volumes\n",
9241 VPartitionPath(diskP), diskP->vol_list.len);
9248 /* print extended VLRU statistics */
9249 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9250 afs_uint32 idx, cur, lpos;
9255 Log("VLRU State Dump:\n\n");
9257 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9258 Log("\t%s:\n", vlru_idx_to_string(idx));
9261 for (cur = vlru_stats.queue_info[idx].start;
9262 cur < vlru_stats.queue_info[idx].len;
9264 line[lpos++] = vlru_stats.vec[cur].volid;
9266 Log("\t\t%u, %u, %u, %u, %u,\n",
9267 line[0], line[1], line[2], line[3], line[4]);
9276 Log("\t\t%u, %u, %u, %u, %u\n",
9277 line[0], line[1], line[2], line[3], line[4]);
9282 free(vlru_stats.vec);
9289 VPrintExtendedCacheStats(int flags)
9292 VPrintExtendedCacheStats_r(flags);
9295 #endif /* AFS_DEMAND_ATTACH_FS */
9298 VCanScheduleSalvage(void)
9300 return vol_opts.canScheduleSalvage;
9306 return vol_opts.canUseFSSYNC;
9310 VCanUseSALVSYNC(void)
9312 return vol_opts.canUseSALVSYNC;
9316 VCanUnsafeAttach(void)
9318 return vol_opts.unsafe_attach;