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
35 #include <afs/afsint.h>
38 #if !defined(AFS_SGI_ENV)
41 #else /* AFS_OSF_ENV */
42 #ifdef AFS_VFSINCL_ENV
45 #include <sys/fs/ufs_fs.h>
47 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
48 #include <ufs/ufs/dinode.h>
49 #include <ufs/ffs/fs.h>
54 #else /* AFS_VFSINCL_ENV */
55 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
58 #endif /* AFS_VFSINCL_ENV */
59 #endif /* AFS_OSF_ENV */
60 #endif /* AFS_SGI_ENV */
61 #endif /* !AFS_NT40_ENV */
69 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
71 #include <sys/mnttab.h>
72 #include <sys/mntent.h>
78 #if defined(AFS_SGI_ENV)
81 #ifndef AFS_LINUX20_ENV
82 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
85 #endif /* AFS_SGI_ENV */
87 #endif /* AFS_HPUX_ENV */
91 #include <afs/errors.h>
94 #include <afs/afssyscalls.h>
96 #include <afs/afsutil.h>
97 #include "daemon_com.h"
102 #include "partition.h"
103 #include "volume_inline.h"
108 #ifdef AFS_PTHREAD_ENV
109 pthread_mutex_t vol_glock_mutex;
110 pthread_mutex_t vol_trans_mutex;
111 pthread_cond_t vol_put_volume_cond;
112 pthread_cond_t vol_sleep_cond;
113 pthread_cond_t vol_init_attach_cond;
114 pthread_cond_t vol_vinit_cond;
115 int vol_attach_threads = 1;
116 #endif /* AFS_PTHREAD_ENV */
118 /* start-time configurable I/O parameters */
119 ih_init_params vol_io_params;
121 #ifdef AFS_DEMAND_ATTACH_FS
122 pthread_mutex_t vol_salvsync_mutex;
125 * Set this to 1 to disallow SALVSYNC communication in all threads; used
126 * during shutdown, since the salvageserver may have gone away.
128 static volatile sig_atomic_t vol_disallow_salvsync = 0;
129 #endif /* AFS_DEMAND_ATTACH_FS */
132 * has VShutdown_r been called / is VShutdown_r running?
134 static int vol_shutting_down = 0;
137 extern void *calloc(), *realloc();
140 /* Forward declarations */
141 static Volume *attach2(Error * ec, VolId volumeId, char *path,
142 struct DiskPartition64 *partp, Volume * vp,
143 int isbusy, int mode, int *acheckedOut);
144 static void ReallyFreeVolume(Volume * vp);
145 #ifdef AFS_DEMAND_ATTACH_FS
146 static void FreeVolume(Volume * vp);
147 #else /* !AFS_DEMAND_ATTACH_FS */
148 #define FreeVolume(vp) ReallyFreeVolume(vp)
149 static void VScanUpdateList(void);
150 #endif /* !AFS_DEMAND_ATTACH_FS */
151 static void VInitVolumeHeaderCache(afs_uint32 howMany);
152 static int GetVolumeHeader(Volume * vp);
153 static void ReleaseVolumeHeader(struct volHeader *hd);
154 static void FreeVolumeHeader(Volume * vp);
155 static void AddVolumeToHashTable(Volume * vp, int hashid);
156 static void DeleteVolumeFromHashTable(Volume * vp);
158 static int VHold(Volume * vp);
160 static int VHold_r(Volume * vp);
161 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
162 static void VReleaseVolumeHandles_r(Volume * vp);
163 static void VCloseVolumeHandles_r(Volume * vp);
164 static void LoadVolumeHeader(Error * ec, Volume * vp);
165 static int VCheckOffline(Volume * vp);
166 static int VCheckDetach(Volume * vp);
167 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
168 Volume * hint, const struct timespec *ts);
170 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
171 * defined when not linked with vice, XXXX */
172 ProgramType programType; /* The type of program using the package */
173 static VolumePackageOptions vol_opts;
175 /* extended volume package statistics */
178 #ifdef VOL_LOCK_DEBUG
179 pthread_t vol_glock_holder = 0;
183 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
184 /* Must be a multiple of 4 (1 word) !! */
186 /* this parameter needs to be tunable at runtime.
187 * 128 was really inadequate for largish servers -- at 16384 volumes this
188 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
189 * talk about bad spatial locality...
191 * an AVL or splay tree might work a lot better, but we'll just increase
192 * the default hash table size for now
194 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
195 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
196 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
199 * turn volume hash chains into partially ordered lists.
200 * when the threshold is exceeded between two adjacent elements,
201 * perform a chain rebalancing operation.
203 * keep the threshold high in order to keep cache line invalidates
204 * low "enough" on SMPs
206 #define VOLUME_HASH_REORDER_THRESHOLD 200
209 * when possible, don't just reorder single elements, but reorder
210 * entire chains of elements at once. a chain of elements that
211 * exceed the element previous to the pivot by at least CHAIN_THRESH
212 * accesses are moved in front of the chain whose elements have at
213 * least CHAIN_THRESH less accesses than the pivot element
215 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
217 #include "rx/rx_queue.h"
220 VolumeHashTable_t VolumeHashTable = {
221 DEFAULT_VOLUME_HASH_SIZE,
222 DEFAULT_VOLUME_HASH_MASK,
227 static void VInitVolumeHash(void);
231 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
235 afs_int32 ffs_tmp = x;
239 for (ffs_i = 1;; ffs_i++) {
246 #endif /* !AFS_HAVE_FFS */
248 #ifdef AFS_PTHREAD_ENV
250 * disk partition queue element
252 typedef struct diskpartition_queue_t {
253 struct rx_queue queue; /**< queue header */
254 struct DiskPartition64 *diskP; /**< disk partition table entry */
255 } diskpartition_queue_t;
257 #ifndef AFS_DEMAND_ATTACH_FS
259 typedef struct vinitvolumepackage_thread_t {
260 struct rx_queue queue;
261 pthread_cond_t thread_done_cv;
262 int n_threads_complete;
263 } vinitvolumepackage_thread_t;
264 static void * VInitVolumePackageThread(void * args);
266 #else /* !AFS_DEMAND_ATTTACH_FS */
267 #define VINIT_BATCH_MAX_SIZE 512
270 * disk partition work queue
272 struct partition_queue {
273 struct rx_queue head; /**< diskpartition_queue_t queue */
274 pthread_mutex_t mutex;
279 * volumes parameters for preattach
281 struct volume_init_batch {
282 struct rx_queue queue; /**< queue header */
283 int thread; /**< posting worker thread */
284 int last; /**< indicates thread is done */
285 int size; /**< number of volume ids in batch */
286 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
290 * volume parameters work queue
292 struct volume_init_queue {
293 struct rx_queue head; /**< volume_init_batch queue */
294 pthread_mutex_t mutex;
299 * volume init worker thread parameters
301 struct vinitvolumepackage_thread_param {
302 int nthreads; /**< total number of worker threads */
303 int thread; /**< thread number for this worker thread */
304 struct partition_queue *pq; /**< queue partitions to scan */
305 struct volume_init_queue *vq; /**< queue of volume to preattach */
308 static void *VInitVolumePackageThread(void *args);
309 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
310 static VolId VInitNextVolumeId(DIR *dirp);
311 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
313 #endif /* !AFS_DEMAND_ATTACH_FS */
314 #endif /* AFS_PTHREAD_ENV */
316 #ifndef AFS_DEMAND_ATTACH_FS
317 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
318 int * nAttached, int * nUnattached);
319 #endif /* AFS_DEMAND_ATTACH_FS */
322 #ifdef AFS_DEMAND_ATTACH_FS
323 /* demand attach fileserver extensions */
326 * in the future we will support serialization of VLRU state into the fs_state
329 * these structures are the beginning of that effort
331 struct VLRU_DiskHeader {
332 struct versionStamp stamp; /* magic and structure version number */
333 afs_uint32 mtime; /* time of dump to disk */
334 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
337 struct VLRU_DiskEntry {
338 afs_uint32 vid; /* volume ID */
339 afs_uint32 idx; /* generation */
340 afs_uint32 last_get; /* timestamp of last get */
343 struct VLRU_StartupQueue {
344 struct VLRU_DiskEntry * entry;
349 typedef struct vshutdown_thread_t {
351 pthread_mutex_t lock;
353 pthread_cond_t master_cv;
355 int n_threads_complete;
357 int schedule_version;
360 byte n_parts_done_pass;
361 byte part_thread_target[VOLMAXPARTS+1];
362 byte part_done_pass[VOLMAXPARTS+1];
363 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
364 int stats[4][VOLMAXPARTS+1];
365 } vshutdown_thread_t;
366 static void * VShutdownThread(void * args);
369 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
370 static int VCheckFree(Volume * vp);
373 static void AddVolumeToVByPList_r(Volume * vp);
374 static void DeleteVolumeFromVByPList_r(Volume * vp);
375 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
376 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
377 static void VVByPListWait_r(struct DiskPartition64 * dp);
379 /* online salvager */
380 static int VCheckSalvage(Volume * vp);
381 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
382 static int VScheduleSalvage_r(Volume * vp);
385 /* Volume hash table */
386 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
387 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
388 static void VHashEndExclusive_r(VolumeHashChainHead * head);
389 static void VHashWait_r(VolumeHashChainHead * head);
392 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
393 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
394 struct rx_queue ** idx);
395 static void ShutdownController(vshutdown_thread_t * params);
396 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
399 static void VLRU_ComputeConstants(void);
400 static void VInitVLRU(void);
401 static void VLRU_Init_Node_r(Volume * vp);
402 static void VLRU_Add_r(Volume * vp);
403 static void VLRU_Delete_r(Volume * vp);
404 static void VLRU_UpdateAccess_r(Volume * vp);
405 static void * VLRU_ScannerThread(void * args);
406 static void VLRU_Scan_r(int idx);
407 static void VLRU_Promote_r(int idx);
408 static void VLRU_Demote_r(int idx);
409 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
412 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
413 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
414 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
417 pthread_key_t VThread_key;
418 VThreadOptions_t VThread_defaults = {
419 0 /**< allow salvsync */
421 #endif /* AFS_DEMAND_ATTACH_FS */
424 struct Lock vol_listLock; /* Lock obtained when listing volumes:
425 * prevents a volume from being missed
426 * if the volume is attached during a
430 /* Common message used when the volume goes off line */
431 char *VSalvageMessage =
432 "Files in this volume are currently unavailable; call operations";
434 int VInit; /* 0 - uninitialized,
435 * 1 - initialized but not all volumes have been attached,
436 * 2 - initialized and all volumes have been attached,
437 * 3 - initialized, all volumes have been attached, and
438 * VConnectFS() has completed. */
440 static int vinit_attach_abort = 0;
442 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
443 * used to stamp volume headers and in-core
444 * vnodes. When the volume goes on-line the
445 * vnode will be invalidated
446 * access only with VOL_LOCK held */
451 /***************************************************/
452 /* Startup routines */
453 /***************************************************/
455 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
456 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
457 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
461 * assign default values to a VolumePackageOptions struct.
463 * Always call this on a VolumePackageOptions struct first, then set any
464 * specific options you want, then call VInitVolumePackage2.
466 * @param[in] pt caller's program type
467 * @param[out] opts volume package options
470 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
472 opts->nLargeVnodes = opts->nSmallVnodes = 5;
475 opts->canScheduleSalvage = 0;
476 opts->canUseFSSYNC = 0;
477 opts->canUseSALVSYNC = 0;
479 opts->interrupt_rxcall = NULL;
480 opts->offline_timeout = -1;
481 opts->offline_shutdown_timeout = -1;
482 opts->usage_threshold = 128;
483 opts->usage_rate_limit = 5;
486 opts->unsafe_attach = 1;
487 #else /* !FAST_RESTART */
488 opts->unsafe_attach = 0;
489 #endif /* !FAST_RESTART */
493 opts->canScheduleSalvage = 1;
494 opts->canUseSALVSYNC = 1;
498 opts->canUseFSSYNC = 1;
502 opts->nLargeVnodes = 0;
503 opts->nSmallVnodes = 0;
505 opts->canScheduleSalvage = 1;
506 opts->canUseFSSYNC = 1;
516 * Set VInit to a certain value, and signal waiters.
518 * @param[in] value the value to set VInit to
523 VSetVInit_r(int value)
526 CV_BROADCAST(&vol_vinit_cond);
530 VLogOfflineTimeout(const char *type, afs_int32 timeout)
536 Log("VInitVolumePackage: Interrupting clients accessing %s "
537 "immediately\n", type);
539 Log("VInitVolumePackage: Interrupting clients accessing %s "
540 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
545 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
547 int errors = 0; /* Number of errors while finding vice partitions. */
552 #ifndef AFS_PTHREAD_ENV
553 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
554 Log("VInitVolumePackage: offline_timeout and/or "
555 "offline_shutdown_timeout was specified, but the volume package "
556 "does not support these for LWP builds\n");
560 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
561 VLogOfflineTimeout("volumes going offline during shutdown",
562 opts->offline_shutdown_timeout);
564 memset(&VStats, 0, sizeof(VStats));
565 VStats.hdr_cache_size = 200;
567 VInitPartitionPackage();
569 #ifdef AFS_DEMAND_ATTACH_FS
570 if (programType == fileServer) {
573 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
575 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
578 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
579 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
580 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
581 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
582 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
583 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
584 #ifndef AFS_PTHREAD_ENV
586 #endif /* AFS_PTHREAD_ENV */
587 Lock_Init(&vol_listLock);
589 srandom(time(0)); /* For VGetVolumeInfo */
591 #ifdef AFS_DEMAND_ATTACH_FS
592 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
593 #endif /* AFS_DEMAND_ATTACH_FS */
595 /* Ok, we have done enough initialization that fileserver can
596 * start accepting calls, even though the volumes may not be
597 * available just yet.
601 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
602 if (programType == salvageServer) {
605 #endif /* AFS_DEMAND_ATTACH_FS */
606 #ifdef FSSYNC_BUILD_SERVER
607 if (programType == fileServer) {
611 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
612 if (VCanUseSALVSYNC()) {
613 /* establish a connection to the salvager at this point */
614 osi_Assert(VConnectSALV() != 0);
616 #endif /* AFS_DEMAND_ATTACH_FS */
618 if (opts->volcache > VStats.hdr_cache_size)
619 VStats.hdr_cache_size = opts->volcache;
620 VInitVolumeHeaderCache(VStats.hdr_cache_size);
622 VInitVnodes(vLarge, opts->nLargeVnodes);
623 VInitVnodes(vSmall, opts->nSmallVnodes);
626 errors = VAttachPartitions();
630 if (programType != fileServer) {
631 errors = VInitAttachVolumes(programType);
637 #ifdef FSSYNC_BUILD_CLIENT
638 if (VCanUseFSSYNC()) {
640 #ifdef AFS_DEMAND_ATTACH_FS
641 if (programType == salvageServer) {
642 Log("Unable to connect to file server; aborted\n");
645 #endif /* AFS_DEMAND_ATTACH_FS */
646 Log("Unable to connect to file server; will retry at need\n");
649 #endif /* FSSYNC_BUILD_CLIENT */
654 #if !defined(AFS_PTHREAD_ENV)
656 * Attach volumes in vice partitions
658 * @param[in] pt calling program type
661 * @note This is the original, non-threaded version of attach parititions.
663 * @post VInit state is 2
666 VInitAttachVolumes(ProgramType pt)
668 osi_Assert(VInit==1);
669 if (pt == fileServer) {
670 struct DiskPartition64 *diskP;
671 /* Attach all the volumes in this partition */
672 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
673 int nAttached = 0, nUnattached = 0;
674 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
678 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
679 LWP_NoYieldSignal(VInitAttachVolumes);
683 #endif /* !AFS_PTHREAD_ENV */
685 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
687 * Attach volumes in vice partitions
689 * @param[in] pt calling program type
692 * @note Threaded version of attach parititions.
694 * @post VInit state is 2
697 VInitAttachVolumes(ProgramType pt)
699 osi_Assert(VInit==1);
700 if (pt == fileServer) {
701 struct DiskPartition64 *diskP;
702 struct vinitvolumepackage_thread_t params;
703 struct diskpartition_queue_t * dpq;
704 int i, threads, parts;
706 pthread_attr_t attrs;
708 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
710 params.n_threads_complete = 0;
712 /* create partition work queue */
713 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
714 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
715 osi_Assert(dpq != NULL);
717 queue_Append(¶ms,dpq);
720 threads = MIN(parts, vol_attach_threads);
723 /* spawn off a bunch of initialization threads */
724 osi_Assert(pthread_attr_init(&attrs) == 0);
725 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
727 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
728 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
732 for (i=0; i < threads; i++) {
735 osi_Assert(pthread_create
736 (&tid, &attrs, &VInitVolumePackageThread,
738 AFS_SIGSET_RESTORE();
741 while(params.n_threads_complete < threads) {
742 VOL_CV_WAIT(¶ms.thread_done_cv);
746 osi_Assert(pthread_attr_destroy(&attrs) == 0);
748 /* if we're only going to run one init thread, don't bother creating
750 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
751 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
754 VInitVolumePackageThread(¶ms);
757 CV_DESTROY(¶ms.thread_done_cv);
760 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
761 CV_BROADCAST(&vol_init_attach_cond);
767 VInitVolumePackageThread(void * args) {
769 struct DiskPartition64 *diskP;
770 struct vinitvolumepackage_thread_t * params;
771 struct diskpartition_queue_t * dpq;
773 params = (vinitvolumepackage_thread_t *) args;
777 /* Attach all the volumes in this partition */
778 while (queue_IsNotEmpty(params)) {
779 int nAttached = 0, nUnattached = 0;
781 if (vinit_attach_abort) {
782 Log("Aborting initialization\n");
786 dpq = queue_First(params,diskpartition_queue_t);
792 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
798 params->n_threads_complete++;
799 CV_SIGNAL(¶ms->thread_done_cv);
803 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
805 #if defined(AFS_DEMAND_ATTACH_FS)
807 * Attach volumes in vice partitions
809 * @param[in] pt calling program type
812 * @note Threaded version of attach partitions.
814 * @post VInit state is 2
817 VInitAttachVolumes(ProgramType pt)
819 osi_Assert(VInit==1);
820 if (pt == fileServer) {
822 struct DiskPartition64 *diskP;
823 struct partition_queue pq;
824 struct volume_init_queue vq;
826 int i, threads, parts;
828 pthread_attr_t attrs;
830 /* create partition work queue */
832 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
833 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
834 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
835 struct diskpartition_queue_t *dp;
836 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
837 osi_Assert(dp != NULL);
839 queue_Append(&pq, dp);
842 /* number of worker threads; at least one, not to exceed the number of partitions */
843 threads = MIN(parts, vol_attach_threads);
845 /* create volume work queue */
847 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
848 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
850 osi_Assert(pthread_attr_init(&attrs) == 0);
851 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
853 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
854 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
857 /* create threads to scan disk partitions. */
858 for (i=0; i < threads; i++) {
859 struct vinitvolumepackage_thread_param *params;
862 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
866 params->nthreads = threads;
867 params->thread = i+1;
870 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
871 AFS_SIGSET_RESTORE();
874 VInitPreAttachVolumes(threads, &vq);
876 osi_Assert(pthread_attr_destroy(&attrs) == 0);
878 MUTEX_DESTROY(&pq.mutex);
880 MUTEX_DESTROY(&vq.mutex);
884 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
885 CV_BROADCAST(&vol_init_attach_cond);
892 * Volume package initialization worker thread. Scan partitions for volume
893 * header files. Gather batches of volume ids and dispatch them to
894 * the main thread to be preattached. The volume preattachement is done
895 * in the main thread to avoid global volume lock contention.
898 VInitVolumePackageThread(void *args)
900 struct vinitvolumepackage_thread_param *params;
901 struct DiskPartition64 *partition;
902 struct partition_queue *pq;
903 struct volume_init_queue *vq;
904 struct volume_init_batch *vb;
907 params = (struct vinitvolumepackage_thread_param *)args;
913 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
915 vb->thread = params->thread;
919 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
920 while((partition = VInitNextPartition(pq))) {
924 Log("Partition %s: pre-attaching volumes\n", partition->name);
925 dirp = opendir(VPartitionPath(partition));
927 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
930 while ((vid = VInitNextVolumeId(dirp))) {
931 Volume *vp = (Volume*)malloc(sizeof(Volume));
933 memset(vp, 0, sizeof(Volume));
934 vp->device = partition->device;
935 vp->partition = partition;
937 queue_Init(&vp->vnode_list);
938 queue_Init(&vp->rx_call_list);
939 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
941 vb->batch[vb->size++] = vp;
942 if (vb->size == VINIT_BATCH_MAX_SIZE) {
943 MUTEX_ENTER(&vq->mutex);
944 queue_Append(vq, vb);
945 CV_BROADCAST(&vq->cv);
946 MUTEX_EXIT(&vq->mutex);
948 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
950 vb->thread = params->thread;
959 MUTEX_ENTER(&vq->mutex);
960 queue_Append(vq, vb);
961 CV_BROADCAST(&vq->cv);
962 MUTEX_EXIT(&vq->mutex);
964 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
970 * Read next element from the pre-populated partition list.
972 static struct DiskPartition64*
973 VInitNextPartition(struct partition_queue *pq)
975 struct DiskPartition64 *partition;
976 struct diskpartition_queue_t *dp; /* queue element */
978 if (vinit_attach_abort) {
979 Log("Aborting volume preattach thread.\n");
983 /* get next partition to scan */
984 MUTEX_ENTER(&pq->mutex);
985 if (queue_IsEmpty(pq)) {
986 MUTEX_EXIT(&pq->mutex);
989 dp = queue_First(pq, diskpartition_queue_t);
991 MUTEX_EXIT(&pq->mutex);
994 osi_Assert(dp->diskP);
996 partition = dp->diskP;
1002 * Find next volume id on the partition.
1005 VInitNextVolumeId(DIR *dirp)
1011 while((d = readdir(dirp))) {
1012 if (vinit_attach_abort) {
1013 Log("Aborting volume preattach thread.\n");
1016 ext = strrchr(d->d_name, '.');
1017 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1018 vid = VolumeNumber(d->d_name);
1022 Log("Warning: bogus volume header file: %s\n", d->d_name);
1029 * Preattach volumes in batches to avoid lock contention.
1032 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1034 struct volume_init_batch *vb;
1038 /* dequeue next volume */
1039 MUTEX_ENTER(&vq->mutex);
1040 if (queue_IsEmpty(vq)) {
1041 CV_WAIT(&vq->cv, &vq->mutex);
1043 vb = queue_First(vq, volume_init_batch);
1045 MUTEX_EXIT(&vq->mutex);
1049 for (i = 0; i<vb->size; i++) {
1055 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1057 Log("Error looking up volume, code=%d\n", ec);
1060 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1063 /* put pre-attached volume onto the hash table
1064 * and bring it up to the pre-attached state */
1065 AddVolumeToHashTable(vp, vp->hashid);
1066 AddVolumeToVByPList_r(vp);
1067 VLRU_Init_Node_r(vp);
1068 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1081 #endif /* AFS_DEMAND_ATTACH_FS */
1083 #if !defined(AFS_DEMAND_ATTACH_FS)
1085 * attach all volumes on a given disk partition
1088 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1094 Log("Partition %s: attaching volumes\n", diskP->name);
1095 dirp = opendir(VPartitionPath(diskP));
1097 Log("opendir on Partition %s failed!\n", diskP->name);
1101 while ((dp = readdir(dirp))) {
1103 p = strrchr(dp->d_name, '.');
1105 if (vinit_attach_abort) {
1106 Log("Partition %s: abort attach volumes\n", diskP->name);
1110 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1113 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1115 (*(vp ? nAttached : nUnattached))++;
1116 if (error == VOFFLINE)
1117 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1118 else if (LogLevel >= 5) {
1119 Log("Partition %s: attached volume %d (%s)\n",
1120 diskP->name, VolumeNumber(dp->d_name),
1129 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1134 #endif /* !AFS_DEMAND_ATTACH_FS */
1136 /***************************************************/
1137 /* Shutdown routines */
1138 /***************************************************/
1142 * highly multithreaded volume package shutdown
1144 * with the demand attach fileserver extensions,
1145 * VShutdown has been modified to be multithreaded.
1146 * In order to achieve optimal use of many threads,
1147 * the shutdown code involves one control thread and
1148 * n shutdown worker threads. The control thread
1149 * periodically examines the number of volumes available
1150 * for shutdown on each partition, and produces a worker
1151 * thread allocation schedule. The idea is to eliminate
1152 * redundant scheduling computation on the workers by
1153 * having a single master scheduler.
1155 * The scheduler's objectives are:
1157 * each partition with volumes remaining gets allocated
1158 * at least 1 thread (assuming sufficient threads)
1160 * threads are allocated proportional to the number of
1161 * volumes remaining to be offlined. This ensures that
1162 * the OS I/O scheduler has many requests to elevator
1163 * seek on partitions that will (presumably) take the
1164 * longest amount of time (from now) to finish shutdown
1165 * (3) keep threads busy
1166 * when there are extra threads, they are assigned to
1167 * partitions using a simple round-robin algorithm
1169 * In the future, we may wish to add the ability to adapt
1170 * to the relative performance patterns of each disk
1175 * multi-step shutdown process
1177 * demand attach shutdown is a four-step process. Each
1178 * shutdown "pass" shuts down increasingly more difficult
1179 * volumes. The main purpose is to achieve better cache
1180 * utilization during shutdown.
1183 * shutdown volumes in the unattached, pre-attached
1186 * shutdown attached volumes with cached volume headers
1188 * shutdown all volumes in non-exclusive states
1190 * shutdown all remaining volumes
1193 #ifdef AFS_DEMAND_ATTACH_FS
1199 struct DiskPartition64 * diskP;
1200 struct diskpartition_queue_t * dpq;
1201 vshutdown_thread_t params;
1203 pthread_attr_t attrs;
1205 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1208 Log("VShutdown: aborting attach volumes\n");
1209 vinit_attach_abort = 1;
1210 VOL_CV_WAIT(&vol_init_attach_cond);
1213 for (params.n_parts=0, diskP = DiskPartitionList;
1214 diskP; diskP = diskP->next, params.n_parts++);
1216 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1217 params.n_parts, params.n_parts > 1 ? "s" : "");
1219 vol_shutting_down = 1;
1221 if (vol_attach_threads > 1) {
1222 /* prepare for parallel shutdown */
1223 params.n_threads = vol_attach_threads;
1224 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1225 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1226 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1227 osi_Assert(pthread_attr_init(&attrs) == 0);
1228 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1229 queue_Init(¶ms);
1231 /* setup the basic partition information structures for
1232 * parallel shutdown */
1233 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1235 struct rx_queue * qp, * nqp;
1239 VVByPListWait_r(diskP);
1240 VVByPListBeginExclusive_r(diskP);
1243 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1244 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1248 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1249 VPartitionPath(diskP), count);
1252 /* build up the pass 0 shutdown work queue */
1253 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1254 osi_Assert(dpq != NULL);
1256 queue_Prepend(¶ms, dpq);
1258 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1261 Log("VShutdown: beginning parallel fileserver shutdown\n");
1262 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1263 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1265 /* do pass 0 shutdown */
1266 MUTEX_ENTER(¶ms.lock);
1267 for (i=0; i < params.n_threads; i++) {
1268 osi_Assert(pthread_create
1269 (&tid, &attrs, &VShutdownThread,
1273 /* wait for all the pass 0 shutdowns to complete */
1274 while (params.n_threads_complete < params.n_threads) {
1275 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1277 params.n_threads_complete = 0;
1279 CV_BROADCAST(¶ms.cv);
1280 MUTEX_EXIT(¶ms.lock);
1282 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1283 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1285 /* run the parallel shutdown scheduler. it will drop the glock internally */
1286 ShutdownController(¶ms);
1288 /* wait for all the workers to finish pass 3 and terminate */
1289 while (params.pass < 4) {
1290 VOL_CV_WAIT(¶ms.cv);
1293 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1294 CV_DESTROY(¶ms.cv);
1295 CV_DESTROY(¶ms.master_cv);
1296 MUTEX_DESTROY(¶ms.lock);
1298 /* drop the VByPList exclusive reservations */
1299 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1300 VVByPListEndExclusive_r(diskP);
1301 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1302 VPartitionPath(diskP),
1303 params.stats[0][diskP->index],
1304 params.stats[1][diskP->index],
1305 params.stats[2][diskP->index],
1306 params.stats[3][diskP->index]);
1309 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1311 /* if we're only going to run one shutdown thread, don't bother creating
1313 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1315 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1316 VShutdownByPartition_r(diskP);
1320 Log("VShutdown: complete.\n");
1323 #else /* AFS_DEMAND_ATTACH_FS */
1333 Log("VShutdown: aborting attach volumes\n");
1334 vinit_attach_abort = 1;
1335 #ifdef AFS_PTHREAD_ENV
1336 VOL_CV_WAIT(&vol_init_attach_cond);
1338 LWP_WaitProcess(VInitAttachVolumes);
1339 #endif /* AFS_PTHREAD_ENV */
1342 Log("VShutdown: shutting down on-line volumes...\n");
1343 vol_shutting_down = 1;
1344 for (i = 0; i < VolumeHashTable.Size; i++) {
1345 /* try to hold first volume in the hash table */
1346 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1350 Log("VShutdown: Attempting to take volume %u offline.\n",
1353 /* next, take the volume offline (drops reference count) */
1354 VOffline_r(vp, "File server was shut down");
1358 Log("VShutdown: complete.\n");
1360 #endif /* AFS_DEMAND_ATTACH_FS */
1366 osi_Assert(VInit>0);
1373 * stop new activity (e.g. SALVSYNC) from occurring
1375 * Use this to make the volume package less busy; for example, during
1376 * shutdown. This doesn't actually shutdown/detach anything in the
1377 * volume package, but prevents certain processes from ocurring. For
1378 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1379 * could also use this to prevent new volume attachment, or prevent
1380 * other programs from checking out volumes, etc.
1385 #ifdef AFS_DEMAND_ATTACH_FS
1386 /* make sure we don't try to contact the salvageserver, since it may
1387 * not be around anymore */
1388 vol_disallow_salvsync = 1;
1392 #ifdef AFS_DEMAND_ATTACH_FS
1395 * shutdown control thread
1398 ShutdownController(vshutdown_thread_t * params)
1401 struct DiskPartition64 * diskP;
1403 vshutdown_thread_t shadow;
1405 ShutdownCreateSchedule(params);
1407 while ((params->pass < 4) &&
1408 (params->n_threads_complete < params->n_threads)) {
1409 /* recompute schedule once per second */
1411 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1415 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1416 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1417 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1418 shadow.n_threads_complete, shadow.n_parts_done_pass);
1419 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1421 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1423 diskP->vol_list.len,
1424 shadow.part_thread_target[id],
1425 shadow.part_done_pass[id],
1426 shadow.part_pass_head[id]);
1432 ShutdownCreateSchedule(params);
1436 /* create the shutdown thread work schedule.
1437 * this scheduler tries to implement fairness
1438 * by allocating at least 1 thread to each
1439 * partition with volumes to be shutdown,
1440 * and then it attempts to allocate remaining
1441 * threads based upon the amount of work left
1444 ShutdownCreateSchedule(vshutdown_thread_t * params)
1446 struct DiskPartition64 * diskP;
1447 int sum, thr_workload, thr_left;
1448 int part_residue[VOLMAXPARTS+1];
1451 /* compute the total number of outstanding volumes */
1453 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1454 sum += diskP->vol_list.len;
1457 params->schedule_version++;
1458 params->vol_remaining = sum;
1463 /* compute average per-thread workload */
1464 thr_workload = sum / params->n_threads;
1465 if (sum % params->n_threads)
1468 thr_left = params->n_threads;
1469 memset(&part_residue, 0, sizeof(part_residue));
1471 /* for fairness, give every partition with volumes remaining
1472 * at least one thread */
1473 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1475 if (diskP->vol_list.len) {
1476 params->part_thread_target[id] = 1;
1479 params->part_thread_target[id] = 0;
1483 if (thr_left && thr_workload) {
1484 /* compute length-weighted workloads */
1487 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1489 delta = (diskP->vol_list.len / thr_workload) -
1490 params->part_thread_target[id];
1494 if (delta < thr_left) {
1495 params->part_thread_target[id] += delta;
1498 params->part_thread_target[id] += thr_left;
1506 /* try to assign any leftover threads to partitions that
1507 * had volume lengths closer to needing thread_target+1 */
1508 int max_residue, max_id = 0;
1510 /* compute the residues */
1511 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1513 part_residue[id] = diskP->vol_list.len -
1514 (params->part_thread_target[id] * thr_workload);
1517 /* now try to allocate remaining threads to partitions with the
1518 * highest residues */
1521 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1523 if (part_residue[id] > max_residue) {
1524 max_residue = part_residue[id];
1533 params->part_thread_target[max_id]++;
1535 part_residue[max_id] = 0;
1540 /* punt and give any remaining threads equally to each partition */
1542 if (thr_left >= params->n_parts) {
1543 alloc = thr_left / params->n_parts;
1544 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1546 params->part_thread_target[id] += alloc;
1551 /* finish off the last of the threads */
1552 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1554 params->part_thread_target[id]++;
1560 /* worker thread for parallel shutdown */
1562 VShutdownThread(void * args)
1564 vshutdown_thread_t * params;
1565 int found, pass, schedule_version_save, count;
1566 struct DiskPartition64 *diskP;
1567 struct diskpartition_queue_t * dpq;
1570 params = (vshutdown_thread_t *) args;
1572 /* acquire the shutdown pass 0 lock */
1573 MUTEX_ENTER(¶ms->lock);
1575 /* if there's still pass 0 work to be done,
1576 * get a work entry, and do a pass 0 shutdown */
1577 if (queue_IsNotEmpty(params)) {
1578 dpq = queue_First(params, diskpartition_queue_t);
1580 MUTEX_EXIT(¶ms->lock);
1586 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1588 params->stats[0][diskP->index] = count;
1589 MUTEX_ENTER(¶ms->lock);
1592 params->n_threads_complete++;
1593 if (params->n_threads_complete == params->n_threads) {
1594 /* notify control thread that all workers have completed pass 0 */
1595 CV_SIGNAL(¶ms->master_cv);
1597 while (params->pass == 0) {
1598 CV_WAIT(¶ms->cv, ¶ms->lock);
1602 MUTEX_EXIT(¶ms->lock);
1605 pass = params->pass;
1606 osi_Assert(pass > 0);
1608 /* now escalate through the more complicated shutdowns */
1610 schedule_version_save = params->schedule_version;
1612 /* find a disk partition to work on */
1613 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1615 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1616 params->part_thread_target[id]--;
1623 /* hmm. for some reason the controller thread couldn't find anything for
1624 * us to do. let's see if there's anything we can do */
1625 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1627 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1630 } else if (!params->part_done_pass[id]) {
1631 params->part_done_pass[id] = 1;
1632 params->n_parts_done_pass++;
1634 Log("VShutdown: done shutting down volumes on partition %s.\n",
1635 VPartitionPath(diskP));
1641 /* do work on this partition until either the controller
1642 * creates a new schedule, or we run out of things to do
1643 * on this partition */
1646 while (!params->part_done_pass[id] &&
1647 (schedule_version_save == params->schedule_version)) {
1648 /* ShutdownVolumeWalk_r will drop the glock internally */
1649 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1650 if (!params->part_done_pass[id]) {
1651 params->part_done_pass[id] = 1;
1652 params->n_parts_done_pass++;
1654 Log("VShutdown: done shutting down volumes on partition %s.\n",
1655 VPartitionPath(diskP));
1663 params->stats[pass][id] += count;
1665 /* ok, everyone is done this pass, proceed */
1668 params->n_threads_complete++;
1669 while (params->pass == pass) {
1670 if (params->n_threads_complete == params->n_threads) {
1671 /* we are the last thread to complete, so we will
1672 * reinitialize worker pool state for the next pass */
1673 params->n_threads_complete = 0;
1674 params->n_parts_done_pass = 0;
1676 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1678 params->part_done_pass[id] = 0;
1679 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1682 /* compute a new thread schedule before releasing all the workers */
1683 ShutdownCreateSchedule(params);
1685 /* wake up all the workers */
1686 CV_BROADCAST(¶ms->cv);
1689 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1690 pass, params->n_threads, params->n_parts);
1693 VOL_CV_WAIT(¶ms->cv);
1696 pass = params->pass;
1710 /* shut down all volumes on a given disk partition
1712 * note that this function will not allow mp-fast
1713 * shutdown of a partition */
1715 VShutdownByPartition_r(struct DiskPartition64 * dp)
1721 /* wait for other exclusive ops to finish */
1722 VVByPListWait_r(dp);
1724 /* begin exclusive access */
1725 VVByPListBeginExclusive_r(dp);
1727 /* pick the low-hanging fruit first,
1728 * then do the complicated ones last
1729 * (has the advantage of keeping
1730 * in-use volumes up until the bitter end) */
1731 for (pass = 0, total=0; pass < 4; pass++) {
1732 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1733 total += pass_stats[pass];
1736 /* end exclusive access */
1737 VVByPListEndExclusive_r(dp);
1739 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1740 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1745 /* internal shutdown functionality
1747 * for multi-pass shutdown:
1748 * 0 to only "shutdown" {pre,un}attached and error state volumes
1749 * 1 to also shutdown attached volumes w/ volume header loaded
1750 * 2 to also shutdown attached volumes w/o volume header loaded
1751 * 3 to also shutdown exclusive state volumes
1753 * caller MUST hold exclusive access on the hash chain
1754 * because we drop vol_glock_mutex internally
1756 * this function is reentrant for passes 1--3
1757 * (e.g. multiple threads can cooperate to
1758 * shutdown a partition mp-fast)
1760 * pass 0 is not scaleable because the volume state data is
1761 * synchronized by vol_glock mutex, and the locking overhead
1762 * is too high to drop the lock long enough to do linked list
1766 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1768 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1771 while (ShutdownVolumeWalk_r(dp, pass, &q))
1777 /* conditionally shutdown one volume on partition dp
1778 * returns 1 if a volume was shutdown in this pass,
1781 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1782 struct rx_queue ** idx)
1784 struct rx_queue *qp, *nqp;
1789 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1790 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1794 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1795 (V_attachState(vp) != VOL_STATE_ERROR) &&
1796 (V_attachState(vp) != VOL_STATE_DELETED) &&
1797 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1801 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1802 (vp->header == NULL)) {
1806 if (VIsExclusiveState(V_attachState(vp))) {
1811 DeleteVolumeFromVByPList_r(vp);
1812 VShutdownVolume_r(vp);
1822 * shutdown a specific volume
1824 /* caller MUST NOT hold a heavyweight ref on vp */
1826 VShutdownVolume_r(Volume * vp)
1830 VCreateReservation_r(vp);
1832 if (LogLevel >= 5) {
1833 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1834 vp->hashid, vp->partition->device, V_attachState(vp));
1837 /* wait for other blocking ops to finish */
1838 VWaitExclusiveState_r(vp);
1840 osi_Assert(VIsValidState(V_attachState(vp)));
1842 switch(V_attachState(vp)) {
1843 case VOL_STATE_SALVAGING:
1844 /* Leave salvaging volumes alone. Any in-progress salvages will
1845 * continue working after viced shuts down. This is intentional.
1848 case VOL_STATE_PREATTACHED:
1849 case VOL_STATE_ERROR:
1850 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1851 case VOL_STATE_UNATTACHED:
1852 case VOL_STATE_DELETED:
1854 case VOL_STATE_GOING_OFFLINE:
1855 case VOL_STATE_SHUTTING_DOWN:
1856 case VOL_STATE_ATTACHED:
1860 Log("VShutdown: Attempting to take volume %u offline.\n",
1863 /* take the volume offline (drops reference count) */
1864 VOffline_r(vp, "File server was shut down");
1871 VCancelReservation_r(vp);
1875 #endif /* AFS_DEMAND_ATTACH_FS */
1878 /***************************************************/
1879 /* Header I/O routines */
1880 /***************************************************/
1883 HeaderName(bit32 magic)
1886 case VOLUMEINFOMAGIC:
1887 return "volume info";
1888 case SMALLINDEXMAGIC:
1889 return "small index";
1890 case LARGEINDEXMAGIC:
1891 return "large index";
1892 case LINKTABLEMAGIC:
1893 return "link table";
1898 /* open a descriptor for the inode (h),
1899 * read in an on-disk structure into buffer (to) of size (size),
1900 * verify versionstamp in structure has magic (magic) and
1901 * optionally verify version (version) if (version) is nonzero
1904 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1907 struct versionStamp *vsn;
1909 afs_sfsize_t nbytes;
1914 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1922 Log("ReadHeader: Failed to open %s header file "
1923 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1924 PrintInode(stmp, h->ih_ino), errno);
1929 vsn = (struct versionStamp *)to;
1930 nbytes = FDH_PREAD(fdP, to, size, 0);
1932 Log("ReadHeader: Failed to read %s header file "
1933 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1934 PrintInode(stmp, h->ih_ino), errno);
1936 FDH_REALLYCLOSE(fdP);
1939 if (nbytes != size) {
1940 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1941 "(volume=%u, inode=%s); expected=%d, read=%d\n",
1942 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), size,
1945 FDH_REALLYCLOSE(fdP);
1948 if (vsn->magic != magic) {
1949 Log("ReadHeader: Incorrect magic for %s header file "
1950 "(volume=%u, inode=%s); expected=0x%x, read=0x%x\n",
1951 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), magic,
1954 FDH_REALLYCLOSE(fdP);
1960 /* Check is conditional, in case caller wants to inspect version himself */
1961 if (version && vsn->version != version) {
1962 Log("ReadHeader: Incorrect version for %s header file "
1963 "(volume=%u, inode=%s); expected=%x, read=%x\n",
1964 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino),
1965 version, vsn->version);
1971 WriteVolumeHeader_r(Error * ec, Volume * vp)
1973 IHandle_t *h = V_diskDataHandle(vp);
1983 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1984 != sizeof(V_disk(vp))) {
1986 FDH_REALLYCLOSE(fdP);
1992 /* VolumeHeaderToDisk
1993 * Allows for storing 64 bit inode numbers in on-disk volume header
1996 /* convert in-memory representation of a volume header to the
1997 * on-disk representation of a volume header */
1999 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2002 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2003 dh->stamp = h->stamp;
2005 dh->parent = h->parent;
2007 #ifdef AFS_64BIT_IOPS_ENV
2008 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2009 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2010 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2011 dh->smallVnodeIndex_hi =
2012 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2013 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2014 dh->largeVnodeIndex_hi =
2015 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2016 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2017 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2019 dh->volumeInfo_lo = h->volumeInfo;
2020 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2021 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2022 dh->linkTable_lo = h->linkTable;
2026 /* DiskToVolumeHeader
2027 * Converts an on-disk representation of a volume header to
2028 * the in-memory representation of a volume header.
2030 * Makes the assumption that AFS has *always*
2031 * zero'd the volume header file so that high parts of inode
2032 * numbers are 0 in older (SGI EFS) volume header files.
2035 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2037 memset(h, 0, sizeof(VolumeHeader_t));
2038 h->stamp = dh->stamp;
2040 h->parent = dh->parent;
2042 #ifdef AFS_64BIT_IOPS_ENV
2044 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2046 h->smallVnodeIndex =
2047 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2048 smallVnodeIndex_hi << 32);
2050 h->largeVnodeIndex =
2051 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2052 largeVnodeIndex_hi << 32);
2054 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2056 h->volumeInfo = dh->volumeInfo_lo;
2057 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2058 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2059 h->linkTable = dh->linkTable_lo;
2064 /***************************************************/
2065 /* Volume Attachment routines */
2066 /***************************************************/
2068 #ifdef AFS_DEMAND_ATTACH_FS
2070 * pre-attach a volume given its path.
2072 * @param[out] ec outbound error code
2073 * @param[in] partition partition path string
2074 * @param[in] name volume id string
2076 * @return volume object pointer
2078 * @note A pre-attached volume will only have its partition
2079 * and hashid fields initialized. At first call to
2080 * VGetVolume, the volume will be fully attached.
2084 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2088 vp = VPreAttachVolumeByName_r(ec, partition, name);
2094 * pre-attach a volume given its path.
2096 * @param[out] ec outbound error code
2097 * @param[in] partition path to vice partition
2098 * @param[in] name volume id string
2100 * @return volume object pointer
2102 * @pre VOL_LOCK held
2104 * @internal volume package internal use only.
2107 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2109 return VPreAttachVolumeById_r(ec,
2111 VolumeNumber(name));
2115 * pre-attach a volume given its path and numeric volume id.
2117 * @param[out] ec error code return
2118 * @param[in] partition path to vice partition
2119 * @param[in] volumeId numeric volume id
2121 * @return volume object pointer
2123 * @pre VOL_LOCK held
2125 * @internal volume package internal use only.
2128 VPreAttachVolumeById_r(Error * ec,
2133 struct DiskPartition64 *partp;
2137 osi_Assert(programType == fileServer);
2139 if (!(partp = VGetPartition_r(partition, 0))) {
2141 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2145 vp = VLookupVolume_r(ec, volumeId, NULL);
2150 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2154 * preattach a volume.
2156 * @param[out] ec outbound error code
2157 * @param[in] partp pointer to partition object
2158 * @param[in] vp pointer to volume object
2159 * @param[in] vid volume id
2161 * @return volume object pointer
2163 * @pre VOL_LOCK is held.
2165 * @warning Returned volume object pointer does not have to
2166 * equal the pointer passed in as argument vp. There
2167 * are potential race conditions which can result in
2168 * the pointers having different values. It is up to
2169 * the caller to make sure that references are handled
2170 * properly in this case.
2172 * @note If there is already a volume object registered with
2173 * the same volume id, its pointer MUST be passed as
2174 * argument vp. Failure to do so will result in a silent
2175 * failure to preattach.
2177 * @internal volume package internal use only.
2180 VPreAttachVolumeByVp_r(Error * ec,
2181 struct DiskPartition64 * partp,
2189 /* check to see if pre-attach already happened */
2191 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2192 (V_attachState(vp) != VOL_STATE_DELETED) &&
2193 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2194 !VIsErrorState(V_attachState(vp))) {
2196 * pre-attach is a no-op in all but the following cases:
2198 * - volume is unattached
2199 * - volume is in an error state
2200 * - volume is pre-attached
2202 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state (state %u flags 0x%x)\n",
2203 vid, V_attachState(vp), V_attachFlags(vp));
2206 /* we're re-attaching a volume; clear out some old state */
2207 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2209 if (V_partition(vp) != partp) {
2210 /* XXX potential race */
2211 DeleteVolumeFromVByPList_r(vp);
2214 /* if we need to allocate a new Volume struct,
2215 * go ahead and drop the vol glock, otherwise
2216 * do the basic setup synchronised, as it's
2217 * probably not worth dropping the lock */
2220 /* allocate the volume structure */
2221 vp = nvp = (Volume *) malloc(sizeof(Volume));
2222 osi_Assert(vp != NULL);
2223 memset(vp, 0, sizeof(Volume));
2224 queue_Init(&vp->vnode_list);
2225 queue_Init(&vp->rx_call_list);
2226 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2229 /* link the volume with its associated vice partition */
2230 vp->device = partp->device;
2231 vp->partition = partp;
2234 vp->specialStatus = 0;
2236 /* if we dropped the lock, reacquire the lock,
2237 * check for pre-attach races, and then add
2238 * the volume to the hash table */
2241 nvp = VLookupVolume_r(ec, vid, NULL);
2246 } else if (nvp) { /* race detected */
2251 /* hack to make up for VChangeState_r() decrementing
2252 * the old state counter */
2253 VStats.state_levels[0]++;
2257 /* put pre-attached volume onto the hash table
2258 * and bring it up to the pre-attached state */
2259 AddVolumeToHashTable(vp, vp->hashid);
2260 AddVolumeToVByPList_r(vp);
2261 VLRU_Init_Node_r(vp);
2262 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2265 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2273 #endif /* AFS_DEMAND_ATTACH_FS */
2275 /* Attach an existing volume, given its pathname, and return a
2276 pointer to the volume header information. The volume also
2277 normally goes online at this time. An offline volume
2278 must be reattached to make it go online */
2280 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2284 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2290 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2293 struct DiskPartition64 *partp;
2298 #ifdef AFS_DEMAND_ATTACH_FS
2299 VolumeStats stats_save;
2301 #endif /* AFS_DEMAND_ATTACH_FS */
2305 volumeId = VolumeNumber(name);
2307 if (!(partp = VGetPartition_r(partition, 0))) {
2309 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2313 if (VRequiresPartLock()) {
2314 osi_Assert(VInit == 3);
2315 VLockPartition_r(partition);
2316 } else if (programType == fileServer) {
2317 #ifdef AFS_DEMAND_ATTACH_FS
2318 /* lookup the volume in the hash table */
2319 vp = VLookupVolume_r(ec, volumeId, NULL);
2325 /* save any counters that are supposed to
2326 * be monotonically increasing over the
2327 * lifetime of the fileserver */
2328 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2330 memset(&stats_save, 0, sizeof(VolumeStats));
2333 /* if there's something in the hash table, and it's not
2334 * in the pre-attach state, then we may need to detach
2335 * it before proceeding */
2336 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2337 VCreateReservation_r(vp);
2338 VWaitExclusiveState_r(vp);
2340 /* at this point state must be one of:
2350 if (vp->specialStatus == VBUSY)
2353 /* if it's already attached, see if we can return it */
2354 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2355 VGetVolumeByVp_r(ec, vp);
2356 if (V_inUse(vp) == fileServer) {
2357 VCancelReservation_r(vp);
2361 /* otherwise, we need to detach, and attempt to re-attach */
2362 VDetachVolume_r(ec, vp);
2364 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2367 /* if it isn't fully attached, delete from the hash tables,
2368 and let the refcounter handle the rest */
2369 DeleteVolumeFromHashTable(vp);
2370 DeleteVolumeFromVByPList_r(vp);
2373 VCancelReservation_r(vp);
2377 /* pre-attach volume if it hasn't been done yet */
2379 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2380 (V_attachState(vp) == VOL_STATE_DELETED) ||
2381 (V_attachState(vp) == VOL_STATE_ERROR)) {
2383 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2389 osi_Assert(vp != NULL);
2391 /* handle pre-attach races
2393 * multiple threads can race to pre-attach a volume,
2394 * but we can't let them race beyond that
2396 * our solution is to let the first thread to bring
2397 * the volume into an exclusive state win; the other
2398 * threads just wait until it finishes bringing the
2399 * volume online, and then they do a vgetvolumebyvp
2401 if (svp && (svp != vp)) {
2402 /* wait for other exclusive ops to finish */
2403 VCreateReservation_r(vp);
2404 VWaitExclusiveState_r(vp);
2406 /* get a heavyweight ref, kill the lightweight ref, and return */
2407 VGetVolumeByVp_r(ec, vp);
2408 VCancelReservation_r(vp);
2412 /* at this point, we are chosen as the thread to do
2413 * demand attachment for this volume. all other threads
2414 * doing a getvolume on vp->hashid will block until we finish */
2416 /* make sure any old header cache entries are invalidated
2417 * before proceeding */
2418 FreeVolumeHeader(vp);
2420 VChangeState_r(vp, VOL_STATE_ATTACHING);
2422 /* restore any saved counters */
2423 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2424 #else /* AFS_DEMAND_ATTACH_FS */
2425 vp = VGetVolume_r(ec, volumeId);
2427 if (V_inUse(vp) == fileServer)
2429 if (vp->specialStatus == VBUSY)
2431 VDetachVolume_r(ec, vp);
2433 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2437 #endif /* AFS_DEMAND_ATTACH_FS */
2441 strcpy(path, VPartitionPath(partp));
2445 strcat(path, OS_DIRSEP);
2449 vp = (Volume *) calloc(1, sizeof(Volume));
2450 osi_Assert(vp != NULL);
2451 vp->hashid = volumeId;
2452 vp->device = partp->device;
2453 vp->partition = partp;
2454 queue_Init(&vp->vnode_list);
2455 queue_Init(&vp->rx_call_list);
2456 #ifdef AFS_DEMAND_ATTACH_FS
2457 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2458 #endif /* AFS_DEMAND_ATTACH_FS */
2461 /* attach2 is entered without any locks, and returns
2462 * with vol_glock_mutex held */
2463 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2465 if (VCanUseFSSYNC() && vp) {
2466 #ifdef AFS_DEMAND_ATTACH_FS
2467 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2468 /* mark volume header as in use so that volser crashes lead to a
2469 * salvage attempt */
2470 VUpdateVolume_r(ec, vp, 0);
2472 /* for dafs, we should tell the fileserver, except for V_PEEK
2473 * where we know it is not necessary */
2474 if (mode == V_PEEK) {
2475 vp->needsPutBack = 0;
2477 vp->needsPutBack = VOL_PUTBACK;
2479 #else /* !AFS_DEMAND_ATTACH_FS */
2480 /* duplicate computation in fssync.c about whether the server
2481 * takes the volume offline or not. If the volume isn't
2482 * offline, we must not return it when we detach the volume,
2483 * or the server will abort */
2484 if (mode == V_READONLY || mode == V_PEEK
2485 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2486 vp->needsPutBack = 0;
2488 vp->needsPutBack = VOL_PUTBACK;
2489 #endif /* !AFS_DEMAND_ATTACH_FS */
2491 #ifdef FSSYNC_BUILD_CLIENT
2492 /* Only give back the vol to the fileserver if we checked it out; attach2
2493 * will set checkedOut only if we successfully checked it out from the
2495 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2497 #ifdef AFS_DEMAND_ATTACH_FS
2498 /* If we couldn't attach but we scheduled a salvage, we already
2499 * notified the fileserver; don't online it now */
2500 if (*ec != VSALVAGING)
2501 #endif /* AFS_DEMAND_ATTACH_FS */
2502 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2505 if (programType == fileServer && vp) {
2506 #ifdef AFS_DEMAND_ATTACH_FS
2508 * we can get here in cases where we don't "own"
2509 * the volume (e.g. volume owned by a utility).
2510 * short circuit around potential disk header races.
2512 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2516 VUpdateVolume_r(ec, vp, 0);
2518 Log("VAttachVolume: Error updating volume\n");
2523 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2524 #ifndef AFS_DEMAND_ATTACH_FS
2525 /* This is a hack: by temporarily setting the incore
2526 * dontSalvage flag ON, the volume will be put back on the
2527 * Update list (with dontSalvage OFF again). It will then
2528 * come back in N minutes with DONT_SALVAGE eventually
2529 * set. This is the way that volumes that have never had
2530 * it set get it set; or that volumes that have been
2531 * offline without DONT SALVAGE having been set also
2532 * eventually get it set */
2533 V_dontSalvage(vp) = DONT_SALVAGE;
2534 #endif /* !AFS_DEMAND_ATTACH_FS */
2535 VAddToVolumeUpdateList_r(ec, vp);
2537 Log("VAttachVolume: Error adding volume to update list\n");
2544 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2549 if (VRequiresPartLock()) {
2550 VUnlockPartition_r(partition);
2553 #ifdef AFS_DEMAND_ATTACH_FS
2554 /* attach failed; make sure we're in error state */
2555 if (vp && !VIsErrorState(V_attachState(vp))) {
2556 VChangeState_r(vp, VOL_STATE_ERROR);
2558 #endif /* AFS_DEMAND_ATTACH_FS */
2565 #ifdef AFS_DEMAND_ATTACH_FS
2566 /* VAttachVolumeByVp_r
2568 * finish attaching a volume that is
2569 * in a less than fully attached state
2571 /* caller MUST hold a ref count on vp */
2573 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2575 char name[VMAXPATHLEN];
2577 struct DiskPartition64 *partp;
2581 Volume * nvp = NULL;
2582 VolumeStats stats_save;
2586 /* volume utility should never call AttachByVp */
2587 osi_Assert(programType == fileServer);
2589 volumeId = vp->hashid;
2590 partp = vp->partition;
2591 VolumeExternalName_r(volumeId, name, sizeof(name));
2594 /* if another thread is performing a blocking op, wait */
2595 VWaitExclusiveState_r(vp);
2597 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2599 /* if it's already attached, see if we can return it */
2600 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2601 VGetVolumeByVp_r(ec, vp);
2602 if (V_inUse(vp) == fileServer) {
2605 if (vp->specialStatus == VBUSY)
2607 VDetachVolume_r(ec, vp);
2609 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2615 /* pre-attach volume if it hasn't been done yet */
2617 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2618 (V_attachState(vp) == VOL_STATE_DELETED) ||
2619 (V_attachState(vp) == VOL_STATE_ERROR)) {
2620 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2626 VCreateReservation_r(nvp);
2631 osi_Assert(vp != NULL);
2632 VChangeState_r(vp, VOL_STATE_ATTACHING);
2634 /* restore monotonically increasing stats */
2635 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2639 /* compute path to disk header */
2640 strcpy(path, VPartitionPath(partp));
2644 strcat(path, OS_DIRSEP);
2649 * NOTE: attach2 is entered without any locks, and returns
2650 * with vol_glock_mutex held */
2651 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2654 * the event that an error was encountered, or
2655 * the volume was not brought to an attached state
2656 * for any reason, skip to the end. We cannot
2657 * safely call VUpdateVolume unless we "own" it.
2661 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2665 VUpdateVolume_r(ec, vp, 0);
2667 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2671 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2672 #ifndef AFS_DEMAND_ATTACH_FS
2673 /* This is a hack: by temporarily setting the incore
2674 * dontSalvage flag ON, the volume will be put back on the
2675 * Update list (with dontSalvage OFF again). It will then
2676 * come back in N minutes with DONT_SALVAGE eventually
2677 * set. This is the way that volumes that have never had
2678 * it set get it set; or that volumes that have been
2679 * offline without DONT SALVAGE having been set also
2680 * eventually get it set */
2681 V_dontSalvage(vp) = DONT_SALVAGE;
2682 #endif /* !AFS_DEMAND_ATTACH_FS */
2683 VAddToVolumeUpdateList_r(ec, vp);
2685 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2692 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2696 VCancelReservation_r(nvp);
2699 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2700 if (vp && !VIsErrorState(V_attachState(vp))) {
2701 VChangeState_r(vp, VOL_STATE_ERROR);
2710 * lock a volume on disk (non-blocking).
2712 * @param[in] vp The volume to lock
2713 * @param[in] locktype READ_LOCK or WRITE_LOCK
2715 * @return operation status
2716 * @retval 0 success, lock was obtained
2717 * @retval EBUSY a conflicting lock was held by another process
2718 * @retval EIO error acquiring lock
2720 * @pre If we're in the fileserver, vp is in an exclusive state
2722 * @pre vp is not already locked
2725 VLockVolumeNB(Volume *vp, int locktype)
2729 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2730 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2732 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2734 V_attachFlags(vp) |= VOL_LOCKED;
2741 * unlock a volume on disk that was locked with VLockVolumeNB.
2743 * @param[in] vp volume to unlock
2745 * @pre If we're in the fileserver, vp is in an exclusive state
2747 * @pre vp has already been locked
2750 VUnlockVolume(Volume *vp)
2752 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2753 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2755 VUnlockVolumeById(vp->hashid, vp->partition);
2757 V_attachFlags(vp) &= ~VOL_LOCKED;
2759 #endif /* AFS_DEMAND_ATTACH_FS */
2762 * read in a vol header, possibly lock the vol header, and possibly check out
2763 * the vol header from the fileserver, as part of volume attachment.
2765 * @param[out] ec error code
2766 * @param[in] vp volume pointer object
2767 * @param[in] partp disk partition object of the attaching partition
2768 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2770 * @param[in] peek 1 to just try to read in the volume header and make sure
2771 * we don't try to lock the vol, or check it out from
2772 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2774 * @param[out] acheckedOut If we successfully checked-out the volume from
2775 * the fileserver (if we needed to), this is set
2776 * to 1, otherwise it is untouched.
2778 * @note As part of DAFS volume attachment, the volume header may be either
2779 * read- or write-locked to ensure mutual exclusion of certain volume
2780 * operations. In some cases in order to determine whether we need to
2781 * read- or write-lock the header, we need to read in the header to see
2782 * if the volume is RW or not. So, if we read in the header under a
2783 * read-lock and determine that we actually need a write-lock on the
2784 * volume header, this function will drop the read lock, acquire a write
2785 * lock, and read the header in again.
2788 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2789 int mode, int peek, int *acheckedOut)
2791 struct VolumeDiskHeader diskHeader;
2792 struct VolumeHeader header;
2795 int lock_tries = 0, checkout_tries = 0;
2797 VolumeId volid = vp->hashid;
2798 #ifdef FSSYNC_BUILD_CLIENT
2799 int checkout, done_checkout = 0;
2800 #endif /* FSSYNC_BUILD_CLIENT */
2801 #ifdef AFS_DEMAND_ATTACH_FS
2802 int locktype = 0, use_locktype = -1;
2803 #endif /* AFS_DEMAND_ATTACH_FS */
2809 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2810 Log("VAttachVolume: retried too many times trying to lock header for "
2811 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2812 VPartitionPath(partp));
2816 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2817 Log("VAttachVolume: retried too many times trying to checkout "
2818 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2819 VPartitionPath(partp));
2824 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2825 /* short-circuit the 'volume does not exist' case */
2830 #ifdef FSSYNC_BUILD_CLIENT
2831 checkout = !done_checkout;
2833 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2835 memset(&res, 0, sizeof(res));
2837 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2840 if (res.hdr.reason == FSYNC_SALVAGE) {
2841 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2842 afs_printable_uint32_lu(volid));
2845 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2846 afs_printable_uint32_lu(volid));
2847 *ec = VNOVOL; /* XXXX */
2855 #ifdef AFS_DEMAND_ATTACH_FS
2856 if (use_locktype < 0) {
2857 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2858 * if it turns out to be RW */
2859 locktype = VVolLockType(mode, 0);
2862 /* a previous try says we should use use_locktype to lock the volume,
2864 locktype = use_locktype;
2867 if (!peek && locktype) {
2868 code = VLockVolumeNB(vp, locktype);
2870 if (code == EBUSY) {
2871 Log("VAttachVolume: another program has vol %lu locked\n",
2872 afs_printable_uint32_lu(volid));
2874 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2875 code, afs_printable_uint32_lu(volid));
2882 #endif /* AFS_DEMAND_ATTACH_FS */
2884 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2894 DiskToVolumeHeader(&header, &diskHeader);
2896 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2897 header.largeVnodeIndex);
2898 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2899 header.smallVnodeIndex);
2900 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2902 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2905 /* only need to do this once */
2907 GetVolumeHeader(vp);
2911 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2912 /* demand attach changes the V_PEEK mechanism
2914 * we can now suck the current disk data structure over
2915 * the fssync interface without going to disk
2917 * (technically, we don't need to restrict this feature
2918 * to demand attach fileservers. However, I'm trying
2919 * to limit the number of common code changes)
2921 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2923 res.payload.len = sizeof(VolumeDiskData);
2924 res.payload.buf = &vp->header->diskstuff;
2926 if (FSYNC_VolOp(vp->hashid,
2928 FSYNC_VOL_QUERY_HDR,
2931 goto disk_header_loaded;
2934 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2935 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2936 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2938 #ifdef AFS_DEMAND_ATTACH_FS
2941 IncUInt64(&VStats.hdr_loads);
2942 IncUInt64(&vp->stats.hdr_loads);
2944 #endif /* AFS_DEMAND_ATTACH_FS */
2947 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2948 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2952 #ifdef AFS_DEMAND_ATTACH_FS
2953 # ifdef FSSYNC_BUILD_CLIENT
2955 # endif /* FSSYNC_BUILD_CLIENT */
2957 /* if the lock type we actually used to lock the volume is different than
2958 * the lock type we should have used, retry with the lock type we should
2960 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2961 if (locktype != use_locktype) {
2965 #endif /* AFS_DEMAND_ATTACH_FS */
2970 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2971 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2973 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2975 if (code == SYNC_DENIED) {
2976 /* must retry checkout; fileserver no longer thinks we have
2982 } else if (code != SYNC_OK) {
2986 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2989 /* either we are going to be called again for a second pass, or we
2990 * encountered an error; clean up in either case */
2992 #ifdef AFS_DEMAND_ATTACH_FS
2993 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2996 #endif /* AFS_DEMAND_ATTACH_FS */
2997 if (vp->linkHandle) {
2998 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2999 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3000 IH_RELEASE(vp->diskDataHandle);
3001 IH_RELEASE(vp->linkHandle);
3014 #ifdef AFS_DEMAND_ATTACH_FS
3016 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3017 Volume *vp, int *acheckedOut)
3021 if (vp->pending_vol_op) {
3025 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3027 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3029 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3030 } else if (code == 0) {
3031 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3034 /* we need the vol header to determine if the volume can be
3035 * left online for the vop, so... get the header */
3039 /* attach header with peek=1 to avoid checking out the volume
3040 * or locking it; we just want the header info, we're not
3041 * messing with the volume itself at all */
3042 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3049 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3050 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3052 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3055 /* make sure we grab a new vol header and re-open stuff on
3056 * actual attachment; we can't keep the data we grabbed, since
3057 * it was not done under a lock and thus not safe */
3058 FreeVolumeHeader(vp);
3059 VReleaseVolumeHandles_r(vp);
3062 /* see if the pending volume op requires exclusive access */
3063 switch (vp->pending_vol_op->vol_op_state) {
3064 case FSSYNC_VolOpPending:
3065 /* this should never happen */
3066 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3069 case FSSYNC_VolOpRunningUnknown:
3070 /* this should never happen; we resolved 'unknown' above */
3071 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3074 case FSSYNC_VolOpRunningOffline:
3075 /* mark the volume down */
3077 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3079 /* do not set V_offlineMessage here; we don't have ownership of
3080 * the volume (and probably do not have the header loaded), so we
3081 * can't alter the disk header */
3083 /* check to see if we should set the specialStatus flag */
3084 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3085 /* don't overwrite specialStatus if it was already set to
3086 * something else (e.g. VMOVED) */
3087 if (!vp->specialStatus) {
3088 vp->specialStatus = VBUSY;
3100 #endif /* AFS_DEMAND_ATTACH_FS */
3103 * volume attachment helper function.
3105 * @param[out] ec error code
3106 * @param[in] volumeId volume ID of the attaching volume
3107 * @param[in] path full path to the volume header .vol file
3108 * @param[in] partp disk partition object for the attaching partition
3109 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3110 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3111 * DAFS) should already be initialized
3112 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3113 * if there is a volume operation running for this volume
3114 * that should set the volume to VBUSY during its run. 0
3115 * otherwise. (see VVolOpSetVBusy_r)
3116 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3118 * @param[out] acheckedOut If we successfully checked-out the volume from
3119 * the fileserver (if we needed to), this is set
3120 * to 1, otherwise it is 0.
3122 * @return pointer to the semi-attached volume pointer
3123 * @retval NULL an error occurred (check value of *ec)
3124 * @retval vp volume successfully attaching
3126 * @pre no locks held
3128 * @post VOL_LOCK held
3131 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3132 Volume * vp, int isbusy, int mode, int *acheckedOut)
3134 /* have we read in the header successfully? */
3135 int read_header = 0;
3137 #ifdef AFS_DEMAND_ATTACH_FS
3138 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3142 /* in the case of an error, to what state should the volume be
3144 VolState error_state = VOL_STATE_ERROR;
3145 #endif /* AFS_DEMAND_ATTACH_FS */
3149 vp->vnodeIndex[vLarge].handle = NULL;
3150 vp->vnodeIndex[vSmall].handle = NULL;
3151 vp->diskDataHandle = NULL;
3152 vp->linkHandle = NULL;
3156 #ifdef AFS_DEMAND_ATTACH_FS
3157 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3159 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3162 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3163 #endif /* !AFS_DEMAND_ATTACH_FS */
3165 if (*ec == VNOVOL) {
3166 /* if the volume doesn't exist, skip straight to 'error' so we don't
3167 * request a salvage */
3169 goto error_notbroken;
3175 /* ensure that we don't override specialStatus if it was set to
3176 * something else (e.g. VMOVED) */
3177 if (isbusy && !vp->specialStatus) {
3178 vp->specialStatus = VBUSY;
3180 vp->shuttingDown = 0;
3181 vp->goingOffline = 0;
3183 #ifdef AFS_DEMAND_ATTACH_FS
3184 vp->stats.last_attach = FT_ApproxTime();
3185 vp->stats.attaches++;
3189 IncUInt64(&VStats.attaches);
3190 vp->cacheCheck = ++VolumeCacheCheck;
3191 /* just in case this ever rolls over */
3192 if (!vp->cacheCheck)
3193 vp->cacheCheck = ++VolumeCacheCheck;
3196 #ifdef AFS_DEMAND_ATTACH_FS
3197 V_attachFlags(vp) |= VOL_HDR_LOADED;
3198 vp->stats.last_hdr_load = vp->stats.last_attach;
3199 #endif /* AFS_DEMAND_ATTACH_FS */
3203 struct IndexFileHeader iHead;
3205 #if OPENAFS_VOL_STATS
3207 * We just read in the diskstuff part of the header. If the detailed
3208 * volume stats area has not yet been initialized, we should bzero the
3209 * area and mark it as initialized.
3211 if (!(V_stat_initialized(vp))) {
3212 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3213 V_stat_initialized(vp) = 1;
3215 #endif /* OPENAFS_VOL_STATS */
3217 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3218 (char *)&iHead, sizeof(iHead),
3219 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3222 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3227 struct IndexFileHeader iHead;
3229 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3230 (char *)&iHead, sizeof(iHead),
3231 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3234 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3238 #ifdef AFS_NAMEI_ENV
3240 struct versionStamp stamp;
3242 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3243 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3246 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3249 #endif /* AFS_NAMEI_ENV */
3251 #if defined(AFS_DEMAND_ATTACH_FS)
3252 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3254 if (!VCanScheduleSalvage()) {
3255 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3257 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3262 /* volume operation in progress */
3264 goto error_notbroken;
3266 #else /* AFS_DEMAND_ATTACH_FS */
3268 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3269 goto unlocked_error;
3271 #endif /* AFS_DEMAND_ATTACH_FS */
3273 if (V_needsSalvaged(vp)) {
3274 if (vp->specialStatus)
3275 vp->specialStatus = 0;
3277 #if defined(AFS_DEMAND_ATTACH_FS)
3278 if (!VCanScheduleSalvage()) {
3279 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3281 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3284 #else /* AFS_DEMAND_ATTACH_FS */
3286 #endif /* AFS_DEMAND_ATTACH_FS */
3292 vp->nextVnodeUnique = V_uniquifier(vp);
3294 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3295 if (!V_needsSalvaged(vp)) {
3296 V_needsSalvaged(vp) = 1;
3297 VUpdateVolume_r(ec, vp, 0);
3299 #if defined(AFS_DEMAND_ATTACH_FS)
3300 if (!VCanScheduleSalvage()) {
3301 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3303 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3306 #else /* AFS_DEMAND_ATTACH_FS */
3307 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3309 #endif /* AFS_DEMAND_ATTACH_FS */
3314 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3315 /* Only check destroyMe if we are the fileserver, since the
3316 * volserver et al sometimes need to work with volumes with
3317 * destroyMe set. Examples are 'temporary' volumes the
3318 * volserver creates, and when we create a volume (destroyMe
3319 * is set on creation; sometimes a separate volserver
3320 * transaction is created to clear destroyMe).
3323 #if defined(AFS_DEMAND_ATTACH_FS)
3324 /* schedule a salvage so the volume goes away on disk */
3325 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3326 VChangeState_r(vp, VOL_STATE_ERROR);
3329 #endif /* AFS_DEMAND_ATTACH_FS */
3330 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3335 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3336 #ifndef BITMAP_LATER
3337 if (programType == fileServer && VolumeWriteable(vp)) {
3339 for (i = 0; i < nVNODECLASSES; i++) {
3340 VGetBitmap_r(ec, vp, i);
3342 #ifdef AFS_DEMAND_ATTACH_FS
3343 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3345 #endif /* AFS_DEMAND_ATTACH_FS */
3346 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3352 #endif /* BITMAP_LATER */
3354 if (VInit >= 2 && V_needsCallback(vp)) {
3355 if (V_BreakVolumeCallbacks) {
3356 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3357 afs_printable_uint32_lu(V_id(vp)));
3358 V_needsCallback(vp) = 0;
3360 (*V_BreakVolumeCallbacks) (V_id(vp));
3363 VUpdateVolume_r(ec, vp, 0);
3365 #ifdef FSSYNC_BUILD_CLIENT
3366 else if (VCanUseFSSYNC()) {
3367 afs_int32 fsync_code;
3369 V_needsCallback(vp) = 0;
3371 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3375 V_needsCallback(vp) = 1;
3376 Log("Error trying to tell the fileserver to break callbacks for "
3377 "changed volume %lu; error code %ld\n",
3378 afs_printable_uint32_lu(V_id(vp)),
3379 afs_printable_int32_ld(fsync_code));
3381 VUpdateVolume_r(ec, vp, 0);
3384 #endif /* FSSYNC_BUILD_CLIENT */
3387 Log("VAttachVolume: error %d clearing needsCallback on volume "
3388 "%lu; needs salvage\n", (int)*ec,
3389 afs_printable_uint32_lu(V_id(vp)));
3390 #ifdef AFS_DEMAND_ATTACH_FS
3391 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3393 #else /* !AFS_DEMAND_ATTACH_FS */
3395 #endif /* !AFS_DEMAND_ATTACh_FS */
3400 if (programType == fileServer) {
3401 if (vp->specialStatus)
3402 vp->specialStatus = 0;
3403 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3404 V_inUse(vp) = fileServer;
3405 V_offlineMessage(vp)[0] = '\0';
3409 #ifdef AFS_DEMAND_ATTACH_FS
3410 /* Put the vol into PREATTACHED state, so if someone tries to
3411 * access it again, we try to attach, see that we're not blessed,
3412 * and give a VNOVOL error again. Putting it into UNATTACHED state
3413 * would result in a VOFFLINE error instead. */
3414 error_state = VOL_STATE_PREATTACHED;
3415 #endif /* AFS_DEMAND_ATTACH_FS */
3417 /* mimic e.g. GetVolume errors */
3418 if (!V_blessed(vp)) {
3419 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3420 FreeVolumeHeader(vp);
3421 } else if (!V_inService(vp)) {
3422 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3423 FreeVolumeHeader(vp);
3425 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3427 #ifdef AFS_DEMAND_ATTACH_FS
3428 error_state = VOL_STATE_ERROR;
3429 /* see if we can recover */
3430 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0 /*flags*/);
3433 #ifdef AFS_DEMAND_ATTACH_FS
3439 #ifdef AFS_DEMAND_ATTACH_FS
3440 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3441 V_inUse(vp) = programType;
3442 #endif /* AFS_DEMAND_ATTACH_FS */
3443 V_checkoutMode(vp) = mode;
3446 AddVolumeToHashTable(vp, V_id(vp));
3447 #ifdef AFS_DEMAND_ATTACH_FS
3448 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3451 if ((programType != fileServer) ||
3452 (V_inUse(vp) == fileServer)) {
3453 AddVolumeToVByPList_r(vp);
3455 VChangeState_r(vp, VOL_STATE_ATTACHED);
3457 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3463 #ifndef AFS_DEMAND_ATTACH_FS
3469 #ifdef AFS_DEMAND_ATTACH_FS
3470 if (!VIsErrorState(V_attachState(vp))) {
3471 if (VIsErrorState(error_state)) {
3472 Log("attach2: forcing vol %u to error state (state %u flags 0x%x ec %d)\n",
3473 vp->hashid, V_attachState(vp), V_attachFlags(vp), *ec);
3475 VChangeState_r(vp, error_state);
3477 #endif /* AFS_DEMAND_ATTACH_FS */
3480 VReleaseVolumeHandles_r(vp);
3484 #ifdef AFS_DEMAND_ATTACH_FS
3491 #else /* !AFS_DEMAND_ATTACH_FS */
3493 #endif /* !AFS_DEMAND_ATTACH_FS */
3497 /* Attach an existing volume.
3498 The volume also normally goes online at this time.
3499 An offline volume must be reattached to make it go online.
3503 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3507 retVal = VAttachVolume_r(ec, volumeId, mode);
3513 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3516 VGetVolumePath(ec, volumeId, &part, &name);
3520 vp = VGetVolume_r(&error, volumeId);
3522 osi_Assert(V_inUse(vp) == 0);
3523 VDetachVolume_r(ec, vp);
3527 return VAttachVolumeByName_r(ec, part, name, mode);
3530 /* Increment a reference count to a volume, sans context swaps. Requires
3531 * possibly reading the volume header in from the disk, since there's
3532 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3534 * N.B. This call can fail if we can't read in the header!! In this case
3535 * we still guarantee we won't context swap, but the ref count won't be
3536 * incremented (otherwise we'd violate the invariant).
3538 /* NOTE: with the demand attach fileserver extensions, the global lock
3539 * is dropped within VHold */
3540 #ifdef AFS_DEMAND_ATTACH_FS
3542 VHold_r(Volume * vp)
3546 VCreateReservation_r(vp);
3547 VWaitExclusiveState_r(vp);
3549 LoadVolumeHeader(&error, vp);
3551 VCancelReservation_r(vp);
3555 VCancelReservation_r(vp);
3558 #else /* AFS_DEMAND_ATTACH_FS */
3560 VHold_r(Volume * vp)
3564 LoadVolumeHeader(&error, vp);
3570 #endif /* AFS_DEMAND_ATTACH_FS */
3572 /**** volume timeout-related stuff ****/
3574 #ifdef AFS_PTHREAD_ENV
3576 static struct timespec *shutdown_timeout;
3577 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3580 VTimedOut(const struct timespec *ts)
3585 if (ts->tv_sec == 0) {
3586 /* short-circuit; this will have always timed out */
3590 code = gettimeofday(&tv, NULL);
3592 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3593 /* assume no timeout; failure mode is we just wait longer than normal
3594 * instead of returning errors when we shouldn't */
3598 if (tv.tv_sec < ts->tv_sec ||
3599 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3608 * Calculate an absolute timeout.
3610 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3611 * NULL, the memory is not touched
3612 * @param[in] timeout How long the timeout should be from now
3614 * @return timeout to use
3615 * @retval NULL no timeout; wait forever
3616 * @retval non-NULL the given value for "ts"
3620 static struct timespec *
3621 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3631 ts->tv_sec = ts->tv_nsec = 0;
3635 code = gettimeofday(&now, NULL);
3637 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3641 ts->tv_sec = now.tv_sec + timeout;
3642 ts->tv_nsec = now.tv_usec * 1000;
3648 * Initialize the shutdown_timeout global.
3651 VShutdownTimeoutInit(void)
3653 struct timespec *ts;
3655 ts = malloc(sizeof(*ts));
3657 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3659 if (!shutdown_timeout) {
3665 * Figure out the timeout that should be used for waiting for offline volumes.
3667 * @param[out] ats Storage space for a local timeout value if needed
3669 * @return The timeout value that should be used
3670 * @retval NULL No timeout; wait forever for offlining volumes
3671 * @retval non-NULL A pointer to the absolute time that should be used as
3672 * the deadline for waiting for offlining volumes.
3674 * @note If we return non-NULL, the pointer we return may or may not be the
3677 static const struct timespec *
3678 VOfflineTimeout(struct timespec *ats)
3680 if (vol_shutting_down) {
3681 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3682 return shutdown_timeout;
3684 return VCalcTimeout(ats, vol_opts.offline_timeout);
3688 #else /* AFS_PTHREAD_ENV */
3690 /* Waiting a certain amount of time for offlining volumes is not supported
3691 * for LWP due to a lack of primitives. So, we never time out */
3692 # define VTimedOut(x) (0)
3693 # define VOfflineTimeout(x) (NULL)
3695 #endif /* !AFS_PTHREAD_ENV */
3703 retVal = VHold_r(vp);
3710 VIsGoingOffline_r(struct Volume *vp)
3714 if (vp->goingOffline) {
3715 if (vp->specialStatus) {
3716 code = vp->specialStatus;
3717 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3728 * Tell the caller if a volume is waiting to go offline.
3730 * @param[in] vp The volume we want to know about
3732 * @return volume status
3733 * @retval 0 volume is not waiting to go offline, go ahead and use it
3734 * @retval nonzero volume is waiting to offline, and give the returned code
3735 * as an error to anyone accessing the volume
3737 * @pre VOL_LOCK is NOT held
3738 * @pre caller holds a heavyweight reference on vp
3741 VIsGoingOffline(struct Volume *vp)
3746 code = VIsGoingOffline_r(vp);
3753 * Register an RX call with a volume.
3755 * @param[inout] ec Error code; if unset when passed in, may be set if
3756 * the volume starts going offline
3757 * @param[out] client_ec @see GetVolume
3758 * @param[in] vp Volume struct
3759 * @param[in] cbv VCallByVol struct containing the RX call to register
3761 * @pre VOL_LOCK held
3762 * @pre caller holds heavy ref on vp
3767 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3770 #ifdef AFS_DEMAND_ATTACH_FS
3772 /* just in case the volume started going offline after we got the
3773 * reference to it... otherwise, if the volume started going
3774 * offline right at the end of GetVolume(), we might race with the
3775 * RX call scanner, and return success and add our cbv to the
3776 * rx_call_list _after_ the scanner has scanned the list. */
3777 *ec = VIsGoingOffline_r(vp);
3783 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3784 VWaitStateChange_r(vp);
3786 #endif /* AFS_DEMAND_ATTACH_FS */
3788 queue_Prepend(&vp->rx_call_list, cbv);
3793 * Deregister an RX call with a volume.
3795 * @param[in] vp Volume struct
3796 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3798 * @pre VOL_LOCK held
3799 * @pre caller holds heavy ref on vp
3804 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3806 if (cbv && queue_IsOnQueue(cbv)) {
3807 #ifdef AFS_DEMAND_ATTACH_FS
3808 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3809 VWaitStateChange_r(vp);
3811 #endif /* AFS_DEMAND_ATTACH_FS */
3817 /***************************************************/
3818 /* get and put volume routines */
3819 /***************************************************/
3822 * put back a heavyweight reference to a volume object.
3824 * @param[in] vp volume object pointer
3826 * @pre VOL_LOCK held
3828 * @post heavyweight volume reference put back.
3829 * depending on state, volume may have been taken offline,
3830 * detached, salvaged, freed, etc.
3832 * @internal volume package internal use only
3835 VPutVolume_r(Volume * vp)
3837 osi_Assert(--vp->nUsers >= 0);
3838 if (vp->nUsers == 0) {
3840 ReleaseVolumeHeader(vp->header);
3841 #ifdef AFS_DEMAND_ATTACH_FS
3842 if (!VCheckDetach(vp)) {
3846 #else /* AFS_DEMAND_ATTACH_FS */
3848 #endif /* AFS_DEMAND_ATTACH_FS */
3853 VPutVolume(Volume * vp)
3861 * Puts a volume reference obtained with VGetVolumeWithCall.
3863 * @param[in] vp Volume struct
3864 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3866 * @pre VOL_LOCK is NOT held
3869 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3872 VDeregisterCall_r(vp, cbv);
3877 /* Get a pointer to an attached volume. The pointer is returned regardless
3878 of whether or not the volume is in service or on/off line. An error
3879 code, however, is returned with an indication of the volume's status */
3881 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3885 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3891 * Get a volume reference associated with an RX call.
3893 * @param[out] ec @see GetVolume
3894 * @param[out] client_ec @see GetVolume
3895 * @param[in] volumeId @see GetVolume
3896 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3897 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3898 * with an error if the volume is going offline.
3899 * @param[in] cbv Contains an RX call to be associated with this volume
3900 * reference. This call may be interrupted if the volume is
3901 * requested to go offline while we hold a ref on it. Give NULL
3902 * to not associate an RX call with this reference.
3904 * @return @see GetVolume
3906 * @note for LWP builds, ts must be NULL
3908 * @note A reference obtained with this function MUST be put back with
3909 * VPutVolumeWithCall
3912 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3913 const struct timespec *ts, struct VCallByVol *cbv)
3917 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3918 VRegisterCall_r(ec, client_ec, retVal, cbv);
3924 VGetVolume_r(Error * ec, VolId volumeId)
3926 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3929 /* try to get a volume we've previously looked up */
3930 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3932 VGetVolumeByVp_r(Error * ec, Volume * vp)
3934 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3938 * private interface for getting a volume handle
3940 * @param[out] ec error code (0 if no error)
3941 * @param[out] client_ec wire error code to be given to clients
3942 * @param[in] volumeId ID of the volume we want
3943 * @param[in] hint optional hint for hash lookups, or NULL
3944 * @param[in] timeout absolute deadline for waiting for the volume to go
3945 * offline, if it is going offline. NULL to wait forever.
3947 * @return a volume handle for the specified volume
3948 * @retval NULL an error occurred, or the volume is in such a state that
3949 * we cannot load a header or return any volume struct
3951 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3953 * @note 'timeout' is only checked if the volume is actually going offline; so
3954 * if you pass timeout->tv_sec = 0, this will exhibit typical
3955 * nonblocking behavior.
3957 * @note for LWP builds, 'timeout' must be NULL
3960 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3961 const struct timespec *timeout)
3964 /* pull this profiling/debugging code out of regular builds */
3966 #define VGET_CTR_INC(x) x++
3967 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3968 0, V7 = 0, V8 = 0, V9 = 0;
3969 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3971 #define VGET_CTR_INC(x)
3973 #ifdef AFS_DEMAND_ATTACH_FS
3974 Volume *avp, * rvp = hint;
3978 * if VInit is zero, the volume package dynamic
3979 * data structures have not been initialized yet,
3980 * and we must immediately return an error
3986 *client_ec = VOFFLINE;
3991 #ifdef AFS_DEMAND_ATTACH_FS
3993 VCreateReservation_r(rvp);
3995 #endif /* AFS_DEMAND_ATTACH_FS */
4003 vp = VLookupVolume_r(ec, volumeId, vp);
4009 #ifdef AFS_DEMAND_ATTACH_FS
4010 if (rvp && (rvp != vp)) {
4011 /* break reservation on old vp */
4012 VCancelReservation_r(rvp);
4015 #endif /* AFS_DEMAND_ATTACH_FS */
4021 /* Until we have reached an initialization level of 2
4022 * we don't know whether this volume exists or not.
4023 * We can't sleep and retry later because before a volume
4024 * is attached, the caller tries to get it first. Just
4025 * return VOFFLINE and the caller can choose whether to
4026 * retry the command or not. */
4036 IncUInt64(&VStats.hdr_gets);
4038 #ifdef AFS_DEMAND_ATTACH_FS
4039 /* block if someone else is performing an exclusive op on this volume */
4042 VCreateReservation_r(rvp);
4044 VWaitExclusiveState_r(vp);
4046 /* short circuit with VNOVOL in the following circumstances:
4049 * - VOL_STATE_SHUTTING_DOWN
4051 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4052 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
4053 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
4060 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
4061 * VNOVOL for VOL_STATE_DELETED
4063 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4064 (V_attachState(vp) == VOL_STATE_DELETED)) {
4065 if (vp->specialStatus) {
4066 *ec = vp->specialStatus;
4067 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4076 /* allowable states:
4083 if (vp->salvage.requested) {
4084 VUpdateSalvagePriority_r(vp);
4087 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4088 if (vp->specialStatus) {
4089 *ec = vp->specialStatus;
4093 avp = VAttachVolumeByVp_r(ec, vp, 0);
4096 /* VAttachVolumeByVp_r can return a pointer
4097 * != the vp passed to it under certain
4098 * conditions; make sure we don't leak
4099 * reservations if that happens */
4101 VCancelReservation_r(rvp);
4103 VCreateReservation_r(rvp);
4113 if (!vp->pending_vol_op) {
4128 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4130 /* see CheckVnode() in afsfileprocs.c for an explanation
4131 * of this error code logic */
4132 afs_uint32 now = FT_ApproxTime();
4133 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4136 *client_ec = VRESTARTING;
4144 if (VIsErrorState(V_attachState(vp))) {
4145 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4146 * it, or transition it out of that state */
4155 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
4156 * not VolOpRunningUnknown (attach2 would have converted it to Online
4160 /* only valid before/during demand attachment */
4161 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
4163 /* deny getvolume due to running mutually exclusive vol op */
4164 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
4166 * volume cannot remain online during this volume operation.
4169 if (vp->specialStatus) {
4171 * special status codes outrank normal VOFFLINE code
4173 *ec = vp->specialStatus;
4175 *client_ec = vp->specialStatus;
4179 /* see CheckVnode() in afsfileprocs.c for an explanation
4180 * of this error code logic */
4181 afs_uint32 now = FT_ApproxTime();
4182 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
4185 *client_ec = VRESTARTING;
4190 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4191 FreeVolumeHeader(vp);
4195 #endif /* AFS_DEMAND_ATTACH_FS */
4197 LoadVolumeHeader(ec, vp);
4200 /* Only log the error if it was a totally unexpected error. Simply
4201 * a missing inode is likely to be caused by the volume being deleted */
4202 if (errno != ENXIO || LogLevel)
4203 Log("Volume %u: couldn't reread volume header\n",
4205 #ifdef AFS_DEMAND_ATTACH_FS
4206 if (VCanScheduleSalvage()) {
4207 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4212 #else /* AFS_DEMAND_ATTACH_FS */
4215 #endif /* AFS_DEMAND_ATTACH_FS */
4220 if (vp->shuttingDown) {
4227 if (programType == fileServer) {
4229 if (vp->goingOffline) {
4230 if (timeout && VTimedOut(timeout)) {
4231 /* we've timed out; don't wait for the vol */
4234 #ifdef AFS_DEMAND_ATTACH_FS
4235 /* wait for the volume to go offline */
4236 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4237 VTimedWaitStateChange_r(vp, timeout, NULL);
4239 #elif defined(AFS_PTHREAD_ENV)
4240 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4241 #else /* AFS_PTHREAD_ENV */
4242 /* LWP has no timed wait, so the caller better not be
4244 osi_Assert(!timeout);
4245 LWP_WaitProcess(VPutVolume);
4246 #endif /* AFS_PTHREAD_ENV */
4250 if (vp->specialStatus) {
4252 *ec = vp->specialStatus;
4253 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4256 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4267 #ifdef AFS_DEMAND_ATTACH_FS
4268 /* if no error, bump nUsers */
4271 VLRU_UpdateAccess_r(vp);
4274 VCancelReservation_r(rvp);
4277 if (client_ec && !*client_ec) {
4280 #else /* AFS_DEMAND_ATTACH_FS */
4281 /* if no error, bump nUsers */
4288 #endif /* AFS_DEMAND_ATTACH_FS */
4291 osi_Assert(vp || *ec);
4296 /***************************************************/
4297 /* Volume offline/detach routines */
4298 /***************************************************/
4300 /* caller MUST hold a heavyweight ref on vp */
4301 #ifdef AFS_DEMAND_ATTACH_FS
4303 VTakeOffline_r(Volume * vp)
4307 osi_Assert(vp->nUsers > 0);
4308 osi_Assert(programType == fileServer);
4310 VCreateReservation_r(vp);
4311 VWaitExclusiveState_r(vp);
4313 vp->goingOffline = 1;
4314 V_needsSalvaged(vp) = 1;
4316 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4317 VCancelReservation_r(vp);
4319 #else /* AFS_DEMAND_ATTACH_FS */
4321 VTakeOffline_r(Volume * vp)
4323 osi_Assert(vp->nUsers > 0);
4324 osi_Assert(programType == fileServer);
4326 vp->goingOffline = 1;
4327 V_needsSalvaged(vp) = 1;
4329 #endif /* AFS_DEMAND_ATTACH_FS */
4332 VTakeOffline(Volume * vp)
4340 * force a volume offline.
4342 * @param[in] vp volume object pointer
4343 * @param[in] flags flags (see note below)
4345 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4346 * used when VUpdateVolume_r needs to call VForceOffline_r
4347 * (which in turn would normally call VUpdateVolume_r)
4349 * @see VUpdateVolume_r
4351 * @pre VOL_LOCK must be held.
4352 * for DAFS, caller must hold ref.
4354 * @note for DAFS, it _is safe_ to call this function from an
4357 * @post needsSalvaged flag is set.
4358 * for DAFS, salvage is requested.
4359 * no further references to the volume through the volume
4360 * package will be honored.
4361 * all file descriptor and vnode caches are invalidated.
4363 * @warning this is a heavy-handed interface. it results in
4364 * a volume going offline regardless of the current
4365 * reference count state.
4367 * @internal volume package internal use only
4370 VForceOffline_r(Volume * vp, int flags)
4374 #ifdef AFS_DEMAND_ATTACH_FS
4375 VChangeState_r(vp, VOL_STATE_ERROR);
4380 strcpy(V_offlineMessage(vp),
4381 "Forced offline due to internal error: volume needs to be salvaged");
4382 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4385 vp->goingOffline = 0;
4386 V_needsSalvaged(vp) = 1;
4387 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4388 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4391 #ifdef AFS_DEMAND_ATTACH_FS
4392 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4393 #endif /* AFS_DEMAND_ATTACH_FS */
4395 #ifdef AFS_PTHREAD_ENV
4396 CV_BROADCAST(&vol_put_volume_cond);
4397 #else /* AFS_PTHREAD_ENV */
4398 LWP_NoYieldSignal(VPutVolume);
4399 #endif /* AFS_PTHREAD_ENV */
4401 VReleaseVolumeHandles_r(vp);
4405 * force a volume offline.
4407 * @param[in] vp volume object pointer
4409 * @see VForceOffline_r
4412 VForceOffline(Volume * vp)
4415 VForceOffline_r(vp, 0);
4420 * Iterate over the RX calls associated with a volume, and interrupt them.
4422 * @param[in] vp The volume whose RX calls we want to scan
4424 * @pre VOL_LOCK held
4427 VScanCalls_r(struct Volume *vp)
4429 struct VCallByVol *cbv, *ncbv;
4431 #ifdef AFS_DEMAND_ATTACH_FS
4432 VolState state_save;
4435 if (queue_IsEmpty(&vp->rx_call_list))
4436 return; /* no calls to interrupt */
4437 if (!vol_opts.interrupt_rxcall)
4438 return; /* we have no function with which to interrupt calls */
4439 err = VIsGoingOffline_r(vp);
4441 return; /* we're not going offline anymore */
4443 #ifdef AFS_DEMAND_ATTACH_FS
4444 VWaitExclusiveState_r(vp);
4445 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4447 #endif /* AFS_DEMAND_ATTACH_FS */
4449 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4451 struct rx_peer *peer;
4453 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4455 Log("Offlining volume %lu while client %s:%u is trying to read "
4456 "from it; kicking client off with error %ld\n",
4457 (long unsigned) vp->hashid,
4458 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4459 (unsigned) ntohs(rx_PortOf(peer)),
4462 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4465 #ifdef AFS_DEMAND_ATTACH_FS
4467 VChangeState_r(vp, state_save);
4468 #endif /* AFS_DEMAND_ATTACH_FS */
4471 #ifdef AFS_DEMAND_ATTACH_FS
4473 * Wait for a vp to go offline.
4475 * @param[out] ec 1 if a salvage on the volume has been requested and
4476 * salvok == 0, 0 otherwise
4477 * @param[in] vp The volume to wait for
4478 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4479 * has been requested to salvage. Otherwise we keep waiting
4480 * until the volume has gone offline.
4482 * @pre VOL_LOCK held
4483 * @pre caller holds a lightweight ref on vp
4488 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4490 struct timespec timeout_ts;
4491 const struct timespec *ts;
4494 ts = VOfflineTimeout(&timeout_ts);
4498 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4499 if (!salvok && vp->salvage.requested) {
4503 VTimedWaitStateChange_r(vp, ts, &timedout);
4506 /* we didn't time out, so the volume must be offline, so we're done */
4510 /* If we got here, we timed out waiting for the volume to go offline.
4511 * Kick off the accessing RX calls and wait again */
4515 while (!VIsOfflineState(V_attachState(vp))) {
4516 if (!salvok && vp->salvage.requested) {
4521 VWaitStateChange_r(vp);
4525 #else /* AFS_DEMAND_ATTACH_FS */
4528 * Wait for a volume to go offline.
4530 * @pre VOL_LOCK held
4532 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4535 VWaitForOffline_r(Error *ec, VolumeId volid)
4538 const struct timespec *ts;
4539 #ifdef AFS_PTHREAD_ENV
4540 struct timespec timeout_ts;
4543 ts = VOfflineTimeout(&timeout_ts);
4545 vp = GetVolume(ec, NULL, volid, NULL, ts);
4547 /* error occurred so bad that we can't even get a vp; we have no
4548 * information on the vol so we don't know whether to wait, so just
4552 if (!VIsGoingOffline_r(vp)) {
4553 /* volume is no longer going offline, so we're done */
4558 /* If we got here, we timed out waiting for the volume to go offline.
4559 * Kick off the accessing RX calls and wait again */
4565 vp = VGetVolume_r(ec, volid);
4567 /* In case it was reattached... */
4571 #endif /* !AFS_DEMAND_ATTACH_FS */
4573 /* The opposite of VAttachVolume. The volume header is written to disk, with
4574 the inUse bit turned off. A copy of the header is maintained in memory,
4575 however (which is why this is VOffline, not VDetach).
4578 VOffline_r(Volume * vp, char *message)
4581 #ifndef AFS_DEMAND_ATTACH_FS
4582 VolumeId vid = V_id(vp);
4585 osi_Assert(programType != volumeUtility && programType != volumeServer);
4590 if (V_offlineMessage(vp)[0] == '\0')
4591 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4592 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4594 vp->goingOffline = 1;
4595 #ifdef AFS_DEMAND_ATTACH_FS
4596 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4597 VCreateReservation_r(vp);
4599 VWaitForOfflineByVp_r(&error, vp, 1);
4600 VCancelReservation_r(vp);
4601 #else /* AFS_DEMAND_ATTACH_FS */
4603 VWaitForOffline_r(&error, vid);
4604 #endif /* AFS_DEMAND_ATTACH_FS */
4607 #ifdef AFS_DEMAND_ATTACH_FS
4609 * Take a volume offline in order to perform a volume operation.
4611 * @param[inout] ec address in which to store error code
4612 * @param[in] vp volume object pointer
4613 * @param[in] message volume offline status message
4616 * - VOL_LOCK is held
4617 * - caller MUST hold a heavyweight ref on vp
4620 * - volume is taken offline
4621 * - if possible, volume operation is promoted to running state
4622 * - on failure, *ec is set to nonzero
4624 * @note Although this function does not return any value, it may
4625 * still fail to promote our pending volume operation to
4626 * a running state. Any caller MUST check the value of *ec,
4627 * and MUST NOT blindly assume success.
4629 * @warning if the caller does not hold a lightweight ref on vp,
4630 * then it MUST NOT reference vp after this function
4631 * returns to the caller.
4633 * @internal volume package internal use only
4636 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4639 osi_Assert(vp->pending_vol_op);
4645 if (V_offlineMessage(vp)[0] == '\0')
4646 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4647 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4649 vp->goingOffline = 1;
4650 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4651 VCreateReservation_r(vp);
4654 if (vp->pending_vol_op->com.programType != salvageServer) {
4655 /* do not give corrupted volumes to the volserver */
4660 VWaitForOfflineByVp_r(ec, vp, salvok);
4662 VCancelReservation_r(vp);
4664 #endif /* AFS_DEMAND_ATTACH_FS */
4667 VOffline(Volume * vp, char *message)
4670 VOffline_r(vp, message);
4674 /* This gets used for the most part by utility routines that don't want
4675 * to keep all the volume headers around. Generally, the file server won't
4676 * call this routine, because then the offline message in the volume header
4677 * (or other information) won't be available to clients. For NAMEI, also
4678 * close the file handles. However, the fileserver does call this during
4679 * an attach following a volume operation.
4682 VDetachVolume_r(Error * ec, Volume * vp)
4684 #ifdef FSSYNC_BUILD_CLIENT
4686 struct DiskPartition64 *tpartp;
4687 int notifyServer = 0;
4688 int useDone = FSYNC_VOL_ON;
4690 if (VCanUseFSSYNC()) {
4691 notifyServer = vp->needsPutBack;
4692 if (V_destroyMe(vp) == DESTROY_ME)
4693 useDone = FSYNC_VOL_LEAVE_OFF;
4694 # ifdef AFS_DEMAND_ATTACH_FS
4695 else if (!V_blessed(vp) || !V_inService(vp))
4696 useDone = FSYNC_VOL_LEAVE_OFF;
4699 # ifdef AFS_DEMAND_ATTACH_FS
4700 if (V_needsSalvaged(vp)) {
4702 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4705 tpartp = vp->partition;
4707 #endif /* FSSYNC_BUILD_CLIENT */
4709 *ec = 0; /* always "succeeds" */
4710 DeleteVolumeFromHashTable(vp);
4711 vp->shuttingDown = 1;
4712 #ifdef AFS_DEMAND_ATTACH_FS
4713 DeleteVolumeFromVByPList_r(vp);
4715 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4717 if (programType != fileServer)
4719 #endif /* AFS_DEMAND_ATTACH_FS */
4721 /* Will be detached sometime in the future--this is OK since volume is offline */
4723 /* XXX the following code should really be moved to VCheckDetach() since the volume
4724 * is not technically detached until the refcounts reach zero
4726 #ifdef FSSYNC_BUILD_CLIENT
4727 if (VCanUseFSSYNC() && notifyServer) {
4728 if (notifyServer == VOL_PUTBACK_DELETE) {
4729 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4730 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4731 * to signify a deleted volume. */
4732 useDone = FSYNC_VOL_DONE;
4735 * Note: The server is not notified in the case of a bogus volume
4736 * explicitly to make it possible to create a volume, do a partial
4737 * restore, then abort the operation without ever putting the volume
4738 * online. This is essential in the case of a volume move operation
4739 * between two partitions on the same server. In that case, there
4740 * would be two instances of the same volume, one of them bogus,
4741 * which the file server would attempt to put on line
4743 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4744 /* XXX this code path is only hit by volume utilities, thus
4745 * V_BreakVolumeCallbacks will always be NULL. if we really
4746 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4748 /* Dettaching it so break all callbacks on it */
4749 if (V_BreakVolumeCallbacks) {
4750 Log("volume %u detached; breaking all call backs\n", volume);
4751 (*V_BreakVolumeCallbacks) (volume);
4755 #endif /* FSSYNC_BUILD_CLIENT */
4759 VDetachVolume(Error * ec, Volume * vp)
4762 VDetachVolume_r(ec, vp);
4767 /***************************************************/
4768 /* Volume fd/inode handle closing routines */
4769 /***************************************************/
4771 /* For VDetachVolume, we close all cached file descriptors, but keep
4772 * the Inode handles in case we need to read from a busy volume.
4774 /* for demand attach, caller MUST hold ref count on vp */
4776 VCloseVolumeHandles_r(Volume * vp)
4778 #ifdef AFS_DEMAND_ATTACH_FS
4779 VolState state_save;
4781 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4786 DFlushVolume(vp->hashid);
4788 #ifdef AFS_DEMAND_ATTACH_FS
4792 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4793 VCloseVnodeFiles_r(vp);
4795 #ifdef AFS_DEMAND_ATTACH_FS
4799 /* Too time consuming and unnecessary for the volserver */
4800 if (programType == fileServer) {
4801 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4802 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4803 IH_CONDSYNC(vp->diskDataHandle);
4805 IH_CONDSYNC(vp->linkHandle);
4806 #endif /* AFS_NT40_ENV */
4809 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4810 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4811 IH_REALLYCLOSE(vp->diskDataHandle);
4812 IH_REALLYCLOSE(vp->linkHandle);
4814 #ifdef AFS_DEMAND_ATTACH_FS
4815 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4820 VChangeState_r(vp, state_save);
4824 /* For both VForceOffline and VOffline, we close all relevant handles.
4825 * For VOffline, if we re-attach the volume, the files may possible be
4826 * different than before.
4828 /* for demand attach, caller MUST hold a ref count on vp */
4830 VReleaseVolumeHandles_r(Volume * vp)
4832 #ifdef AFS_DEMAND_ATTACH_FS
4833 VolState state_save;
4835 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4840 DFlushVolume(vp->hashid);
4842 #ifdef AFS_DEMAND_ATTACH_FS
4846 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4848 #ifdef AFS_DEMAND_ATTACH_FS
4852 /* Too time consuming and unnecessary for the volserver */
4853 if (programType == fileServer) {
4854 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4855 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4856 IH_CONDSYNC(vp->diskDataHandle);
4858 IH_CONDSYNC(vp->linkHandle);
4859 #endif /* AFS_NT40_ENV */
4862 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4863 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4864 IH_RELEASE(vp->diskDataHandle);
4865 IH_RELEASE(vp->linkHandle);
4867 #ifdef AFS_DEMAND_ATTACH_FS
4868 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4873 VChangeState_r(vp, state_save);
4878 /***************************************************/
4879 /* Volume write and fsync routines */
4880 /***************************************************/
4883 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4885 #ifdef AFS_DEMAND_ATTACH_FS
4886 VolState state_save;
4888 if (flags & VOL_UPDATE_WAIT) {
4889 VCreateReservation_r(vp);
4890 VWaitExclusiveState_r(vp);
4895 if (programType == fileServer)
4897 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4898 200 : V_nextVnodeUnique(vp));
4900 #ifdef AFS_DEMAND_ATTACH_FS
4901 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4905 WriteVolumeHeader_r(ec, vp);
4907 #ifdef AFS_DEMAND_ATTACH_FS
4909 VChangeState_r(vp, state_save);
4910 if (flags & VOL_UPDATE_WAIT) {
4911 VCancelReservation_r(vp);
4916 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4917 V_id(vp), V_name(vp));
4918 /* try to update on-disk header,
4919 * while preventing infinite recursion */
4920 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4921 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4927 VUpdateVolume(Error * ec, Volume * vp)
4930 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4935 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4939 #ifdef AFS_DEMAND_ATTACH_FS
4940 VolState state_save;
4943 if (flags & VOL_SYNC_WAIT) {
4944 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4946 VUpdateVolume_r(ec, vp, 0);
4949 #ifdef AFS_DEMAND_ATTACH_FS
4950 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4953 fdP = IH_OPEN(V_diskDataHandle(vp));
4954 osi_Assert(fdP != NULL);
4955 code = FDH_SYNC(fdP);
4956 osi_Assert(code == 0);
4958 #ifdef AFS_DEMAND_ATTACH_FS
4960 VChangeState_r(vp, state_save);
4966 VSyncVolume(Error * ec, Volume * vp)
4969 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4974 /***************************************************/
4975 /* Volume dealloaction routines */
4976 /***************************************************/
4978 #ifdef AFS_DEMAND_ATTACH_FS
4980 FreeVolume(Volume * vp)
4982 /* free the heap space, iff it's safe.
4983 * otherwise, pull it out of the hash table, so it
4984 * will get deallocated when all refs to it go away */
4985 if (!VCheckFree(vp)) {
4986 DeleteVolumeFromHashTable(vp);
4987 DeleteVolumeFromVByPList_r(vp);
4989 /* make sure we invalidate the header cache entry */
4990 FreeVolumeHeader(vp);
4993 #endif /* AFS_DEMAND_ATTACH_FS */
4996 ReallyFreeVolume(Volume * vp)
5001 #ifdef AFS_DEMAND_ATTACH_FS
5003 VChangeState_r(vp, VOL_STATE_FREED);
5004 if (vp->pending_vol_op)
5005 free(vp->pending_vol_op);
5006 #endif /* AFS_DEMAND_ATTACH_FS */
5007 for (i = 0; i < nVNODECLASSES; i++)
5008 if (vp->vnodeIndex[i].bitmap)
5009 free(vp->vnodeIndex[i].bitmap);
5010 FreeVolumeHeader(vp);
5011 #ifndef AFS_DEMAND_ATTACH_FS
5012 DeleteVolumeFromHashTable(vp);
5013 #endif /* AFS_DEMAND_ATTACH_FS */
5017 /* check to see if we should shutdown this volume
5018 * returns 1 if volume was freed, 0 otherwise */
5019 #ifdef AFS_DEMAND_ATTACH_FS
5021 VCheckDetach(Volume * vp)
5026 if (vp->nUsers || vp->nWaiters)
5029 if (vp->shuttingDown) {
5031 if ((programType != fileServer) &&
5032 (V_inUse(vp) == programType) &&
5033 ((V_checkoutMode(vp) == V_VOLUPD) ||
5034 (V_checkoutMode(vp) == V_SECRETLY) ||
5035 ((V_checkoutMode(vp) == V_CLONE) &&
5036 (VolumeWriteable(vp))))) {
5038 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5040 Log("VCheckDetach: volume header update for volume %u "
5041 "failed with errno %d\n", vp->hashid, errno);
5044 VReleaseVolumeHandles_r(vp);
5046 ReallyFreeVolume(vp);
5047 if (programType == fileServer) {
5048 CV_BROADCAST(&vol_put_volume_cond);
5053 #else /* AFS_DEMAND_ATTACH_FS */
5055 VCheckDetach(Volume * vp)
5063 if (vp->shuttingDown) {
5065 if ((programType != fileServer) &&
5066 (V_inUse(vp) == programType) &&
5067 ((V_checkoutMode(vp) == V_VOLUPD) ||
5068 (V_checkoutMode(vp) == V_SECRETLY) ||
5069 ((V_checkoutMode(vp) == V_CLONE) &&
5070 (VolumeWriteable(vp))))) {
5072 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5074 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5078 VReleaseVolumeHandles_r(vp);
5079 ReallyFreeVolume(vp);
5080 if (programType == fileServer) {
5081 #if defined(AFS_PTHREAD_ENV)
5082 CV_BROADCAST(&vol_put_volume_cond);
5083 #else /* AFS_PTHREAD_ENV */
5084 LWP_NoYieldSignal(VPutVolume);
5085 #endif /* AFS_PTHREAD_ENV */
5090 #endif /* AFS_DEMAND_ATTACH_FS */
5092 /* check to see if we should offline this volume
5093 * return 1 if volume went offline, 0 otherwise */
5094 #ifdef AFS_DEMAND_ATTACH_FS
5096 VCheckOffline(Volume * vp)
5100 if (vp->goingOffline && !vp->nUsers) {
5102 osi_Assert(programType == fileServer);
5103 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5104 (V_attachState(vp) != VOL_STATE_FREED) &&
5105 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5106 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5107 (V_attachState(vp) != VOL_STATE_DELETED));
5111 * VOL_STATE_GOING_OFFLINE
5112 * VOL_STATE_SHUTTING_DOWN
5113 * VIsErrorState(V_attachState(vp))
5114 * VIsExclusiveState(V_attachState(vp))
5117 VCreateReservation_r(vp);
5118 VChangeState_r(vp, VOL_STATE_OFFLINING);
5121 /* must clear the goingOffline flag before we drop the glock */
5122 vp->goingOffline = 0;
5127 /* perform async operations */
5128 VUpdateVolume_r(&error, vp, 0);
5129 VCloseVolumeHandles_r(vp);
5132 if (V_offlineMessage(vp)[0]) {
5133 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5134 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5135 V_offlineMessage(vp));
5137 Log("VOffline: Volume %lu (%s) is now offline\n",
5138 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5142 /* invalidate the volume header cache entry */
5143 FreeVolumeHeader(vp);
5145 /* if nothing changed state to error or salvaging,
5146 * drop state to unattached */
5147 if (!VIsErrorState(V_attachState(vp))) {
5148 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5150 VCancelReservation_r(vp);
5151 /* no usage of vp is safe beyond this point */
5155 #else /* AFS_DEMAND_ATTACH_FS */
5157 VCheckOffline(Volume * vp)
5161 if (vp->goingOffline && !vp->nUsers) {
5163 osi_Assert(programType == fileServer);
5166 vp->goingOffline = 0;
5168 VUpdateVolume_r(&error, vp, 0);
5169 VCloseVolumeHandles_r(vp);
5171 if (V_offlineMessage(vp)[0]) {
5172 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5173 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5174 V_offlineMessage(vp));
5176 Log("VOffline: Volume %lu (%s) is now offline\n",
5177 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5180 FreeVolumeHeader(vp);
5181 #ifdef AFS_PTHREAD_ENV
5182 CV_BROADCAST(&vol_put_volume_cond);
5183 #else /* AFS_PTHREAD_ENV */
5184 LWP_NoYieldSignal(VPutVolume);
5185 #endif /* AFS_PTHREAD_ENV */
5189 #endif /* AFS_DEMAND_ATTACH_FS */
5191 /***************************************************/
5192 /* demand attach fs ref counting routines */
5193 /***************************************************/
5195 #ifdef AFS_DEMAND_ATTACH_FS
5196 /* the following two functions handle reference counting for
5197 * asynchronous operations on volume structs.
5199 * their purpose is to prevent a VDetachVolume or VShutdown
5200 * from free()ing the Volume struct during an async i/o op */
5202 /* register with the async volume op ref counter */
5203 /* VCreateReservation_r moved into inline code header because it
5204 * is now needed in vnode.c -- tkeiser 11/20/2007
5208 * decrement volume-package internal refcount.
5210 * @param vp volume object pointer
5212 * @internal volume package internal use only
5215 * @arg VOL_LOCK is held
5216 * @arg lightweight refcount held
5218 * @post volume waiters refcount is decremented; volume may
5219 * have been deallocated/shutdown/offlined/salvaged/
5220 * whatever during the process
5222 * @warning once you have tossed your last reference (you can acquire
5223 * lightweight refs recursively) it is NOT SAFE to reference
5224 * a volume object pointer ever again
5226 * @see VCreateReservation_r
5228 * @note DEMAND_ATTACH_FS only
5231 VCancelReservation_r(Volume * vp)
5233 osi_Assert(--vp->nWaiters >= 0);
5234 if (vp->nWaiters == 0) {
5236 if (!VCheckDetach(vp)) {
5243 /* check to see if we should free this volume now
5244 * return 1 if volume was freed, 0 otherwise */
5246 VCheckFree(Volume * vp)
5249 if ((vp->nUsers == 0) &&
5250 (vp->nWaiters == 0) &&
5251 !(V_attachFlags(vp) & (VOL_IN_HASH |
5255 ReallyFreeVolume(vp);
5260 #endif /* AFS_DEMAND_ATTACH_FS */
5263 /***************************************************/
5264 /* online volume operations routines */
5265 /***************************************************/
5267 #ifdef AFS_DEMAND_ATTACH_FS
5269 * register a volume operation on a given volume.
5271 * @param[in] vp volume object
5272 * @param[in] vopinfo volume operation info object
5274 * @pre VOL_LOCK is held
5276 * @post volume operation info object attached to volume object.
5277 * volume operation statistics updated.
5279 * @note by "attached" we mean a copy of the passed in object is made
5281 * @internal volume package internal use only
5284 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5286 FSSYNC_VolOp_info * info;
5288 /* attach a vol op info node to the volume struct */
5289 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5290 osi_Assert(info != NULL);
5291 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5292 vp->pending_vol_op = info;
5295 vp->stats.last_vol_op = FT_ApproxTime();
5296 vp->stats.vol_ops++;
5297 IncUInt64(&VStats.vol_ops);
5303 * deregister the volume operation attached to this volume.
5305 * @param[in] vp volume object pointer
5307 * @pre VOL_LOCK is held
5309 * @post the volume operation info object is detached from the volume object
5311 * @internal volume package internal use only
5314 VDeregisterVolOp_r(Volume * vp)
5316 if (vp->pending_vol_op) {
5317 free(vp->pending_vol_op);
5318 vp->pending_vol_op = NULL;
5322 #endif /* AFS_DEMAND_ATTACH_FS */
5325 * determine whether it is safe to leave a volume online during
5326 * the volume operation described by the vopinfo object.
5328 * @param[in] vp volume object
5329 * @param[in] vopinfo volume operation info object
5331 * @return whether it is safe to leave volume online
5332 * @retval 0 it is NOT SAFE to leave the volume online
5333 * @retval 1 it is safe to leave the volume online during the operation
5336 * @arg VOL_LOCK is held
5337 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5338 * this condition is met)
5340 * @internal volume package internal use only
5343 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5345 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5346 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5347 (vopinfo->com.reason == V_READONLY ||
5348 (!VolumeWriteable(vp) &&
5349 (vopinfo->com.reason == V_CLONE ||
5350 vopinfo->com.reason == V_DUMP)))));
5354 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5357 * @param[in] vp volume object
5358 * @param[in] vopinfo volume operation info object
5360 * @return whether it is safe to leave volume online
5361 * @retval 0 it is NOT SAFE to leave the volume online
5362 * @retval 1 it is safe to leave the volume online during the operation
5363 * @retval -1 unsure; volume header is required in order to know whether or
5364 * not is is safe to leave the volume online
5366 * @pre VOL_LOCK is held
5368 * @internal volume package internal use only
5371 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5373 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5374 * assume that we don't know VolumeWriteable; return -1 if the answer
5375 * depends on VolumeWriteable */
5377 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5380 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5381 vopinfo->com.reason == V_READONLY) {
5385 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5386 (vopinfo->com.reason == V_CLONE ||
5387 vopinfo->com.reason == V_DUMP)) {
5389 /* must know VolumeWriteable */
5396 * determine whether VBUSY should be set during this volume operation.
5398 * @param[in] vp volume object
5399 * @param[in] vopinfo volume operation info object
5401 * @return whether VBUSY should be set
5402 * @retval 0 VBUSY does NOT need to be set
5403 * @retval 1 VBUSY SHOULD be set
5405 * @pre VOL_LOCK is held
5407 * @internal volume package internal use only
5410 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5412 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5413 vopinfo->com.reason == FSYNC_SALVAGE) ||
5414 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5415 (vopinfo->com.reason == V_CLONE ||
5416 vopinfo->com.reason == V_DUMP)));
5420 /***************************************************/
5421 /* online salvager routines */
5422 /***************************************************/
5423 #if defined(AFS_DEMAND_ATTACH_FS)
5426 * offline a volume to let it be salvaged.
5428 * @param[in] vp Volume to offline
5430 * @return whether we offlined the volume successfully
5431 * @retval 0 volume was not offlined
5432 * @retval 1 volume is now offline
5434 * @note This is similar to VCheckOffline, but slightly different. We do not
5435 * deal with vp->goingOffline, and we try to avoid touching the volume
5436 * header except just to set needsSalvaged
5438 * @pre VOL_LOCK held
5439 * @pre vp->nUsers == 0
5440 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5443 VOfflineForSalvage_r(struct Volume *vp)
5447 VCreateReservation_r(vp);
5448 VWaitExclusiveState_r(vp);
5450 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5451 /* Someone's using the volume, or someone got to scheduling the salvage
5452 * before us. I don't think either of these should be possible, as we
5453 * should gain no new heavyweight references while we're trying to
5454 * salvage, but just to be sure... */
5455 VCancelReservation_r(vp);
5459 VChangeState_r(vp, VOL_STATE_OFFLINING);
5463 V_needsSalvaged(vp) = 1;
5464 /* ignore error; updating needsSalvaged is just best effort */
5465 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5467 VCloseVolumeHandles_r(vp);
5469 FreeVolumeHeader(vp);
5471 /* volume has been effectively offlined; we can mark it in the SALVAGING
5472 * state now, which lets FSSYNC give it away */
5473 VChangeState_r(vp, VOL_STATE_SALVAGING);
5475 VCancelReservation_r(vp);
5481 * check whether a salvage needs to be performed on this volume.
5483 * @param[in] vp pointer to volume object
5485 * @return status code
5486 * @retval 0 no salvage scheduled
5487 * @retval 1 a salvage has been scheduled with the salvageserver
5489 * @pre VOL_LOCK is held
5491 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5492 * then a salvage will be requested
5494 * @note this is one of the event handlers called by VCancelReservation_r
5496 * @note the caller must check if the volume needs to be freed after calling
5497 * this; the volume may not have any references or be on any lists after
5498 * we return, and we do not free it
5500 * @see VCancelReservation_r
5502 * @internal volume package internal use only.
5505 VCheckSalvage(Volume * vp)
5508 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5511 if (!vp->salvage.requested) {
5515 /* prevent recursion; some of the code below creates and removes
5516 * lightweight refs, which can call VCheckSalvage */
5517 if (vp->salvage.scheduling) {
5520 vp->salvage.scheduling = 1;
5522 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5523 if (!VOfflineForSalvage_r(vp)) {
5524 vp->salvage.scheduling = 0;
5529 if (vp->salvage.requested) {
5530 VScheduleSalvage_r(vp);
5533 vp->salvage.scheduling = 0;
5534 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5539 * request volume salvage.
5541 * @param[out] ec computed client error code
5542 * @param[in] vp volume object pointer
5543 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5544 * @param[in] flags see flags note below
5547 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5548 * not been fully attached
5550 * @pre VOL_LOCK is held.
5552 * @post volume state is changed.
5553 * for fileserver, salvage will be requested once refcount reaches zero.
5555 * @return operation status code
5556 * @retval 0 volume salvage will occur
5557 * @retval 1 volume salvage could not be scheduled
5561 * @note in the fileserver, this call does not synchronously schedule a volume
5562 * salvage. rather, it sets volume state so that when volume refcounts
5563 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5564 * nUsers and nWaiters must be zero.
5566 * @internal volume package internal use only.
5569 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5573 * for DAFS volume utilities that are not supposed to schedule salvages,
5574 * just transition to error state instead
5576 if (!VCanScheduleSalvage()) {
5577 VChangeState_r(vp, VOL_STATE_ERROR);
5582 if (programType != fileServer && !VCanUseFSSYNC()) {
5583 VChangeState_r(vp, VOL_STATE_ERROR);
5588 if (!vp->salvage.requested) {
5589 vp->salvage.requested = 1;
5590 vp->salvage.reason = reason;
5591 vp->stats.last_salvage = FT_ApproxTime();
5593 /* Note that it is not possible for us to reach this point if a
5594 * salvage is already running on this volume (even if the fileserver
5595 * was restarted during the salvage). If a salvage were running, the
5596 * salvager would have write-locked the volume header file, so when
5597 * we tried to lock the volume header, the lock would have failed,
5598 * and we would have failed during attachment prior to calling
5599 * VRequestSalvage. So we know that we can schedule salvages without
5600 * fear of a salvage already running for this volume. */
5602 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5604 /* if we don't need to offline the volume, we can go directly
5605 * to SALVAGING. SALVAGING says the volume is offline and is
5606 * either salvaging or ready to be handed to the salvager.
5607 * SALVAGE_REQ says that we want to salvage the volume, but we
5608 * are waiting for it to go offline first. */
5609 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5610 VChangeState_r(vp, VOL_STATE_SALVAGING);
5612 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5613 if (vp->nUsers == 0) {
5614 /* normally VOfflineForSalvage_r would be called from
5615 * PutVolume et al when nUsers reaches 0, but if
5616 * it's already 0, just do it ourselves, since PutVolume
5617 * isn't going to get called */
5618 VOfflineForSalvage_r(vp);
5621 /* If we are non-fileserver, we're telling the fileserver to
5622 * salvage the vol, so we don't need to give it back separately. */
5623 vp->needsPutBack = 0;
5627 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5629 /* make sure neither VScheduleSalvage_r nor
5630 * VUpdateSalvagePriority_r try to schedule another salvage */
5631 vp->salvage.requested = vp->salvage.scheduled = 0;
5633 VChangeState_r(vp, VOL_STATE_ERROR);
5642 * update salvageserver scheduling priority for a volume.
5644 * @param[in] vp pointer to volume object
5646 * @return operation status
5648 * @retval 1 request denied, or SALVSYNC communications failure
5650 * @pre VOL_LOCK is held.
5652 * @post in-core salvage priority counter is incremented. if at least
5653 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5654 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5655 * to update its priority queue. if no salvage is scheduled,
5656 * this function is a no-op.
5658 * @note DAFS fileserver only
5660 * @note this should be called whenever a VGetVolume fails due to a
5661 * pending salvage request
5663 * @todo should set exclusive state and drop glock around salvsync call
5665 * @internal volume package internal use only.
5668 VUpdateSalvagePriority_r(Volume * vp)
5672 #ifdef SALVSYNC_BUILD_CLIENT
5677 now = FT_ApproxTime();
5679 /* update the salvageserver priority queue occasionally so that
5680 * frequently requested volumes get moved to the head of the queue
5682 if ((vp->salvage.scheduled) &&
5683 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5684 code = SALVSYNC_SalvageVolume(vp->hashid,
5685 VPartitionPath(vp->partition),
5690 vp->stats.last_salvage_req = now;
5691 if (code != SYNC_OK) {
5695 #endif /* SALVSYNC_BUILD_CLIENT */
5700 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5702 /* A couple of little helper functions. These return true if we tried to
5703 * use this mechanism to schedule a salvage, false if we haven't tried.
5704 * If we did try a salvage then the results are contained in code.
5708 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5709 #ifdef SALVSYNC_BUILD_CLIENT
5710 if (VCanUseSALVSYNC()) {
5711 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5712 afs_printable_uint32_lu(vp->hashid), partName);
5714 /* can't use V_id() since there's no guarantee
5715 * we have the disk data header at this point */
5716 *code = SALVSYNC_SalvageVolume(vp->hashid,
5729 try_FSSYNC(Volume *vp, char *partName, int *code) {
5730 #ifdef FSSYNC_BUILD_CLIENT
5731 if (VCanUseFSSYNC()) {
5732 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5733 afs_printable_uint32_lu(vp->hashid), partName);
5736 * If we aren't the fileserver, tell the fileserver the volume
5737 * needs to be salvaged. We could directly tell the
5738 * salvageserver, but the fileserver keeps track of some stats
5739 * related to salvages, and handles some other salvage-related
5740 * complications for us.
5742 *code = FSYNC_VolOp(vp->hashid, partName,
5743 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5746 #endif /* FSSYNC_BUILD_CLIENT */
5751 * schedule a salvage with the salvage server or fileserver.
5753 * @param[in] vp pointer to volume object
5755 * @return operation status
5756 * @retval 0 salvage scheduled successfully
5757 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5760 * @arg VOL_LOCK is held.
5761 * @arg nUsers and nWaiters should be zero.
5763 * @post salvageserver or fileserver is sent a salvage request
5765 * @note If we are the fileserver, the request will be sent to the salvage
5766 * server over SALVSYNC. If we are not the fileserver, the request will be
5767 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5769 * @note the caller must check if the volume needs to be freed after calling
5770 * this; the volume may not have any references or be on any lists after
5771 * we return, and we do not free it
5775 * @internal volume package internal use only.
5778 VScheduleSalvage_r(Volume * vp)
5782 VolState state_save;
5783 VThreadOptions_t * thread_opts;
5786 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5788 if (vp->nWaiters || vp->nUsers) {
5792 /* prevent endless salvage,attach,salvage,attach,... loops */
5793 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5797 * don't perform salvsync ops on certain threads
5799 thread_opts = pthread_getspecific(VThread_key);
5800 if (thread_opts == NULL) {
5801 thread_opts = &VThread_defaults;
5803 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5807 if (vp->salvage.scheduled) {
5811 VCreateReservation_r(vp);
5812 VWaitExclusiveState_r(vp);
5815 * XXX the scheduling process should really be done asynchronously
5816 * to avoid fssync deadlocks
5818 if (!vp->salvage.scheduled) {
5819 /* if we haven't previously scheduled a salvage, do so now
5821 * set the volume to an exclusive state and drop the lock
5822 * around the SALVSYNC call
5824 strlcpy(partName, vp->partition->name, sizeof(partName));
5825 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5828 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5829 try_FSSYNC(vp, partName, &code));
5832 VChangeState_r(vp, state_save);
5834 if (code == SYNC_OK) {
5835 vp->salvage.scheduled = 1;
5836 vp->stats.last_salvage_req = FT_ApproxTime();
5837 if (VCanUseSALVSYNC()) {
5838 /* don't record these stats for non-fileservers; let the
5839 * fileserver take care of these */
5840 vp->stats.salvages++;
5841 IncUInt64(&VStats.salvages);
5846 case SYNC_BAD_COMMAND:
5847 case SYNC_COM_ERROR:
5850 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5851 "denied\n", afs_printable_uint32_lu(vp->hashid));
5854 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5855 "failed\n", afs_printable_uint32_lu(vp->hashid));
5858 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5859 "received unknown protocol error %d\n",
5860 afs_printable_uint32_lu(vp->hashid), code);
5864 if (VCanUseFSSYNC()) {
5865 VChangeState_r(vp, VOL_STATE_ERROR);
5870 /* NB: this is cancelling the reservation we obtained above, but we do
5871 * not call VCancelReservation_r, since that may trigger the vp dtor,
5872 * possibly free'ing the vp. We need to keep the vp around after
5873 * this, as the caller may reference vp without any refs. Instead, it
5874 * is the duty of the caller to inspect 'vp' after we return to see if
5875 * needs to be freed. */
5876 osi_Assert(--vp->nWaiters >= 0);
5879 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5881 #ifdef SALVSYNC_BUILD_CLIENT
5884 * connect to the salvageserver SYNC service.
5886 * @return operation status
5890 * @post connection to salvageserver SYNC service established
5892 * @see VConnectSALV_r
5893 * @see VDisconnectSALV
5894 * @see VReconnectSALV
5901 retVal = VConnectSALV_r();
5907 * connect to the salvageserver SYNC service.
5909 * @return operation status
5913 * @pre VOL_LOCK is held.
5915 * @post connection to salvageserver SYNC service established
5918 * @see VDisconnectSALV_r
5919 * @see VReconnectSALV_r
5920 * @see SALVSYNC_clientInit
5922 * @internal volume package internal use only.
5925 VConnectSALV_r(void)
5927 return SALVSYNC_clientInit();
5931 * disconnect from the salvageserver SYNC service.
5933 * @return operation status
5936 * @pre client should have a live connection to the salvageserver
5938 * @post connection to salvageserver SYNC service destroyed
5940 * @see VDisconnectSALV_r
5942 * @see VReconnectSALV
5945 VDisconnectSALV(void)
5948 VDisconnectSALV_r();
5954 * disconnect from the salvageserver SYNC service.
5956 * @return operation status
5960 * @arg VOL_LOCK is held.
5961 * @arg client should have a live connection to the salvageserver.
5963 * @post connection to salvageserver SYNC service destroyed
5965 * @see VDisconnectSALV
5966 * @see VConnectSALV_r
5967 * @see VReconnectSALV_r
5968 * @see SALVSYNC_clientFinis
5970 * @internal volume package internal use only.
5973 VDisconnectSALV_r(void)
5975 return SALVSYNC_clientFinis();
5979 * disconnect and then re-connect to the salvageserver SYNC service.
5981 * @return operation status
5985 * @pre client should have a live connection to the salvageserver
5987 * @post old connection is dropped, and a new one is established
5990 * @see VDisconnectSALV
5991 * @see VReconnectSALV_r
5994 VReconnectSALV(void)
5998 retVal = VReconnectSALV_r();
6004 * disconnect and then re-connect to the salvageserver SYNC service.
6006 * @return operation status
6011 * @arg VOL_LOCK is held.
6012 * @arg client should have a live connection to the salvageserver.
6014 * @post old connection is dropped, and a new one is established
6016 * @see VConnectSALV_r
6017 * @see VDisconnectSALV
6018 * @see VReconnectSALV
6019 * @see SALVSYNC_clientReconnect
6021 * @internal volume package internal use only.
6024 VReconnectSALV_r(void)
6026 return SALVSYNC_clientReconnect();
6028 #endif /* SALVSYNC_BUILD_CLIENT */
6029 #endif /* AFS_DEMAND_ATTACH_FS */
6032 /***************************************************/
6033 /* FSSYNC routines */
6034 /***************************************************/
6036 /* This must be called by any volume utility which needs to run while the
6037 file server is also running. This is separated from VInitVolumePackage2 so
6038 that a utility can fork--and each of the children can independently
6039 initialize communication with the file server */
6040 #ifdef FSSYNC_BUILD_CLIENT
6042 * connect to the fileserver SYNC service.
6044 * @return operation status
6049 * @arg VInit must equal 2.
6050 * @arg Program Type must not be fileserver or salvager.
6052 * @post connection to fileserver SYNC service established
6055 * @see VDisconnectFS
6056 * @see VChildProcReconnectFS
6063 retVal = VConnectFS_r();
6069 * connect to the fileserver SYNC service.
6071 * @return operation status
6076 * @arg VInit must equal 2.
6077 * @arg Program Type must not be fileserver or salvager.
6078 * @arg VOL_LOCK is held.
6080 * @post connection to fileserver SYNC service established
6083 * @see VDisconnectFS_r
6084 * @see VChildProcReconnectFS_r
6086 * @internal volume package internal use only.
6092 osi_Assert((VInit == 2) &&
6093 (programType != fileServer) &&
6094 (programType != salvager));
6095 rc = FSYNC_clientInit();
6103 * disconnect from the fileserver SYNC service.
6106 * @arg client should have a live connection to the fileserver.
6107 * @arg VOL_LOCK is held.
6108 * @arg Program Type must not be fileserver or salvager.
6110 * @post connection to fileserver SYNC service destroyed
6112 * @see VDisconnectFS
6114 * @see VChildProcReconnectFS_r
6116 * @internal volume package internal use only.
6119 VDisconnectFS_r(void)
6121 osi_Assert((programType != fileServer) &&
6122 (programType != salvager));
6123 FSYNC_clientFinis();
6128 * disconnect from the fileserver SYNC service.
6131 * @arg client should have a live connection to the fileserver.
6132 * @arg Program Type must not be fileserver or salvager.
6134 * @post connection to fileserver SYNC service destroyed
6136 * @see VDisconnectFS_r
6138 * @see VChildProcReconnectFS
6149 * connect to the fileserver SYNC service from a child process following a fork.
6151 * @return operation status
6156 * @arg VOL_LOCK is held.
6157 * @arg current FSYNC handle is shared with a parent process
6159 * @post current FSYNC handle is discarded and a new connection to the
6160 * fileserver SYNC service is established
6162 * @see VChildProcReconnectFS
6164 * @see VDisconnectFS_r
6166 * @internal volume package internal use only.
6169 VChildProcReconnectFS_r(void)
6171 return FSYNC_clientChildProcReconnect();
6175 * connect to the fileserver SYNC service from a child process following a fork.
6177 * @return operation status
6181 * @pre current FSYNC handle is shared with a parent process
6183 * @post current FSYNC handle is discarded and a new connection to the
6184 * fileserver SYNC service is established
6186 * @see VChildProcReconnectFS_r
6188 * @see VDisconnectFS
6191 VChildProcReconnectFS(void)
6195 ret = VChildProcReconnectFS_r();
6199 #endif /* FSSYNC_BUILD_CLIENT */
6202 /***************************************************/
6203 /* volume bitmap routines */
6204 /***************************************************/
6207 * allocate a vnode bitmap number for the vnode
6209 * @param[out] ec error code
6210 * @param[in] vp volume object pointer
6211 * @param[in] index vnode index number for the vnode
6212 * @param[in] flags flag values described in note
6214 * @note for DAFS, flags parameter controls locking behavior.
6215 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6216 * will create a reservation and block on any other exclusive
6217 * operations. Otherwise, this function assumes the caller
6218 * already has exclusive access to vp, and we just change the
6221 * @pre VOL_LOCK held
6223 * @return bit number allocated
6229 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6230 struct vnodeIndex *index, int flags)
6234 #ifdef AFS_DEMAND_ATTACH_FS
6235 VolState state_save;
6236 #endif /* AFS_DEMAND_ATTACH_FS */
6240 /* This test is probably redundant */
6241 if (!VolumeWriteable(vp)) {
6242 *ec = (bit32) VREADONLY;
6246 #ifdef AFS_DEMAND_ATTACH_FS
6247 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6248 VCreateReservation_r(vp);
6249 VWaitExclusiveState_r(vp);
6251 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6252 #endif /* AFS_DEMAND_ATTACH_FS */
6255 if ((programType == fileServer) && !index->bitmap) {
6257 #ifndef AFS_DEMAND_ATTACH_FS
6258 /* demand attach fs uses the volume state to avoid races.
6259 * specialStatus field is not used at all */
6261 if (vp->specialStatus == VBUSY) {
6262 if (vp->goingOffline) { /* vos dump waiting for the volume to
6263 * go offline. We probably come here
6264 * from AddNewReadableResidency */
6267 while (vp->specialStatus == VBUSY) {
6268 #ifdef AFS_PTHREAD_ENV
6272 #else /* !AFS_PTHREAD_ENV */
6274 #endif /* !AFS_PTHREAD_ENV */
6278 #endif /* !AFS_DEMAND_ATTACH_FS */
6280 if (!index->bitmap) {
6281 #ifndef AFS_DEMAND_ATTACH_FS
6282 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6283 #endif /* AFS_DEMAND_ATTACH_FS */
6284 for (i = 0; i < nVNODECLASSES; i++) {
6285 VGetBitmap_r(ec, vp, i);
6287 #ifdef AFS_DEMAND_ATTACH_FS
6288 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6289 #else /* AFS_DEMAND_ATTACH_FS */
6290 DeleteVolumeFromHashTable(vp);
6291 vp->shuttingDown = 1; /* Let who has it free it. */
6292 vp->specialStatus = 0;
6293 #endif /* AFS_DEMAND_ATTACH_FS */
6297 #ifndef AFS_DEMAND_ATTACH_FS
6299 vp->specialStatus = 0; /* Allow others to have access. */
6300 #endif /* AFS_DEMAND_ATTACH_FS */
6303 #endif /* BITMAP_LATER */
6305 #ifdef AFS_DEMAND_ATTACH_FS
6307 #endif /* AFS_DEMAND_ATTACH_FS */
6308 bp = index->bitmap + index->bitmapOffset;
6309 ep = index->bitmap + index->bitmapSize;
6311 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6313 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6316 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6318 ret = ((bp - index->bitmap) * 8 + o);
6319 #ifdef AFS_DEMAND_ATTACH_FS
6321 #endif /* AFS_DEMAND_ATTACH_FS */
6324 bp += sizeof(bit32) /* i.e. 4 */ ;
6326 /* No bit map entry--must grow bitmap */
6328 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6329 osi_Assert(bp != NULL);
6331 bp += index->bitmapSize;
6332 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6333 index->bitmapOffset = index->bitmapSize;
6334 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6336 ret = index->bitmapOffset * 8;
6337 #ifdef AFS_DEMAND_ATTACH_FS
6339 #endif /* AFS_DEMAND_ATTACH_FS */
6342 #ifdef AFS_DEMAND_ATTACH_FS
6343 VChangeState_r(vp, state_save);
6344 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6345 VCancelReservation_r(vp);
6347 #endif /* AFS_DEMAND_ATTACH_FS */
6352 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6356 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6362 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6363 unsigned bitNumber, int flags)
6365 unsigned int offset;
6369 #ifdef AFS_DEMAND_ATTACH_FS
6370 if (flags & VOL_FREE_BITMAP_WAIT) {
6371 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6372 * state, so ensure we're not in an exclusive volume state when we update
6374 VCreateReservation_r(vp);
6375 VWaitExclusiveState_r(vp);
6382 #endif /* BITMAP_LATER */
6384 offset = bitNumber >> 3;
6385 if (offset >= index->bitmapSize) {
6389 if (offset < index->bitmapOffset)
6390 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6391 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6394 #ifdef AFS_DEMAND_ATTACH_FS
6395 VCancelReservation_r(vp);
6397 return; /* make the compiler happy for non-DAFS */
6401 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6405 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6409 /* this function will drop the glock internally.
6410 * for old pthread fileservers, this is safe thanks to vbusy.
6412 * for demand attach fs, caller must have already called
6413 * VCreateReservation_r and VWaitExclusiveState_r */
6415 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6417 StreamHandle_t *file;
6418 afs_sfsize_t nVnodes, size;
6419 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6420 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6421 struct VnodeDiskObject *vnode;
6422 unsigned int unique = 0;
6426 #endif /* BITMAP_LATER */
6427 #ifdef AFS_DEMAND_ATTACH_FS
6428 VolState state_save;
6429 #endif /* AFS_DEMAND_ATTACH_FS */
6433 #ifdef AFS_DEMAND_ATTACH_FS
6434 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6435 #endif /* AFS_DEMAND_ATTACH_FS */
6438 fdP = IH_OPEN(vip->handle);
6439 osi_Assert(fdP != NULL);
6440 file = FDH_FDOPEN(fdP, "r");
6441 osi_Assert(file != NULL);
6442 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6443 osi_Assert(vnode != NULL);
6444 size = OS_SIZE(fdP->fd_fd);
6445 osi_Assert(size != -1);
6446 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6448 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6449 * a few files can be created in this volume,
6450 * the whole thing is rounded up to nearest 4
6451 * bytes, because the bit map allocator likes
6454 BitMap = (byte *) calloc(1, vip->bitmapSize);
6455 osi_Assert(BitMap != NULL);
6456 #else /* BITMAP_LATER */
6457 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6458 osi_Assert(vip->bitmap != NULL);
6459 vip->bitmapOffset = 0;
6460 #endif /* BITMAP_LATER */
6461 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6463 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6464 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6466 if (vnode->type != vNull) {
6467 if (vnode->vnodeMagic != vcp->magic) {
6468 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6473 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6474 #else /* BITMAP_LATER */
6475 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6476 #endif /* BITMAP_LATER */
6477 if (unique <= vnode->uniquifier)
6478 unique = vnode->uniquifier + 1;
6480 #ifndef AFS_PTHREAD_ENV
6481 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6484 #endif /* !AFS_PTHREAD_ENV */
6487 if (vp->nextVnodeUnique < unique) {
6488 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6491 /* Paranoia, partly justified--I think fclose after fdopen
6492 * doesn't seem to close fd. In any event, the documentation
6493 * doesn't specify, so it's safer to close it twice.
6501 /* There may have been a racing condition with some other thread, both
6502 * creating the bitmaps for this volume. If the other thread was faster
6503 * the pointer to bitmap should already be filled and we can free ours.
6505 if (vip->bitmap == NULL) {
6506 vip->bitmap = BitMap;
6507 vip->bitmapOffset = 0;
6509 free((byte *) BitMap);
6510 #endif /* BITMAP_LATER */
6511 #ifdef AFS_DEMAND_ATTACH_FS
6512 VChangeState_r(vp, state_save);
6513 #endif /* AFS_DEMAND_ATTACH_FS */
6517 /***************************************************/
6518 /* Volume Path and Volume Number utility routines */
6519 /***************************************************/
6522 * find the first occurrence of a volume header file and return the path.
6524 * @param[out] ec outbound error code
6525 * @param[in] volumeId volume id to find
6526 * @param[out] partitionp pointer to disk partition path string
6527 * @param[out] namep pointer to volume header file name string
6529 * @post path to first occurrence of volume header is returned in partitionp
6530 * and namep, or ec is set accordingly.
6532 * @warning this function is NOT re-entrant -- partitionp and namep point to
6533 * static data segments
6535 * @note if a volume utility inadvertently leaves behind a stale volume header
6536 * on a vice partition, it is possible for callers to get the wrong one,
6537 * depending on the order of the disk partition linked list.
6541 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6543 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6544 char path[VMAXPATHLEN];
6546 struct DiskPartition64 *dp;
6549 name[0] = OS_DIRSEPC;
6550 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6551 afs_printable_uint32_lu(volumeId));
6552 for (dp = DiskPartitionList; dp; dp = dp->next) {
6553 struct afs_stat_st status;
6554 strcpy(path, VPartitionPath(dp));
6556 if (afs_stat(path, &status) == 0) {
6557 strcpy(partition, dp->name);
6564 *partitionp = *namep = NULL;
6566 *partitionp = partition;
6572 * extract a volume number from a volume header filename string.
6574 * @param[in] name volume header filename string
6576 * @return volume number
6578 * @note the string must be of the form VFORMAT. the only permissible
6579 * deviation is a leading OS_DIRSEPC character.
6584 VolumeNumber(char *name)
6586 if (*name == OS_DIRSEPC)
6588 return strtoul(name + 1, NULL, 10);
6592 * compute the volume header filename.
6594 * @param[in] volumeId
6596 * @return volume header filename
6598 * @post volume header filename string is constructed
6600 * @warning this function is NOT re-entrant -- the returned string is
6601 * stored in a static char array. see VolumeExternalName_r
6602 * for a re-entrant equivalent.
6604 * @see VolumeExternalName_r
6606 * @deprecated due to the above re-entrancy warning, this interface should
6607 * be considered deprecated. Please use VolumeExternalName_r
6611 VolumeExternalName(VolumeId volumeId)
6613 static char name[VMAXPATHLEN];
6614 snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6619 * compute the volume header filename.
6621 * @param[in] volumeId
6622 * @param[inout] name array in which to store filename
6623 * @param[in] len length of name array
6625 * @return result code from afs_snprintf
6627 * @see VolumeExternalName
6630 * @note re-entrant equivalent of VolumeExternalName
6633 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6635 return snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6639 /***************************************************/
6640 /* Volume Usage Statistics routines */
6641 /***************************************************/
6643 #if OPENAFS_VOL_STATS
6644 #define OneDay (86400) /* 24 hours' worth of seconds */
6646 #define OneDay (24*60*60) /* 24 hours */
6647 #endif /* OPENAFS_VOL_STATS */
6650 Midnight(time_t t) {
6651 struct tm local, *l;
6654 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6655 l = localtime_r(&t, &local);
6661 /* the following is strictly speaking problematic on the
6662 switching day to daylight saving time, after the switch,
6663 as tm_isdst does not match. Similarly, on the looong day when
6664 switching back the OneDay check will not do what naively expected!
6665 The effects are minor, though, and more a matter of interpreting
6667 #ifndef AFS_PTHREAD_ENV
6670 local.tm_hour = local.tm_min=local.tm_sec = 0;
6671 midnight = mktime(&local);
6672 if (midnight != (time_t) -1) return(midnight);
6674 return( (t/OneDay)*OneDay );
6678 /*------------------------------------------------------------------------
6679 * [export] VAdjustVolumeStatistics
6682 * If we've passed midnight, we need to update all the day use
6683 * statistics as well as zeroing the detailed volume statistics
6684 * (if we are implementing them).
6687 * vp : Pointer to the volume structure describing the lucky
6688 * volume being considered for update.
6694 * Nothing interesting.
6698 *------------------------------------------------------------------------*/
6701 VAdjustVolumeStatistics_r(Volume * vp)
6703 unsigned int now = FT_ApproxTime();
6705 if (now - V_dayUseDate(vp) > OneDay) {
6708 ndays = (now - V_dayUseDate(vp)) / OneDay;
6709 for (i = 6; i > ndays - 1; i--)
6710 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6711 for (i = 0; i < ndays - 1 && i < 7; i++)
6712 V_weekUse(vp)[i] = 0;
6714 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6716 V_dayUseDate(vp) = Midnight(now);
6718 #if OPENAFS_VOL_STATS
6720 * All we need to do is bzero the entire VOL_STATS_BYTES of
6721 * the detailed volume statistics area.
6723 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6724 #endif /* OPENAFS_VOL_STATS */
6727 /*It's been more than a day of collection */
6729 * Always return happily.
6732 } /*VAdjustVolumeStatistics */
6735 VAdjustVolumeStatistics(Volume * vp)
6739 retVal = VAdjustVolumeStatistics_r(vp);
6745 VBumpVolumeUsage_r(Volume * vp)
6747 unsigned int now = FT_ApproxTime();
6748 V_accessDate(vp) = now;
6749 if (now - V_dayUseDate(vp) > OneDay)
6750 VAdjustVolumeStatistics_r(vp);
6752 * Save the volume header image to disk after a threshold of bumps to dayUse,
6753 * at most every usage_rate_limit seconds.
6756 vp->usage_bumps_outstanding++;
6757 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6758 && vp->usage_bumps_next_write <= now) {
6760 vp->usage_bumps_outstanding = 0;
6761 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6762 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6767 VBumpVolumeUsage(Volume * vp)
6770 VBumpVolumeUsage_r(vp);
6775 VSetDiskUsage_r(void)
6777 #ifndef AFS_DEMAND_ATTACH_FS
6778 static int FifteenMinuteCounter = 0;
6782 /* NOTE: Don't attempt to access the partitions list until the
6783 * initialization level indicates that all volumes are attached,
6784 * which implies that all partitions are initialized. */
6785 #ifdef AFS_PTHREAD_ENV
6786 VOL_CV_WAIT(&vol_vinit_cond);
6787 #else /* AFS_PTHREAD_ENV */
6789 #endif /* AFS_PTHREAD_ENV */
6792 VResetDiskUsage_r();
6794 #ifndef AFS_DEMAND_ATTACH_FS
6795 if (++FifteenMinuteCounter == 3) {
6796 FifteenMinuteCounter = 0;
6799 #endif /* !AFS_DEMAND_ATTACH_FS */
6811 /***************************************************/
6812 /* Volume Update List routines */
6813 /***************************************************/
6815 /* The number of minutes that a volume hasn't been updated before the
6816 * "Dont salvage" flag in the volume header will be turned on */
6817 #define SALVAGE_INTERVAL (10*60)
6822 * volume update list functionality has been moved into the VLRU
6823 * the DONT_SALVAGE flag is now set during VLRU demotion
6826 #ifndef AFS_DEMAND_ATTACH_FS
6827 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6828 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6829 static int updateSize = 0; /* number of entries possible */
6830 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6831 #endif /* !AFS_DEMAND_ATTACH_FS */
6834 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6837 vp->updateTime = FT_ApproxTime();
6838 if (V_dontSalvage(vp) == 0)
6840 V_dontSalvage(vp) = 0;
6841 VSyncVolume_r(ec, vp, 0);
6842 #ifdef AFS_DEMAND_ATTACH_FS
6843 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6844 #else /* !AFS_DEMAND_ATTACH_FS */
6847 if (UpdateList == NULL) {
6848 updateSize = UPDATE_LIST_SIZE;
6849 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6851 if (nUpdatedVolumes == updateSize) {
6853 if (updateSize > 524288) {
6854 Log("warning: there is likely a bug in the volume update scanner\n");
6858 (VolumeId *) realloc(UpdateList,
6859 sizeof(VolumeId) * updateSize);
6862 osi_Assert(UpdateList != NULL);
6863 UpdateList[nUpdatedVolumes++] = V_id(vp);
6864 #endif /* !AFS_DEMAND_ATTACH_FS */
6867 #ifndef AFS_DEMAND_ATTACH_FS
6869 VScanUpdateList(void)
6874 afs_uint32 now = FT_ApproxTime();
6875 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6876 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6878 UpdateList[i - gap] = UpdateList[i];
6880 /* XXX this routine needlessly messes up the Volume LRU by
6881 * breaking the LRU temporal-locality assumptions.....
6882 * we should use a special volume header allocator here */
6883 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6886 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6887 V_dontSalvage(vp) = DONT_SALVAGE;
6888 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6896 #ifndef AFS_PTHREAD_ENV
6898 #endif /* !AFS_PTHREAD_ENV */
6900 nUpdatedVolumes -= gap;
6902 #endif /* !AFS_DEMAND_ATTACH_FS */
6905 /***************************************************/
6906 /* Volume LRU routines */
6907 /***************************************************/
6912 * with demand attach fs, we attempt to soft detach(1)
6913 * volumes which have not been accessed in a long time
6914 * in order to speed up fileserver shutdown
6916 * (1) by soft detach we mean a process very similar
6917 * to VOffline, except the final state of the
6918 * Volume will be VOL_STATE_PREATTACHED, instead
6919 * of the usual VOL_STATE_UNATTACHED
6921 #ifdef AFS_DEMAND_ATTACH_FS
6923 /* implementation is reminiscent of a generational GC
6925 * queue 0 is newly attached volumes. this queue is
6926 * sorted by attach timestamp
6928 * queue 1 is volumes that have been around a bit
6929 * longer than queue 0. this queue is sorted by
6932 * queue 2 is volumes tha have been around the longest.
6933 * this queue is unsorted
6935 * queue 3 is volumes that have been marked as
6936 * candidates for soft detachment. this queue is
6939 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6940 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6943 * definition of a VLRU queue.
6946 volatile struct rx_queue q;
6953 * main VLRU data structure.
6956 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6959 /** time interval (in seconds) between promotion passes for
6960 * each young generation queue. */
6961 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6963 /** time interval (in seconds) between soft detach candidate
6964 * scans for each generation queue.
6966 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6967 * we perform a soft detach pass. */
6968 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6970 /* scheduler state */
6971 int next_idx; /**< next queue to receive attention */
6972 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6973 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6975 int scanner_state; /**< state of scanner thread */
6976 pthread_cond_t cv; /**< state transition CV */
6979 /** global VLRU state */
6980 static struct VLRU volume_LRU;
6983 * defined states for VLRU scanner thread.
6986 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6987 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6988 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6989 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6990 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6991 } vlru_thread_state_t;
6993 /* vlru disk data header stuff */
6994 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6995 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6997 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6998 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7001 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7002 * soft detachment. */
7003 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7005 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7006 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7008 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7009 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7011 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7012 static afs_uint32 VLRU_enabled = 1;
7014 /* queue synchronization routines */
7015 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7016 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7017 static void VLRU_Wait_r(struct VLRU_q * q);
7020 * set VLRU subsystem tunable parameters.
7022 * @param[in] option tunable option to modify
7023 * @param[in] val new value for tunable parameter
7025 * @pre @c VInitVolumePackage2 has not yet been called.
7027 * @post tunable parameter is modified
7031 * @note valid option parameters are:
7032 * @arg @c VLRU_SET_THRESH
7033 * set the period of inactivity after which
7034 * volumes are eligible for soft detachment
7035 * @arg @c VLRU_SET_INTERVAL
7036 * set the time interval between calls
7037 * to the volume LRU "garbage collector"
7038 * @arg @c VLRU_SET_MAX
7039 * set the max number of volumes to deallocate
7043 VLRU_SetOptions(int option, afs_uint32 val)
7045 if (option == VLRU_SET_THRESH) {
7046 VLRU_offline_thresh = val;
7047 } else if (option == VLRU_SET_INTERVAL) {
7048 VLRU_offline_interval = val;
7049 } else if (option == VLRU_SET_MAX) {
7050 VLRU_offline_max = val;
7051 } else if (option == VLRU_SET_ENABLED) {
7054 VLRU_ComputeConstants();
7058 * compute VLRU internal timing parameters.
7060 * @post VLRU scanner thread internal timing parameters are computed
7062 * @note computes internal timing parameters based upon user-modifiable
7063 * tunable parameters.
7067 * @internal volume package internal use only.
7070 VLRU_ComputeConstants(void)
7072 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7074 /* compute the candidate scan interval */
7075 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7077 /* compute the promotion intervals */
7078 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7079 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7082 /* compute the gen 0 scan interval */
7083 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7085 /* compute the gen 0 scan interval */
7086 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7091 * initialize VLRU subsystem.
7093 * @pre this function has not yet been called
7095 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7099 * @internal volume package internal use only.
7105 pthread_attr_t attrs;
7108 if (!VLRU_enabled) {
7109 Log("VLRU: disabled\n");
7113 /* initialize each of the VLRU queues */
7114 for (i = 0; i < VLRU_QUEUES; i++) {
7115 queue_Init(&volume_LRU.q[i]);
7116 volume_LRU.q[i].len = 0;
7117 volume_LRU.q[i].busy = 0;
7118 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7121 /* setup the timing constants */
7122 VLRU_ComputeConstants();
7124 /* XXX put inside LogLevel check? */
7125 Log("VLRU: starting scanner with the following configuration parameters:\n");
7126 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7127 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7128 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7129 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7130 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7131 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7133 /* start up the VLRU scanner */
7134 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7135 if (programType == fileServer) {
7136 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7137 osi_Assert(pthread_attr_init(&attrs) == 0);
7138 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7139 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7144 * initialize the VLRU-related fields of a newly allocated volume object.
7146 * @param[in] vp pointer to volume object
7149 * @arg @c VOL_LOCK is held.
7150 * @arg volume object is not on a VLRU queue.
7152 * @post VLRU fields are initialized to indicate that volume object is not
7153 * currently registered with the VLRU subsystem
7157 * @internal volume package interal use only.
7160 VLRU_Init_Node_r(Volume * vp)
7165 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7166 vp->vlru.idx = VLRU_QUEUE_INVALID;
7170 * add a volume object to a VLRU queue.
7172 * @param[in] vp pointer to volume object
7175 * @arg @c VOL_LOCK is held.
7176 * @arg caller MUST hold a lightweight ref on @p vp.
7177 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7179 * @post the volume object is added to the appropriate VLRU queue
7181 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7182 * then the volume is added to that queue. Otherwise, the value
7183 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7184 * volume is added to the NEW generation queue.
7186 * @note @c VOL_LOCK may be dropped internally
7188 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7189 * during the add operation, and is restored to the previous
7190 * state prior to return.
7194 * @internal volume package internal use only.
7197 VLRU_Add_r(Volume * vp)
7200 VolState state_save;
7205 if (queue_IsOnQueue(&vp->vlru))
7208 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7211 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7212 idx = VLRU_QUEUE_NEW;
7215 VLRU_Wait_r(&volume_LRU.q[idx]);
7217 /* repeat check since VLRU_Wait_r may have dropped
7219 if (queue_IsNotOnQueue(&vp->vlru)) {
7221 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7222 volume_LRU.q[idx].len++;
7223 V_attachFlags(vp) |= VOL_ON_VLRU;
7224 vp->stats.last_promote = FT_ApproxTime();
7227 VChangeState_r(vp, state_save);
7231 * delete a volume object from a VLRU queue.
7233 * @param[in] vp pointer to volume object
7236 * @arg @c VOL_LOCK is held.
7237 * @arg caller MUST hold a lightweight ref on @p vp.
7238 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7240 * @post volume object is removed from the VLRU queue
7242 * @note @c VOL_LOCK may be dropped internally
7246 * @todo We should probably set volume state to something exlcusive
7247 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7249 * @internal volume package internal use only.
7252 VLRU_Delete_r(Volume * vp)
7259 if (queue_IsNotOnQueue(&vp->vlru))
7265 if (idx == VLRU_QUEUE_INVALID)
7267 VLRU_Wait_r(&volume_LRU.q[idx]);
7268 } while (idx != vp->vlru.idx);
7270 /* now remove from the VLRU and update
7271 * the appropriate counter */
7272 queue_Remove(&vp->vlru);
7273 volume_LRU.q[idx].len--;
7274 vp->vlru.idx = VLRU_QUEUE_INVALID;
7275 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7279 * tell the VLRU subsystem that a volume was just accessed.
7281 * @param[in] vp pointer to volume object
7284 * @arg @c VOL_LOCK is held
7285 * @arg caller MUST hold a lightweight ref on @p vp
7286 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7288 * @post volume VLRU access statistics are updated. If the volume was on
7289 * the VLRU soft detach candidate queue, it is moved to the NEW
7292 * @note @c VOL_LOCK may be dropped internally
7296 * @internal volume package internal use only.
7299 VLRU_UpdateAccess_r(Volume * vp)
7301 Volume * rvp = NULL;
7306 if (queue_IsNotOnQueue(&vp->vlru))
7309 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7311 /* update the access timestamp */
7312 vp->stats.last_get = FT_ApproxTime();
7315 * if the volume is on the soft detach candidate
7316 * list, we need to safely move it back to a
7317 * regular generation. this has to be done
7318 * carefully so we don't race against the scanner
7322 /* if this volume is on the soft detach candidate queue,
7323 * then grab exclusive access to the necessary queues */
7324 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7326 VCreateReservation_r(rvp);
7328 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7329 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7330 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7331 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7334 /* make sure multiple threads don't race to update */
7335 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7336 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7340 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7341 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7342 VCancelReservation_r(rvp);
7347 * switch a volume between two VLRU queues.
7349 * @param[in] vp pointer to volume object
7350 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7351 * @param[in] append controls whether the volume will be appended or
7352 * prepended to the queue. A nonzero value means it will
7353 * be appended; zero means it will be prepended.
7355 * @pre The new (and old, if applicable) queue(s) must either be owned
7356 * exclusively by the calling thread for asynchronous manipulation,
7357 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7358 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7359 * for further details of the queue asynchronous processing mechanism.
7361 * @post If the volume object was already on a VLRU queue, it is
7362 * removed from the queue. Depending on the value of the append
7363 * parameter, the volume object is either appended or prepended
7364 * to the VLRU queue referenced by the new_idx parameter.
7368 * @see VLRU_BeginExclusive_r
7369 * @see VLRU_EndExclusive_r
7372 * @internal volume package internal use only.
7375 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7377 if (queue_IsNotOnQueue(&vp->vlru))
7380 queue_Remove(&vp->vlru);
7381 volume_LRU.q[vp->vlru.idx].len--;
7383 /* put the volume back on the correct generational queue */
7385 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7387 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7390 volume_LRU.q[new_idx].len++;
7391 vp->vlru.idx = new_idx;
7395 * VLRU background thread.
7397 * The VLRU Scanner Thread is responsible for periodically scanning through
7398 * each VLRU queue looking for volumes which should be moved to another
7399 * queue, or soft detached.
7401 * @param[in] args unused thread arguments parameter
7403 * @return unused thread return value
7404 * @retval NULL always
7406 * @internal volume package internal use only.
7409 VLRU_ScannerThread(void * args)
7411 afs_uint32 now, min_delay, delay;
7412 int i, min_idx, min_op, overdue, state;
7414 /* set t=0 for promotion cycle to be
7415 * fileserver startup */
7416 now = FT_ApproxTime();
7417 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7418 volume_LRU.last_promotion[i] = now;
7421 /* don't start the scanner until VLRU_offline_thresh
7422 * plus a small delay for VInitVolumePackage2 to finish
7425 sleep(VLRU_offline_thresh + 60);
7427 /* set t=0 for scan cycle to be now */
7428 now = FT_ApproxTime();
7429 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7430 volume_LRU.last_scan[i] = now;
7434 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7435 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7438 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7439 /* check to see if we've been asked to pause */
7440 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7441 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7442 CV_BROADCAST(&volume_LRU.cv);
7444 VOL_CV_WAIT(&volume_LRU.cv);
7445 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7448 /* scheduling can happen outside the glock */
7451 /* figure out what is next on the schedule */
7453 /* figure out a potential schedule for the new generation first */
7455 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7458 if (min_delay > volume_LRU.scan_interval[0]) {
7459 /* unsigned overflow -- we're overdue to run this scan */
7464 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7466 i = VLRU_QUEUE_CANDIDATE;
7467 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7468 if (delay < min_delay) {
7472 if (delay > volume_LRU.scan_interval[i]) {
7473 /* unsigned overflow -- we're overdue to run this scan */
7480 /* if we're still not overdue for something, figure out schedules for promotions */
7481 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7482 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7483 if (delay < min_delay) {
7488 if (delay > volume_LRU.promotion_interval[i]) {
7489 /* unsigned overflow -- we're overdue to run this promotion */
7498 /* sleep as needed */
7503 /* do whatever is next */
7506 VLRU_Promote_r(min_idx);
7507 VLRU_Demote_r(min_idx+1);
7509 VLRU_Scan_r(min_idx);
7511 now = FT_ApproxTime();
7514 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7516 /* signal that scanner is down */
7517 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7518 CV_BROADCAST(&volume_LRU.cv);
7524 * promote volumes from one VLRU generation to the next.
7526 * This routine scans a VLRU generation looking for volumes which are
7527 * eligible to be promoted to the next generation. All volumes which
7528 * meet the eligibility requirement are promoted.
7530 * Promotion eligibility is based upon meeting both of the following
7533 * @arg The volume has been accessed since the last promotion:
7534 * @c (vp->stats.last_get >= vp->stats.last_promote)
7535 * @arg The last promotion occurred at least
7536 * @c volume_LRU.promotion_interval[idx] seconds ago
7538 * As a performance optimization, promotions are "globbed". In other
7539 * words, we promote arbitrarily large contiguous sublists of elements
7542 * @param[in] idx VLRU queue index to scan
7546 * @internal VLRU internal use only.
7549 VLRU_Promote_r(int idx)
7551 int len, chaining, promote;
7552 afs_uint32 now, thresh;
7553 struct rx_queue *qp, *nqp;
7554 Volume * vp, *start = NULL, *end = NULL;
7556 /* get exclusive access to two chains, and drop the glock */
7557 VLRU_Wait_r(&volume_LRU.q[idx]);
7558 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7559 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7560 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7563 thresh = volume_LRU.promotion_interval[idx];
7564 now = FT_ApproxTime();
7567 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7568 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7569 promote = (((vp->stats.last_promote + thresh) <= now) &&
7570 (vp->stats.last_get >= vp->stats.last_promote));
7578 /* promote and prepend chain */
7579 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7593 /* promote and prepend */
7594 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7598 volume_LRU.q[idx].len -= len;
7599 volume_LRU.q[idx+1].len += len;
7602 /* release exclusive access to the two chains */
7604 volume_LRU.last_promotion[idx] = now;
7605 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7606 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7609 /* run the demotions */
7611 VLRU_Demote_r(int idx)
7614 int len, chaining, demote;
7615 afs_uint32 now, thresh;
7616 struct rx_queue *qp, *nqp;
7617 Volume * vp, *start = NULL, *end = NULL;
7618 Volume ** salv_flag_vec = NULL;
7619 int salv_vec_offset = 0;
7621 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7623 /* get exclusive access to two chains, and drop the glock */
7624 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7625 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7626 VLRU_Wait_r(&volume_LRU.q[idx]);
7627 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7630 /* no big deal if this allocation fails */
7631 if (volume_LRU.q[idx].len) {
7632 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7635 now = FT_ApproxTime();
7636 thresh = volume_LRU.promotion_interval[idx-1];
7639 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7640 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7641 demote = (((vp->stats.last_promote + thresh) <= now) &&
7642 (vp->stats.last_get < (now - thresh)));
7644 /* we now do volume update list DONT_SALVAGE flag setting during
7645 * demotion passes */
7646 if (salv_flag_vec &&
7647 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7649 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7650 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7651 salv_flag_vec[salv_vec_offset++] = vp;
7652 VCreateReservation_r(vp);
7661 /* demote and append chain */
7662 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7676 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7680 volume_LRU.q[idx].len -= len;
7681 volume_LRU.q[idx-1].len += len;
7684 /* release exclusive access to the two chains */
7686 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7687 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7689 /* now go back and set the DONT_SALVAGE flags as appropriate */
7690 if (salv_flag_vec) {
7692 for (i = 0; i < salv_vec_offset; i++) {
7693 vp = salv_flag_vec[i];
7694 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7695 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7696 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7699 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7700 V_dontSalvage(vp) = DONT_SALVAGE;
7701 VUpdateVolume_r(&ec, vp, 0);
7705 VCancelReservation_r(vp);
7707 free(salv_flag_vec);
7711 /* run a pass of the VLRU GC scanner */
7713 VLRU_Scan_r(int idx)
7715 afs_uint32 now, thresh;
7716 struct rx_queue *qp, *nqp;
7720 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7722 /* gain exclusive access to the idx VLRU */
7723 VLRU_Wait_r(&volume_LRU.q[idx]);
7724 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7726 if (idx != VLRU_QUEUE_CANDIDATE) {
7727 /* gain exclusive access to the candidate VLRU */
7728 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7729 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7732 now = FT_ApproxTime();
7733 thresh = now - VLRU_offline_thresh;
7735 /* perform candidate selection and soft detaching */
7736 if (idx == VLRU_QUEUE_CANDIDATE) {
7737 /* soft detach some volumes from the candidate pool */
7741 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7742 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7743 if (i >= VLRU_offline_max) {
7746 /* check timestamp to see if it's a candidate for soft detaching */
7747 if (vp->stats.last_get <= thresh) {
7749 if (VCheckSoftDetach(vp, thresh))
7755 /* scan for volumes to become soft detach candidates */
7756 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7757 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7759 /* check timestamp to see if it's a candidate for soft detaching */
7760 if (vp->stats.last_get <= thresh) {
7761 VCheckSoftDetachCandidate(vp, thresh);
7764 if (!(i&0x7f)) { /* lock coarsening optimization */
7772 /* relinquish exclusive access to the VLRU chains */
7776 volume_LRU.last_scan[idx] = now;
7777 if (idx != VLRU_QUEUE_CANDIDATE) {
7778 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7780 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7783 /* check whether volume is safe to soft detach
7784 * caller MUST NOT hold a ref count on vp */
7786 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7790 if (vp->nUsers || vp->nWaiters)
7793 if (vp->stats.last_get <= thresh) {
7794 ret = VSoftDetachVolume_r(vp, thresh);
7800 /* check whether volume should be made a
7801 * soft detach candidate */
7803 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7806 if (vp->nUsers || vp->nWaiters)
7811 osi_Assert(idx == VLRU_QUEUE_NEW);
7813 if (vp->stats.last_get <= thresh) {
7814 /* move to candidate pool */
7815 queue_Remove(&vp->vlru);
7816 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7817 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7818 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7819 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7827 /* begin exclusive access on VLRU */
7829 VLRU_BeginExclusive_r(struct VLRU_q * q)
7831 osi_Assert(q->busy == 0);
7835 /* end exclusive access on VLRU */
7837 VLRU_EndExclusive_r(struct VLRU_q * q)
7839 osi_Assert(q->busy);
7841 CV_BROADCAST(&q->cv);
7844 /* wait for another thread to end exclusive access on VLRU */
7846 VLRU_Wait_r(struct VLRU_q * q)
7849 VOL_CV_WAIT(&q->cv);
7854 * volume soft detach
7856 * caller MUST NOT hold a ref count on vp */
7858 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7863 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7865 ts_save = vp->stats.last_get;
7866 if (ts_save > thresh)
7869 if (vp->nUsers || vp->nWaiters)
7872 if (VIsExclusiveState(V_attachState(vp))) {
7876 switch (V_attachState(vp)) {
7877 case VOL_STATE_UNATTACHED:
7878 case VOL_STATE_PREATTACHED:
7879 case VOL_STATE_ERROR:
7880 case VOL_STATE_GOING_OFFLINE:
7881 case VOL_STATE_SHUTTING_DOWN:
7882 case VOL_STATE_SALVAGING:
7883 case VOL_STATE_DELETED:
7884 volume_LRU.q[vp->vlru.idx].len--;
7886 /* create and cancel a reservation to
7887 * give the volume an opportunity to
7889 VCreateReservation_r(vp);
7890 queue_Remove(&vp->vlru);
7891 vp->vlru.idx = VLRU_QUEUE_INVALID;
7892 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7893 VCancelReservation_r(vp);
7899 /* hold the volume and take it offline.
7900 * no need for reservations, as VHold_r
7901 * takes care of that internally. */
7902 if (VHold_r(vp) == 0) {
7903 /* vhold drops the glock, so now we should
7904 * check to make sure we aren't racing against
7905 * other threads. if we are racing, offlining vp
7906 * would be wasteful, and block the scanner for a while
7910 (vp->shuttingDown) ||
7911 (vp->goingOffline) ||
7912 (vp->stats.last_get != ts_save)) {
7913 /* looks like we're racing someone else. bail */
7917 /* pull it off the VLRU */
7918 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7919 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7920 queue_Remove(&vp->vlru);
7921 vp->vlru.idx = VLRU_QUEUE_INVALID;
7922 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7924 /* take if offline */
7925 VOffline_r(vp, "volume has been soft detached");
7927 /* invalidate the volume header cache */
7928 FreeVolumeHeader(vp);
7931 IncUInt64(&VStats.soft_detaches);
7932 vp->stats.soft_detaches++;
7934 /* put in pre-attached state so demand
7935 * attacher can work on it */
7936 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7942 #endif /* AFS_DEMAND_ATTACH_FS */
7945 /***************************************************/
7946 /* Volume Header Cache routines */
7947 /***************************************************/
7950 * volume header cache.
7952 struct volume_hdr_LRU_t volume_hdr_LRU;
7955 * initialize the volume header cache.
7957 * @param[in] howMany number of header cache entries to preallocate
7959 * @pre VOL_LOCK held. Function has never been called before.
7961 * @post howMany cache entries are allocated, initialized, and added
7962 * to the LRU list. Header cache statistics are initialized.
7964 * @note only applicable to fileServer program type. Should only be
7965 * called once during volume package initialization.
7967 * @internal volume package internal use only.
7970 VInitVolumeHeaderCache(afs_uint32 howMany)
7972 struct volHeader *hp;
7973 if (programType != fileServer)
7975 queue_Init(&volume_hdr_LRU);
7976 volume_hdr_LRU.stats.free = 0;
7977 volume_hdr_LRU.stats.used = howMany;
7978 volume_hdr_LRU.stats.attached = 0;
7979 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7980 osi_Assert(hp != NULL);
7983 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7984 * to ensure they have the right values
7986 ReleaseVolumeHeader(hp++);
7989 /* get a volume header off of the volume header LRU.
7991 * @return volume header
7992 * @retval NULL no usable volume header is available on the LRU
7994 * @pre VOL_LOCK held
7996 * @post for DAFS, if the returned header is associated with a volume, that
7997 * volume is NOT in an exclusive state
7999 * @internal volume package internal use only.
8001 #ifdef AFS_DEMAND_ATTACH_FS
8002 static struct volHeader*
8003 GetVolHeaderFromLRU(void)
8005 struct volHeader *hd = NULL, *qh, *nqh;
8006 /* Usually, a volume in an exclusive state will not have its header on
8007 * the LRU. However, it is possible for this to occur when a salvage
8008 * request is received over FSSYNC, and possibly in other corner cases.
8009 * So just skip over headers whose volumes are in an exclusive state. We
8010 * could VWaitExclusiveState_r instead, but not waiting is faster and
8012 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8013 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8021 #else /* AFS_DEMAND_ATTACH_FS */
8022 static struct volHeader*
8023 GetVolHeaderFromLRU(void)
8025 struct volHeader *hd = NULL;
8026 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8027 hd = queue_First(&volume_hdr_LRU, volHeader);
8032 #endif /* !AFS_DEMAND_ATTACH_FS */
8035 * get a volume header and attach it to the volume object.
8037 * @param[in] vp pointer to volume object
8039 * @return cache entry status
8040 * @retval 0 volume header was newly attached; cache data is invalid
8041 * @retval 1 volume header was previously attached; cache data is valid
8043 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8045 * @post volume header attached to volume object. if necessary, header cache
8046 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8048 * @note VOL_LOCK may be dropped
8050 * @warning this interface does not load header data from disk. it merely
8051 * attaches a header object to the volume object, and may sync the old
8052 * header cache data out to disk in the process.
8054 * @internal volume package internal use only.
8057 GetVolumeHeader(Volume * vp)
8060 struct volHeader *hd;
8062 static int everLogged = 0;
8064 #ifdef AFS_DEMAND_ATTACH_FS
8065 VolState vp_save = 0, back_save = 0;
8067 /* XXX debug 9/19/05 we've apparently got
8068 * a ref counting bug somewhere that's
8069 * breaking the nUsers == 0 => header on LRU
8071 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8072 Log("nUsers == 0, but header not on LRU\n");
8077 old = (vp->header != NULL); /* old == volume already has a header */
8079 if (programType != fileServer) {
8080 /* for volume utilities, we allocate volHeaders as needed */
8082 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
8083 osi_Assert(hd != NULL);
8086 #ifdef AFS_DEMAND_ATTACH_FS
8087 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8091 /* for the fileserver, we keep a volume header cache */
8093 /* the header we previously dropped in the lru is
8094 * still available. pull it off the lru and return */
8097 osi_Assert(hd->back == vp);
8098 #ifdef AFS_DEMAND_ATTACH_FS
8099 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8102 hd = GetVolHeaderFromLRU();
8104 /* LRU is empty, so allocate a new volHeader
8105 * this is probably indicative of a leak, so let the user know */
8106 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
8107 osi_Assert(hd != NULL);
8109 Log("****Allocated more volume headers, probably leak****\n");
8112 volume_hdr_LRU.stats.free++;
8115 /* this header used to belong to someone else.
8116 * we'll need to check if the header needs to
8117 * be sync'd out to disk */
8119 #ifdef AFS_DEMAND_ATTACH_FS
8120 /* GetVolHeaderFromLRU had better not give us back a header
8121 * with a volume in exclusive state... */
8122 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8125 if (hd->diskstuff.inUse) {
8126 /* volume was in use, so we'll need to sync
8127 * its header to disk */
8129 #ifdef AFS_DEMAND_ATTACH_FS
8130 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8131 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8132 VCreateReservation_r(hd->back);
8136 WriteVolumeHeader_r(&error, hd->back);
8137 /* Ignore errors; catch them later */
8139 #ifdef AFS_DEMAND_ATTACH_FS
8144 hd->back->header = NULL;
8145 #ifdef AFS_DEMAND_ATTACH_FS
8146 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8148 if (hd->diskstuff.inUse) {
8149 VChangeState_r(hd->back, back_save);
8150 VCancelReservation_r(hd->back);
8151 VChangeState_r(vp, vp_save);
8155 volume_hdr_LRU.stats.attached++;
8159 #ifdef AFS_DEMAND_ATTACH_FS
8160 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8163 volume_hdr_LRU.stats.free--;
8164 volume_hdr_LRU.stats.used++;
8166 IncUInt64(&VStats.hdr_gets);
8167 #ifdef AFS_DEMAND_ATTACH_FS
8168 IncUInt64(&vp->stats.hdr_gets);
8169 vp->stats.last_hdr_get = FT_ApproxTime();
8176 * make sure volume header is attached and contains valid cache data.
8178 * @param[out] ec outbound error code
8179 * @param[in] vp pointer to volume object
8181 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8183 * @post header cache entry attached, and loaded with valid data, or
8184 * *ec is nonzero, and the header is released back into the LRU.
8186 * @internal volume package internal use only.
8189 LoadVolumeHeader(Error * ec, Volume * vp)
8191 #ifdef AFS_DEMAND_ATTACH_FS
8192 VolState state_save;
8196 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8197 IncUInt64(&VStats.hdr_loads);
8198 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8201 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8202 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8204 IncUInt64(&vp->stats.hdr_loads);
8205 now = FT_ApproxTime();
8209 V_attachFlags(vp) |= VOL_HDR_LOADED;
8210 vp->stats.last_hdr_load = now;
8212 VChangeState_r(vp, state_save);
8214 #else /* AFS_DEMAND_ATTACH_FS */
8216 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8217 IncUInt64(&VStats.hdr_loads);
8219 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8220 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8223 #endif /* AFS_DEMAND_ATTACH_FS */
8225 /* maintain (nUsers==0) => header in LRU invariant */
8226 FreeVolumeHeader(vp);
8231 * release a header cache entry back into the LRU list.
8233 * @param[in] hd pointer to volume header cache object
8235 * @pre VOL_LOCK held.
8237 * @post header cache object appended onto end of LRU list.
8239 * @note only applicable to fileServer program type.
8241 * @note used to place a header cache entry back into the
8242 * LRU pool without invalidating it as a cache entry.
8244 * @internal volume package internal use only.
8247 ReleaseVolumeHeader(struct volHeader *hd)
8249 if (programType != fileServer)
8251 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8253 queue_Append(&volume_hdr_LRU, hd);
8254 #ifdef AFS_DEMAND_ATTACH_FS
8256 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8259 volume_hdr_LRU.stats.free++;
8260 volume_hdr_LRU.stats.used--;
8264 * free/invalidate a volume header cache entry.
8266 * @param[in] vp pointer to volume object
8268 * @pre VOL_LOCK is held.
8270 * @post For fileserver, header cache entry is returned to LRU, and it is
8271 * invalidated as a cache entry. For volume utilities, the header
8272 * cache entry is freed.
8274 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8275 * whenever it is necessary to invalidate the header cache entry.
8277 * @see ReleaseVolumeHeader
8279 * @internal volume package internal use only.
8282 FreeVolumeHeader(Volume * vp)
8284 struct volHeader *hd = vp->header;
8287 if (programType == fileServer) {
8288 ReleaseVolumeHeader(hd);
8293 #ifdef AFS_DEMAND_ATTACH_FS
8294 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8296 volume_hdr_LRU.stats.attached--;
8301 /***************************************************/
8302 /* Volume Hash Table routines */
8303 /***************************************************/
8306 * set size of volume object hash table.
8308 * @param[in] logsize log(2) of desired hash table size
8310 * @return operation status
8312 * @retval -1 failure
8314 * @pre MUST be called prior to VInitVolumePackage2
8316 * @post Volume Hash Table will have 2^logsize buckets
8319 VSetVolHashSize(int logsize)
8321 /* 64 to 268435456 hash buckets seems like a reasonable range */
8322 if ((logsize < 6 ) || (logsize > 28)) {
8327 VolumeHashTable.Size = 1 << logsize;
8328 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8330 /* we can't yet support runtime modification of this
8331 * parameter. we'll need a configuration rwlock to
8332 * make runtime modification feasible.... */
8339 * initialize dynamic data structures for volume hash table.
8341 * @post hash table is allocated, and fields are initialized.
8343 * @internal volume package internal use only.
8346 VInitVolumeHash(void)
8350 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8351 sizeof(VolumeHashChainHead));
8352 osi_Assert(VolumeHashTable.Table != NULL);
8354 for (i=0; i < VolumeHashTable.Size; i++) {
8355 queue_Init(&VolumeHashTable.Table[i]);
8356 #ifdef AFS_DEMAND_ATTACH_FS
8357 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8358 #endif /* AFS_DEMAND_ATTACH_FS */
8363 * add a volume object to the hash table.
8365 * @param[in] vp pointer to volume object
8366 * @param[in] hashid hash of volume id
8368 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8371 * @post volume is added to hash chain.
8373 * @internal volume package internal use only.
8375 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8376 * asynchronous hash chain reordering to finish.
8379 AddVolumeToHashTable(Volume * vp, int hashid)
8381 VolumeHashChainHead * head;
8383 if (queue_IsOnQueue(vp))
8386 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8388 #ifdef AFS_DEMAND_ATTACH_FS
8389 /* wait for the hash chain to become available */
8392 V_attachFlags(vp) |= VOL_IN_HASH;
8393 vp->chainCacheCheck = ++head->cacheCheck;
8394 #endif /* AFS_DEMAND_ATTACH_FS */
8397 vp->hashid = hashid;
8398 queue_Append(head, vp);
8399 vp->vnodeHashOffset = VolumeHashOffset_r();
8403 * delete a volume object from the hash table.
8405 * @param[in] vp pointer to volume object
8407 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8410 * @post volume is removed from hash chain.
8412 * @internal volume package internal use only.
8414 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8415 * asynchronous hash chain reordering to finish.
8418 DeleteVolumeFromHashTable(Volume * vp)
8420 VolumeHashChainHead * head;
8422 if (!queue_IsOnQueue(vp))
8425 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8427 #ifdef AFS_DEMAND_ATTACH_FS
8428 /* wait for the hash chain to become available */
8431 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8433 #endif /* AFS_DEMAND_ATTACH_FS */
8437 /* do NOT reset hashid to zero, as the online
8438 * salvager package may need to know the volume id
8439 * after the volume is removed from the hash */
8443 * lookup a volume object in the hash table given a volume id.
8445 * @param[out] ec error code return
8446 * @param[in] volumeId volume id
8447 * @param[in] hint volume object which we believe could be the correct
8450 * @return volume object pointer
8451 * @retval NULL no such volume id is registered with the hash table.
8453 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8456 * @post volume object with the given id is returned. volume object and
8457 * hash chain access statistics are updated. hash chain may have
8460 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8461 * asynchronous hash chain reordering operation to finish, or
8462 * in order for us to perform an asynchronous chain reordering.
8464 * @note Hash chain reorderings occur when the access count for the
8465 * volume object being looked up exceeds the sum of the previous
8466 * node's (the node ahead of it in the hash chain linked list)
8467 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8469 * @note For DAFS, the hint parameter allows us to short-circuit if the
8470 * cacheCheck fields match between the hash chain head and the
8471 * hint volume object.
8474 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8478 #ifdef AFS_DEMAND_ATTACH_FS
8481 VolumeHashChainHead * head;
8484 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8486 #ifdef AFS_DEMAND_ATTACH_FS
8487 /* wait for the hash chain to become available */
8490 /* check to see if we can short circuit without walking the hash chain */
8491 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8492 IncUInt64(&hint->stats.hash_short_circuits);
8495 #endif /* AFS_DEMAND_ATTACH_FS */
8497 /* someday we need to either do per-chain locks, RWlocks,
8498 * or both for volhash access.
8499 * (and move to a data structure with better cache locality) */
8501 /* search the chain for this volume id */
8502 for(queue_Scan(head, vp, np, Volume)) {
8504 if ((vp->hashid == volumeId)) {
8509 if (queue_IsEnd(head, vp)) {
8513 #ifdef AFS_DEMAND_ATTACH_FS
8514 /* update hash chain statistics */
8517 FillInt64(lks, 0, looks);
8518 AddUInt64(head->looks, lks, &head->looks);
8519 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8520 IncUInt64(&head->gets);
8525 IncUInt64(&vp->stats.hash_lookups);
8527 /* for demand attach fileserver, we permit occasional hash chain reordering
8528 * so that frequently looked up volumes move towards the head of the chain */
8529 pp = queue_Prev(vp, Volume);
8530 if (!queue_IsEnd(head, pp)) {
8531 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8532 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8533 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8534 VReorderHash_r(head, pp, vp);
8538 /* update the short-circuit cache check */
8539 vp->chainCacheCheck = head->cacheCheck;
8541 #endif /* AFS_DEMAND_ATTACH_FS */
8546 #ifdef AFS_DEMAND_ATTACH_FS
8547 /* perform volume hash chain reordering.
8549 * advance a subchain beginning at vp ahead of
8550 * the adjacent subchain ending at pp */
8552 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8554 Volume *tp, *np, *lp;
8555 afs_uint64 move_thresh;
8557 /* this should never be called if the chain is already busy, so
8558 * no need to wait for other exclusive chain ops to finish */
8560 /* this is a rather heavy set of operations,
8561 * so let's set the chain busy flag and drop
8563 VHashBeginExclusive_r(head);
8566 /* scan forward in the chain from vp looking for the last element
8567 * in the chain we want to advance */
8568 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8569 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8570 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8571 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8575 lp = queue_Prev(tp, Volume);
8577 /* scan backwards from pp to determine where to splice and
8578 * insert the subchain we're advancing */
8579 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8580 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8584 tp = queue_Next(tp, Volume);
8586 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8587 queue_MoveChainBefore(tp,vp,lp);
8590 IncUInt64(&VStats.hash_reorders);
8592 IncUInt64(&head->reorders);
8594 /* wake up any threads waiting for the hash chain */
8595 VHashEndExclusive_r(head);
8599 /* demand-attach fs volume hash
8600 * asynchronous exclusive operations */
8603 * begin an asynchronous exclusive operation on a volume hash chain.
8605 * @param[in] head pointer to volume hash chain head object
8607 * @pre VOL_LOCK held. hash chain is quiescent.
8609 * @post hash chain marked busy.
8611 * @note this interface is used in conjunction with VHashEndExclusive_r and
8612 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8613 * volume hash chain. Its main use case is hash chain reordering, which
8614 * has the potential to be a highly latent operation.
8616 * @see VHashEndExclusive_r
8621 * @internal volume package internal use only.
8624 VHashBeginExclusive_r(VolumeHashChainHead * head)
8626 osi_Assert(head->busy == 0);
8631 * relinquish exclusive ownership of a volume hash chain.
8633 * @param[in] head pointer to volume hash chain head object
8635 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8637 * @post hash chain is marked quiescent. threads awaiting use of
8638 * chain are awakened.
8640 * @see VHashBeginExclusive_r
8645 * @internal volume package internal use only.
8648 VHashEndExclusive_r(VolumeHashChainHead * head)
8650 osi_Assert(head->busy);
8652 CV_BROADCAST(&head->chain_busy_cv);
8656 * wait for all asynchronous operations on a hash chain to complete.
8658 * @param[in] head pointer to volume hash chain head object
8660 * @pre VOL_LOCK held.
8662 * @post hash chain object is quiescent.
8664 * @see VHashBeginExclusive_r
8665 * @see VHashEndExclusive_r
8669 * @note This interface should be called before any attempt to
8670 * traverse the hash chain. It is permissible for a thread
8671 * to gain exclusive access to the chain, and then perform
8672 * latent operations on the chain asynchronously wrt the
8675 * @warning if waiting is necessary, VOL_LOCK is dropped
8677 * @internal volume package internal use only.
8680 VHashWait_r(VolumeHashChainHead * head)
8682 while (head->busy) {
8683 VOL_CV_WAIT(&head->chain_busy_cv);
8686 #endif /* AFS_DEMAND_ATTACH_FS */
8689 /***************************************************/
8690 /* Volume by Partition List routines */
8691 /***************************************************/
8694 * demand attach fileserver adds a
8695 * linked list of volumes to each
8696 * partition object, thus allowing
8697 * for quick enumeration of all
8698 * volumes on a partition
8701 #ifdef AFS_DEMAND_ATTACH_FS
8703 * add a volume to its disk partition VByPList.
8705 * @param[in] vp pointer to volume object
8707 * @pre either the disk partition VByPList is owned exclusively
8708 * by the calling thread, or the list is quiescent and
8711 * @post volume is added to disk partition VByPList
8715 * @warning it is the caller's responsibility to ensure list
8718 * @see VVByPListWait_r
8719 * @see VVByPListBeginExclusive_r
8720 * @see VVByPListEndExclusive_r
8722 * @internal volume package internal use only.
8725 AddVolumeToVByPList_r(Volume * vp)
8727 if (queue_IsNotOnQueue(&vp->vol_list)) {
8728 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8729 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8730 vp->partition->vol_list.len++;
8735 * delete a volume from its disk partition VByPList.
8737 * @param[in] vp pointer to volume object
8739 * @pre either the disk partition VByPList is owned exclusively
8740 * by the calling thread, or the list is quiescent and
8743 * @post volume is removed from the disk partition VByPList
8747 * @warning it is the caller's responsibility to ensure list
8750 * @see VVByPListWait_r
8751 * @see VVByPListBeginExclusive_r
8752 * @see VVByPListEndExclusive_r
8754 * @internal volume package internal use only.
8757 DeleteVolumeFromVByPList_r(Volume * vp)
8759 if (queue_IsOnQueue(&vp->vol_list)) {
8760 queue_Remove(&vp->vol_list);
8761 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8762 vp->partition->vol_list.len--;
8767 * begin an asynchronous exclusive operation on a VByPList.
8769 * @param[in] dp pointer to disk partition object
8771 * @pre VOL_LOCK held. VByPList is quiescent.
8773 * @post VByPList marked busy.
8775 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8776 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8779 * @see VVByPListEndExclusive_r
8780 * @see VVByPListWait_r
8784 * @internal volume package internal use only.
8786 /* take exclusive control over the list */
8788 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8790 osi_Assert(dp->vol_list.busy == 0);
8791 dp->vol_list.busy = 1;
8795 * relinquish exclusive ownership of a VByPList.
8797 * @param[in] dp pointer to disk partition object
8799 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8801 * @post VByPList is marked quiescent. threads awaiting use of
8802 * the list are awakened.
8804 * @see VVByPListBeginExclusive_r
8805 * @see VVByPListWait_r
8809 * @internal volume package internal use only.
8812 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8814 osi_Assert(dp->vol_list.busy);
8815 dp->vol_list.busy = 0;
8816 CV_BROADCAST(&dp->vol_list.cv);
8820 * wait for all asynchronous operations on a VByPList to complete.
8822 * @param[in] dp pointer to disk partition object
8824 * @pre VOL_LOCK is held.
8826 * @post disk partition's VByP list is quiescent
8830 * @note This interface should be called before any attempt to
8831 * traverse the VByPList. It is permissible for a thread
8832 * to gain exclusive access to the list, and then perform
8833 * latent operations on the list asynchronously wrt the
8836 * @warning if waiting is necessary, VOL_LOCK is dropped
8838 * @see VVByPListEndExclusive_r
8839 * @see VVByPListBeginExclusive_r
8841 * @internal volume package internal use only.
8844 VVByPListWait_r(struct DiskPartition64 * dp)
8846 while (dp->vol_list.busy) {
8847 VOL_CV_WAIT(&dp->vol_list.cv);
8850 #endif /* AFS_DEMAND_ATTACH_FS */
8852 /***************************************************/
8853 /* Volume Cache Statistics routines */
8854 /***************************************************/
8857 VPrintCacheStats_r(void)
8859 struct VnodeClassInfo *vcp;
8860 vcp = &VnodeClassInfo[vLarge];
8861 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);
8862 vcp = &VnodeClassInfo[vSmall];
8863 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);
8864 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8865 "%"AFS_INT64_FMT" replacements\n",
8866 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8870 VPrintCacheStats(void)
8873 VPrintCacheStats_r();
8877 #ifdef AFS_DEMAND_ATTACH_FS
8879 UInt64ToDouble(afs_uint64 * x)
8881 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8883 SplitInt64(*x, h, l);
8884 return (((double)h) * c32) + ((double) l);
8888 DoubleToPrintable(double x, char * buf, int len)
8890 static double billion = 1000000000.0;
8893 y[0] = (afs_uint32) (x / (billion * billion));
8894 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8895 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8898 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8900 snprintf(buf, len, "%d%09d", y[1], y[2]);
8902 snprintf(buf, len, "%d", y[2]);
8908 struct VLRUExtStatsEntry {
8912 struct VLRUExtStats {
8918 } queue_info[VLRU_QUEUE_INVALID];
8919 struct VLRUExtStatsEntry * vec;
8923 * add a 256-entry fudge factor onto the vector in case state changes
8924 * out from under us.
8926 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8929 * collect extended statistics for the VLRU subsystem.
8931 * @param[out] stats pointer to stats structure to be populated
8932 * @param[in] nvols number of volumes currently known to exist
8934 * @pre VOL_LOCK held
8936 * @post stats->vec allocated and populated
8938 * @return operation status
8943 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8945 afs_uint32 cur, idx, len;
8946 struct rx_queue * qp, * nqp;
8948 struct VLRUExtStatsEntry * vec;
8950 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8951 vec = stats->vec = calloc(len,
8952 sizeof(struct VLRUExtStatsEntry));
8958 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8959 VLRU_Wait_r(&volume_LRU.q[idx]);
8960 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8963 stats->queue_info[idx].start = cur;
8965 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8967 /* out of space in vec */
8970 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8971 vec[cur].volid = vp->hashid;
8975 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8978 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8986 #define ENUMTOSTRING(en) #en
8987 #define ENUMCASE(en) \
8988 case en: return ENUMTOSTRING(en)
8991 vlru_idx_to_string(int idx)
8994 ENUMCASE(VLRU_QUEUE_NEW);
8995 ENUMCASE(VLRU_QUEUE_MID);
8996 ENUMCASE(VLRU_QUEUE_OLD);
8997 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8998 ENUMCASE(VLRU_QUEUE_HELD);
8999 ENUMCASE(VLRU_QUEUE_INVALID);
9001 return "**UNKNOWN**";
9006 VPrintExtendedCacheStats_r(int flags)
9009 afs_uint32 vol_sum = 0;
9016 struct stats looks, gets, reorders, len;
9017 struct stats ch_looks, ch_gets, ch_reorders;
9019 VolumeHashChainHead *head;
9021 struct VLRUExtStats vlru_stats;
9023 /* zero out stats */
9024 memset(&looks, 0, sizeof(struct stats));
9025 memset(&gets, 0, sizeof(struct stats));
9026 memset(&reorders, 0, sizeof(struct stats));
9027 memset(&len, 0, sizeof(struct stats));
9028 memset(&ch_looks, 0, sizeof(struct stats));
9029 memset(&ch_gets, 0, sizeof(struct stats));
9030 memset(&ch_reorders, 0, sizeof(struct stats));
9032 for (i = 0; i < VolumeHashTable.Size; i++) {
9033 head = &VolumeHashTable.Table[i];
9036 VHashBeginExclusive_r(head);
9039 ch_looks.sum = UInt64ToDouble(&head->looks);
9040 ch_gets.sum = UInt64ToDouble(&head->gets);
9041 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9043 /* update global statistics */
9045 looks.sum += ch_looks.sum;
9046 gets.sum += ch_gets.sum;
9047 reorders.sum += ch_reorders.sum;
9048 len.sum += (double)head->len;
9049 vol_sum += head->len;
9052 len.min = (double) head->len;
9053 len.max = (double) head->len;
9054 looks.min = ch_looks.sum;
9055 looks.max = ch_looks.sum;
9056 gets.min = ch_gets.sum;
9057 gets.max = ch_gets.sum;
9058 reorders.min = ch_reorders.sum;
9059 reorders.max = ch_reorders.sum;
9061 if (((double)head->len) < len.min)
9062 len.min = (double) head->len;
9063 if (((double)head->len) > len.max)
9064 len.max = (double) head->len;
9065 if (ch_looks.sum < looks.min)
9066 looks.min = ch_looks.sum;
9067 else if (ch_looks.sum > looks.max)
9068 looks.max = ch_looks.sum;
9069 if (ch_gets.sum < gets.min)
9070 gets.min = ch_gets.sum;
9071 else if (ch_gets.sum > gets.max)
9072 gets.max = ch_gets.sum;
9073 if (ch_reorders.sum < reorders.min)
9074 reorders.min = ch_reorders.sum;
9075 else if (ch_reorders.sum > reorders.max)
9076 reorders.max = ch_reorders.sum;
9080 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9081 /* compute detailed per-chain stats */
9082 struct stats hdr_loads, hdr_gets;
9083 double v_looks, v_loads, v_gets;
9085 /* initialize stats with data from first element in chain */
9086 vp = queue_First(head, Volume);
9087 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9088 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9089 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9090 ch_gets.min = ch_gets.max = v_looks;
9091 hdr_loads.min = hdr_loads.max = v_loads;
9092 hdr_gets.min = hdr_gets.max = v_gets;
9093 hdr_loads.sum = hdr_gets.sum = 0;
9095 vp = queue_Next(vp, Volume);
9097 /* pull in stats from remaining elements in chain */
9098 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9099 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9100 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9101 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9103 hdr_loads.sum += v_loads;
9104 hdr_gets.sum += v_gets;
9106 if (v_looks < ch_gets.min)
9107 ch_gets.min = v_looks;
9108 else if (v_looks > ch_gets.max)
9109 ch_gets.max = v_looks;
9111 if (v_loads < hdr_loads.min)
9112 hdr_loads.min = v_loads;
9113 else if (v_loads > hdr_loads.max)
9114 hdr_loads.max = v_loads;
9116 if (v_gets < hdr_gets.min)
9117 hdr_gets.min = v_gets;
9118 else if (v_gets > hdr_gets.max)
9119 hdr_gets.max = v_gets;
9122 /* compute per-chain averages */
9123 ch_gets.avg = ch_gets.sum / ((double)head->len);
9124 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9125 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9127 /* dump per-chain stats */
9128 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9130 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9131 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9132 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9133 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9134 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9135 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9136 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9137 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9138 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9139 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9140 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9141 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9142 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9143 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9144 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9145 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9146 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9147 } else if (flags & VOL_STATS_PER_CHAIN) {
9148 /* dump simple per-chain stats */
9149 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9151 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9152 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9153 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9157 VHashEndExclusive_r(head);
9162 /* compute global averages */
9163 len.avg = len.sum / ((double)VolumeHashTable.Size);
9164 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9165 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9166 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9168 /* dump global stats */
9169 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9170 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9171 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9172 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9173 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9174 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9175 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9176 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9177 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9178 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9179 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9180 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9181 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9182 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9183 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9184 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9185 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9186 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9187 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9188 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9189 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9191 /* print extended disk related statistics */
9193 struct DiskPartition64 * diskP;
9194 afs_uint32 vol_count[VOLMAXPARTS+1];
9195 byte part_exists[VOLMAXPARTS+1];
9199 memset(vol_count, 0, sizeof(vol_count));
9200 memset(part_exists, 0, sizeof(part_exists));
9204 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9206 vol_count[id] = diskP->vol_list.len;
9207 part_exists[id] = 1;
9211 for (i = 0; i <= VOLMAXPARTS; i++) {
9212 if (part_exists[i]) {
9213 /* XXX while this is currently safe, it is a violation
9214 * of the VGetPartitionById_r interface contract. */
9215 diskP = VGetPartitionById_r(i, 0);
9217 Log("Partition %s has %d online volumes\n",
9218 VPartitionPath(diskP), diskP->vol_list.len);
9225 /* print extended VLRU statistics */
9226 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9227 afs_uint32 idx, cur, lpos;
9232 Log("VLRU State Dump:\n\n");
9234 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9235 Log("\t%s:\n", vlru_idx_to_string(idx));
9238 for (cur = vlru_stats.queue_info[idx].start;
9239 cur < vlru_stats.queue_info[idx].len;
9241 line[lpos++] = vlru_stats.vec[cur].volid;
9243 Log("\t\t%u, %u, %u, %u, %u,\n",
9244 line[0], line[1], line[2], line[3], line[4]);
9253 Log("\t\t%u, %u, %u, %u, %u\n",
9254 line[0], line[1], line[2], line[3], line[4]);
9259 free(vlru_stats.vec);
9266 VPrintExtendedCacheStats(int flags)
9269 VPrintExtendedCacheStats_r(flags);
9272 #endif /* AFS_DEMAND_ATTACH_FS */
9275 VCanScheduleSalvage(void)
9277 return vol_opts.canScheduleSalvage;
9283 return vol_opts.canUseFSSYNC;
9287 VCanUseSALVSYNC(void)
9289 return vol_opts.canUseSALVSYNC;
9293 VCanUnsafeAttach(void)
9295 return vol_opts.unsafe_attach;