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 /* this parameter needs to be tunable at runtime.
184 * 128 was really inadequate for largish servers -- at 16384 volumes this
185 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
186 * talk about bad spatial locality...
188 * an AVL or splay tree might work a lot better, but we'll just increase
189 * the default hash table size for now
191 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
192 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
193 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
196 * turn volume hash chains into partially ordered lists.
197 * when the threshold is exceeded between two adjacent elements,
198 * perform a chain rebalancing operation.
200 * keep the threshold high in order to keep cache line invalidates
201 * low "enough" on SMPs
203 #define VOLUME_HASH_REORDER_THRESHOLD 200
206 * when possible, don't just reorder single elements, but reorder
207 * entire chains of elements at once. a chain of elements that
208 * exceed the element previous to the pivot by at least CHAIN_THRESH
209 * accesses are moved in front of the chain whose elements have at
210 * least CHAIN_THRESH less accesses than the pivot element
212 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
214 #include "rx/rx_queue.h"
217 VolumeHashTable_t VolumeHashTable = {
218 DEFAULT_VOLUME_HASH_SIZE,
219 DEFAULT_VOLUME_HASH_MASK,
224 static void VInitVolumeHash(void);
228 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
232 afs_int32 ffs_tmp = x;
236 for (ffs_i = 1;; ffs_i++) {
243 #endif /* !AFS_HAVE_FFS */
245 #ifdef AFS_PTHREAD_ENV
247 * disk partition queue element
249 typedef struct diskpartition_queue_t {
250 struct rx_queue queue; /**< queue header */
251 struct DiskPartition64 *diskP; /**< disk partition table entry */
252 } diskpartition_queue_t;
254 #ifndef AFS_DEMAND_ATTACH_FS
256 typedef struct vinitvolumepackage_thread_t {
257 struct rx_queue queue;
258 pthread_cond_t thread_done_cv;
259 int n_threads_complete;
260 } vinitvolumepackage_thread_t;
261 static void * VInitVolumePackageThread(void * args);
263 #else /* !AFS_DEMAND_ATTTACH_FS */
264 #define VINIT_BATCH_MAX_SIZE 512
267 * disk partition work queue
269 struct partition_queue {
270 struct rx_queue head; /**< diskpartition_queue_t queue */
271 pthread_mutex_t mutex;
276 * volumes parameters for preattach
278 struct volume_init_batch {
279 struct rx_queue queue; /**< queue header */
280 int thread; /**< posting worker thread */
281 int last; /**< indicates thread is done */
282 int size; /**< number of volume ids in batch */
283 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
287 * volume parameters work queue
289 struct volume_init_queue {
290 struct rx_queue head; /**< volume_init_batch queue */
291 pthread_mutex_t mutex;
296 * volume init worker thread parameters
298 struct vinitvolumepackage_thread_param {
299 int nthreads; /**< total number of worker threads */
300 int thread; /**< thread number for this worker thread */
301 struct partition_queue *pq; /**< queue partitions to scan */
302 struct volume_init_queue *vq; /**< queue of volume to preattach */
305 static void *VInitVolumePackageThread(void *args);
306 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
307 static VolId VInitNextVolumeId(DIR *dirp);
308 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
310 #endif /* !AFS_DEMAND_ATTACH_FS */
311 #endif /* AFS_PTHREAD_ENV */
313 #ifndef AFS_DEMAND_ATTACH_FS
314 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
315 int * nAttached, int * nUnattached);
316 #endif /* AFS_DEMAND_ATTACH_FS */
319 #ifdef AFS_DEMAND_ATTACH_FS
320 /* demand attach fileserver extensions */
323 * in the future we will support serialization of VLRU state into the fs_state
326 * these structures are the beginning of that effort
328 struct VLRU_DiskHeader {
329 struct versionStamp stamp; /* magic and structure version number */
330 afs_uint32 mtime; /* time of dump to disk */
331 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
334 struct VLRU_DiskEntry {
335 afs_uint32 vid; /* volume ID */
336 afs_uint32 idx; /* generation */
337 afs_uint32 last_get; /* timestamp of last get */
340 struct VLRU_StartupQueue {
341 struct VLRU_DiskEntry * entry;
346 typedef struct vshutdown_thread_t {
348 pthread_mutex_t lock;
350 pthread_cond_t master_cv;
352 int n_threads_complete;
354 int schedule_version;
357 byte n_parts_done_pass;
358 byte part_thread_target[VOLMAXPARTS+1];
359 byte part_done_pass[VOLMAXPARTS+1];
360 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
361 int stats[4][VOLMAXPARTS+1];
362 } vshutdown_thread_t;
363 static void * VShutdownThread(void * args);
366 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
367 static int VCheckFree(Volume * vp);
370 static void AddVolumeToVByPList_r(Volume * vp);
371 static void DeleteVolumeFromVByPList_r(Volume * vp);
372 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
373 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
374 static void VVByPListWait_r(struct DiskPartition64 * dp);
376 /* online salvager */
377 static int VCheckSalvage(Volume * vp);
378 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
379 static int VScheduleSalvage_r(Volume * vp);
382 /* Volume hash table */
383 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
384 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
385 static void VHashEndExclusive_r(VolumeHashChainHead * head);
386 static void VHashWait_r(VolumeHashChainHead * head);
389 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
390 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
391 struct rx_queue ** idx);
392 static void ShutdownController(vshutdown_thread_t * params);
393 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
396 static void VLRU_ComputeConstants(void);
397 static void VInitVLRU(void);
398 static void VLRU_Init_Node_r(Volume * vp);
399 static void VLRU_Add_r(Volume * vp);
400 static void VLRU_Delete_r(Volume * vp);
401 static void VLRU_UpdateAccess_r(Volume * vp);
402 static void * VLRU_ScannerThread(void * args);
403 static void VLRU_Scan_r(int idx);
404 static void VLRU_Promote_r(int idx);
405 static void VLRU_Demote_r(int idx);
406 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
409 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
410 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
411 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
414 pthread_key_t VThread_key;
415 VThreadOptions_t VThread_defaults = {
416 0 /**< allow salvsync */
418 #endif /* AFS_DEMAND_ATTACH_FS */
421 struct Lock vol_listLock; /* Lock obtained when listing volumes:
422 * prevents a volume from being missed
423 * if the volume is attached during a
427 /* Common message used when the volume goes off line */
428 char *VSalvageMessage =
429 "Files in this volume are currently unavailable; call operations";
431 int VInit; /* 0 - uninitialized,
432 * 1 - initialized but not all volumes have been attached,
433 * 2 - initialized and all volumes have been attached,
434 * 3 - initialized, all volumes have been attached, and
435 * VConnectFS() has completed. */
437 static int vinit_attach_abort = 0;
439 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
440 * used to stamp volume headers and in-core
441 * vnodes. When the volume goes on-line the
442 * vnode will be invalidated
443 * access only with VOL_LOCK held */
448 /***************************************************/
449 /* Startup routines */
450 /***************************************************/
452 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
453 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
454 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
458 * assign default values to a VolumePackageOptions struct.
460 * Always call this on a VolumePackageOptions struct first, then set any
461 * specific options you want, then call VInitVolumePackage2.
463 * @param[in] pt caller's program type
464 * @param[out] opts volume package options
467 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
469 opts->nLargeVnodes = opts->nSmallVnodes = 5;
472 opts->canScheduleSalvage = 0;
473 opts->canUseFSSYNC = 0;
474 opts->canUseSALVSYNC = 0;
476 opts->interrupt_rxcall = NULL;
477 opts->offline_timeout = -1;
478 opts->offline_shutdown_timeout = -1;
479 opts->usage_threshold = 128;
480 opts->usage_rate_limit = 5;
483 opts->unsafe_attach = 1;
484 #else /* !FAST_RESTART */
485 opts->unsafe_attach = 0;
486 #endif /* !FAST_RESTART */
490 opts->canScheduleSalvage = 1;
491 opts->canUseSALVSYNC = 1;
495 opts->canUseFSSYNC = 1;
499 opts->nLargeVnodes = 0;
500 opts->nSmallVnodes = 0;
502 opts->canScheduleSalvage = 1;
503 opts->canUseFSSYNC = 1;
513 * Set VInit to a certain value, and signal waiters.
515 * @param[in] value the value to set VInit to
520 VSetVInit_r(int value)
523 CV_BROADCAST(&vol_vinit_cond);
527 VLogOfflineTimeout(const char *type, afs_int32 timeout)
533 Log("VInitVolumePackage: Interrupting clients accessing %s "
534 "immediately\n", type);
536 Log("VInitVolumePackage: Interrupting clients accessing %s "
537 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
542 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
544 int errors = 0; /* Number of errors while finding vice partitions. */
549 #ifndef AFS_PTHREAD_ENV
550 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
551 Log("VInitVolumePackage: offline_timeout and/or "
552 "offline_shutdown_timeout was specified, but the volume package "
553 "does not support these for LWP builds\n");
557 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
558 VLogOfflineTimeout("volumes going offline during shutdown",
559 opts->offline_shutdown_timeout);
561 memset(&VStats, 0, sizeof(VStats));
562 VStats.hdr_cache_size = 200;
564 VInitPartitionPackage();
566 #ifdef AFS_DEMAND_ATTACH_FS
567 if (programType == fileServer) {
570 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
572 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
575 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
576 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
577 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
578 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
579 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
580 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
581 #ifndef AFS_PTHREAD_ENV
583 #endif /* AFS_PTHREAD_ENV */
584 Lock_Init(&vol_listLock);
586 srandom(time(0)); /* For VGetVolumeInfo */
588 #ifdef AFS_DEMAND_ATTACH_FS
589 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
590 #endif /* AFS_DEMAND_ATTACH_FS */
592 /* Ok, we have done enough initialization that fileserver can
593 * start accepting calls, even though the volumes may not be
594 * available just yet.
598 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
599 if (programType == salvageServer) {
602 #endif /* AFS_DEMAND_ATTACH_FS */
603 #ifdef FSSYNC_BUILD_SERVER
604 if (programType == fileServer) {
608 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
609 if (VCanUseSALVSYNC()) {
610 /* establish a connection to the salvager at this point */
611 osi_Assert(VConnectSALV() != 0);
613 #endif /* AFS_DEMAND_ATTACH_FS */
615 if (opts->volcache > VStats.hdr_cache_size)
616 VStats.hdr_cache_size = opts->volcache;
617 VInitVolumeHeaderCache(VStats.hdr_cache_size);
619 VInitVnodes(vLarge, opts->nLargeVnodes);
620 VInitVnodes(vSmall, opts->nSmallVnodes);
623 errors = VAttachPartitions();
627 if (programType != fileServer) {
628 errors = VInitAttachVolumes(programType);
634 #ifdef FSSYNC_BUILD_CLIENT
635 if (VCanUseFSSYNC()) {
637 #ifdef AFS_DEMAND_ATTACH_FS
638 if (programType == salvageServer) {
639 Log("Unable to connect to file server; aborted\n");
642 #endif /* AFS_DEMAND_ATTACH_FS */
643 Log("Unable to connect to file server; will retry at need\n");
646 #endif /* FSSYNC_BUILD_CLIENT */
651 #if !defined(AFS_PTHREAD_ENV)
653 * Attach volumes in vice partitions
655 * @param[in] pt calling program type
658 * @note This is the original, non-threaded version of attach parititions.
660 * @post VInit state is 2
663 VInitAttachVolumes(ProgramType pt)
665 osi_Assert(VInit==1);
666 if (pt == fileServer) {
667 struct DiskPartition64 *diskP;
668 /* Attach all the volumes in this partition */
669 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
670 int nAttached = 0, nUnattached = 0;
671 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
675 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
676 LWP_NoYieldSignal(VInitAttachVolumes);
680 #endif /* !AFS_PTHREAD_ENV */
682 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
684 * Attach volumes in vice partitions
686 * @param[in] pt calling program type
689 * @note Threaded version of attach parititions.
691 * @post VInit state is 2
694 VInitAttachVolumes(ProgramType pt)
696 osi_Assert(VInit==1);
697 if (pt == fileServer) {
698 struct DiskPartition64 *diskP;
699 struct vinitvolumepackage_thread_t params;
700 struct diskpartition_queue_t * dpq;
701 int i, threads, parts;
703 pthread_attr_t attrs;
705 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
707 params.n_threads_complete = 0;
709 /* create partition work queue */
710 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
711 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
712 osi_Assert(dpq != NULL);
714 queue_Append(¶ms,dpq);
717 threads = min(parts, vol_attach_threads);
720 /* spawn off a bunch of initialization threads */
721 osi_Assert(pthread_attr_init(&attrs) == 0);
722 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
724 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
725 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
729 for (i=0; i < threads; i++) {
732 osi_Assert(pthread_create
733 (&tid, &attrs, &VInitVolumePackageThread,
735 AFS_SIGSET_RESTORE();
738 while(params.n_threads_complete < threads) {
739 VOL_CV_WAIT(¶ms.thread_done_cv);
743 osi_Assert(pthread_attr_destroy(&attrs) == 0);
745 /* if we're only going to run one init thread, don't bother creating
747 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
748 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
751 VInitVolumePackageThread(¶ms);
754 CV_DESTROY(¶ms.thread_done_cv);
757 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
758 CV_BROADCAST(&vol_init_attach_cond);
764 VInitVolumePackageThread(void * args) {
766 struct DiskPartition64 *diskP;
767 struct vinitvolumepackage_thread_t * params;
768 struct diskpartition_queue_t * dpq;
770 params = (vinitvolumepackage_thread_t *) args;
774 /* Attach all the volumes in this partition */
775 while (queue_IsNotEmpty(params)) {
776 int nAttached = 0, nUnattached = 0;
778 if (vinit_attach_abort) {
779 Log("Aborting initialization\n");
783 dpq = queue_First(params,diskpartition_queue_t);
789 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
795 params->n_threads_complete++;
796 CV_SIGNAL(¶ms->thread_done_cv);
800 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
802 #if defined(AFS_DEMAND_ATTACH_FS)
804 * Attach volumes in vice partitions
806 * @param[in] pt calling program type
809 * @note Threaded version of attach partitions.
811 * @post VInit state is 2
814 VInitAttachVolumes(ProgramType pt)
816 osi_Assert(VInit==1);
817 if (pt == fileServer) {
819 struct DiskPartition64 *diskP;
820 struct partition_queue pq;
821 struct volume_init_queue vq;
823 int i, threads, parts;
825 pthread_attr_t attrs;
827 /* create partition work queue */
829 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
830 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
831 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
832 struct diskpartition_queue_t *dp;
833 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
834 osi_Assert(dp != NULL);
836 queue_Append(&pq, dp);
839 /* number of worker threads; at least one, not to exceed the number of partitions */
840 threads = min(parts, vol_attach_threads);
842 /* create volume work queue */
844 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
845 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
847 osi_Assert(pthread_attr_init(&attrs) == 0);
848 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
850 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
851 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
854 /* create threads to scan disk partitions. */
855 for (i=0; i < threads; i++) {
856 struct vinitvolumepackage_thread_param *params;
859 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
863 params->nthreads = threads;
864 params->thread = i+1;
867 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
868 AFS_SIGSET_RESTORE();
871 VInitPreAttachVolumes(threads, &vq);
873 osi_Assert(pthread_attr_destroy(&attrs) == 0);
875 MUTEX_DESTROY(&pq.mutex);
877 MUTEX_DESTROY(&vq.mutex);
881 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
882 CV_BROADCAST(&vol_init_attach_cond);
889 * Volume package initialization worker thread. Scan partitions for volume
890 * header files. Gather batches of volume ids and dispatch them to
891 * the main thread to be preattached. The volume preattachement is done
892 * in the main thread to avoid global volume lock contention.
895 VInitVolumePackageThread(void *args)
897 struct vinitvolumepackage_thread_param *params;
898 struct DiskPartition64 *partition;
899 struct partition_queue *pq;
900 struct volume_init_queue *vq;
901 struct volume_init_batch *vb;
904 params = (struct vinitvolumepackage_thread_param *)args;
910 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
912 vb->thread = params->thread;
916 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
917 while((partition = VInitNextPartition(pq))) {
921 Log("Partition %s: pre-attaching volumes\n", partition->name);
922 dirp = opendir(VPartitionPath(partition));
924 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
927 while ((vid = VInitNextVolumeId(dirp))) {
928 Volume *vp = (Volume*)malloc(sizeof(Volume));
930 memset(vp, 0, sizeof(Volume));
931 vp->device = partition->device;
932 vp->partition = partition;
934 queue_Init(&vp->vnode_list);
935 queue_Init(&vp->rx_call_list);
936 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
938 vb->batch[vb->size++] = vp;
939 if (vb->size == VINIT_BATCH_MAX_SIZE) {
940 MUTEX_ENTER(&vq->mutex);
941 queue_Append(vq, vb);
942 CV_BROADCAST(&vq->cv);
943 MUTEX_EXIT(&vq->mutex);
945 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
947 vb->thread = params->thread;
956 MUTEX_ENTER(&vq->mutex);
957 queue_Append(vq, vb);
958 CV_BROADCAST(&vq->cv);
959 MUTEX_EXIT(&vq->mutex);
961 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
967 * Read next element from the pre-populated partition list.
969 static struct DiskPartition64*
970 VInitNextPartition(struct partition_queue *pq)
972 struct DiskPartition64 *partition;
973 struct diskpartition_queue_t *dp; /* queue element */
975 if (vinit_attach_abort) {
976 Log("Aborting volume preattach thread.\n");
980 /* get next partition to scan */
981 MUTEX_ENTER(&pq->mutex);
982 if (queue_IsEmpty(pq)) {
983 MUTEX_EXIT(&pq->mutex);
986 dp = queue_First(pq, diskpartition_queue_t);
988 MUTEX_EXIT(&pq->mutex);
991 osi_Assert(dp->diskP);
993 partition = dp->diskP;
999 * Find next volume id on the partition.
1002 VInitNextVolumeId(DIR *dirp)
1008 while((d = readdir(dirp))) {
1009 if (vinit_attach_abort) {
1010 Log("Aborting volume preattach thread.\n");
1013 ext = strrchr(d->d_name, '.');
1014 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1015 vid = VolumeNumber(d->d_name);
1019 Log("Warning: bogus volume header file: %s\n", d->d_name);
1026 * Preattach volumes in batches to avoid lock contention.
1029 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1031 struct volume_init_batch *vb;
1035 /* dequeue next volume */
1036 MUTEX_ENTER(&vq->mutex);
1037 if (queue_IsEmpty(vq)) {
1038 CV_WAIT(&vq->cv, &vq->mutex);
1040 vb = queue_First(vq, volume_init_batch);
1042 MUTEX_EXIT(&vq->mutex);
1046 for (i = 0; i<vb->size; i++) {
1052 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1054 Log("Error looking up volume, code=%d\n", ec);
1057 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1060 /* put pre-attached volume onto the hash table
1061 * and bring it up to the pre-attached state */
1062 AddVolumeToHashTable(vp, vp->hashid);
1063 AddVolumeToVByPList_r(vp);
1064 VLRU_Init_Node_r(vp);
1065 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1078 #endif /* AFS_DEMAND_ATTACH_FS */
1080 #if !defined(AFS_DEMAND_ATTACH_FS)
1082 * attach all volumes on a given disk partition
1085 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1091 Log("Partition %s: attaching volumes\n", diskP->name);
1092 dirp = opendir(VPartitionPath(diskP));
1094 Log("opendir on Partition %s failed!\n", diskP->name);
1098 while ((dp = readdir(dirp))) {
1100 p = strrchr(dp->d_name, '.');
1102 if (vinit_attach_abort) {
1103 Log("Partition %s: abort attach volumes\n", diskP->name);
1107 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1110 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1112 (*(vp ? nAttached : nUnattached))++;
1113 if (error == VOFFLINE)
1114 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1115 else if (LogLevel >= 5) {
1116 Log("Partition %s: attached volume %d (%s)\n",
1117 diskP->name, VolumeNumber(dp->d_name),
1126 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1131 #endif /* !AFS_DEMAND_ATTACH_FS */
1133 /***************************************************/
1134 /* Shutdown routines */
1135 /***************************************************/
1139 * highly multithreaded volume package shutdown
1141 * with the demand attach fileserver extensions,
1142 * VShutdown has been modified to be multithreaded.
1143 * In order to achieve optimal use of many threads,
1144 * the shutdown code involves one control thread and
1145 * n shutdown worker threads. The control thread
1146 * periodically examines the number of volumes available
1147 * for shutdown on each partition, and produces a worker
1148 * thread allocation schedule. The idea is to eliminate
1149 * redundant scheduling computation on the workers by
1150 * having a single master scheduler.
1152 * The scheduler's objectives are:
1154 * each partition with volumes remaining gets allocated
1155 * at least 1 thread (assuming sufficient threads)
1157 * threads are allocated proportional to the number of
1158 * volumes remaining to be offlined. This ensures that
1159 * the OS I/O scheduler has many requests to elevator
1160 * seek on partitions that will (presumably) take the
1161 * longest amount of time (from now) to finish shutdown
1162 * (3) keep threads busy
1163 * when there are extra threads, they are assigned to
1164 * partitions using a simple round-robin algorithm
1166 * In the future, we may wish to add the ability to adapt
1167 * to the relative performance patterns of each disk
1172 * multi-step shutdown process
1174 * demand attach shutdown is a four-step process. Each
1175 * shutdown "pass" shuts down increasingly more difficult
1176 * volumes. The main purpose is to achieve better cache
1177 * utilization during shutdown.
1180 * shutdown volumes in the unattached, pre-attached
1183 * shutdown attached volumes with cached volume headers
1185 * shutdown all volumes in non-exclusive states
1187 * shutdown all remaining volumes
1190 #ifdef AFS_DEMAND_ATTACH_FS
1196 struct DiskPartition64 * diskP;
1197 struct diskpartition_queue_t * dpq;
1198 vshutdown_thread_t params;
1200 pthread_attr_t attrs;
1202 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1205 Log("VShutdown: aborting attach volumes\n");
1206 vinit_attach_abort = 1;
1207 VOL_CV_WAIT(&vol_init_attach_cond);
1210 for (params.n_parts=0, diskP = DiskPartitionList;
1211 diskP; diskP = diskP->next, params.n_parts++);
1213 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1214 params.n_parts, params.n_parts > 1 ? "s" : "");
1216 vol_shutting_down = 1;
1218 if (vol_attach_threads > 1) {
1219 /* prepare for parallel shutdown */
1220 params.n_threads = vol_attach_threads;
1221 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1222 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1223 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1224 osi_Assert(pthread_attr_init(&attrs) == 0);
1225 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1226 queue_Init(¶ms);
1228 /* setup the basic partition information structures for
1229 * parallel shutdown */
1230 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1232 struct rx_queue * qp, * nqp;
1236 VVByPListWait_r(diskP);
1237 VVByPListBeginExclusive_r(diskP);
1240 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1241 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1245 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1246 VPartitionPath(diskP), count);
1249 /* build up the pass 0 shutdown work queue */
1250 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1251 osi_Assert(dpq != NULL);
1253 queue_Prepend(¶ms, dpq);
1255 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1258 Log("VShutdown: beginning parallel fileserver shutdown\n");
1259 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1260 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1262 /* do pass 0 shutdown */
1263 MUTEX_ENTER(¶ms.lock);
1264 for (i=0; i < params.n_threads; i++) {
1265 osi_Assert(pthread_create
1266 (&tid, &attrs, &VShutdownThread,
1270 /* wait for all the pass 0 shutdowns to complete */
1271 while (params.n_threads_complete < params.n_threads) {
1272 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1274 params.n_threads_complete = 0;
1276 CV_BROADCAST(¶ms.cv);
1277 MUTEX_EXIT(¶ms.lock);
1279 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1280 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1282 /* run the parallel shutdown scheduler. it will drop the glock internally */
1283 ShutdownController(¶ms);
1285 /* wait for all the workers to finish pass 3 and terminate */
1286 while (params.pass < 4) {
1287 VOL_CV_WAIT(¶ms.cv);
1290 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1291 CV_DESTROY(¶ms.cv);
1292 CV_DESTROY(¶ms.master_cv);
1293 MUTEX_DESTROY(¶ms.lock);
1295 /* drop the VByPList exclusive reservations */
1296 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1297 VVByPListEndExclusive_r(diskP);
1298 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1299 VPartitionPath(diskP),
1300 params.stats[0][diskP->index],
1301 params.stats[1][diskP->index],
1302 params.stats[2][diskP->index],
1303 params.stats[3][diskP->index]);
1306 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1308 /* if we're only going to run one shutdown thread, don't bother creating
1310 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1312 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1313 VShutdownByPartition_r(diskP);
1317 Log("VShutdown: complete.\n");
1320 #else /* AFS_DEMAND_ATTACH_FS */
1330 Log("VShutdown: aborting attach volumes\n");
1331 vinit_attach_abort = 1;
1332 #ifdef AFS_PTHREAD_ENV
1333 VOL_CV_WAIT(&vol_init_attach_cond);
1335 LWP_WaitProcess(VInitAttachVolumes);
1336 #endif /* AFS_PTHREAD_ENV */
1339 Log("VShutdown: shutting down on-line volumes...\n");
1340 vol_shutting_down = 1;
1341 for (i = 0; i < VolumeHashTable.Size; i++) {
1342 /* try to hold first volume in the hash table */
1343 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1347 Log("VShutdown: Attempting to take volume %u offline.\n",
1350 /* next, take the volume offline (drops reference count) */
1351 VOffline_r(vp, "File server was shut down");
1355 Log("VShutdown: complete.\n");
1357 #endif /* AFS_DEMAND_ATTACH_FS */
1363 osi_Assert(VInit>0);
1370 * stop new activity (e.g. SALVSYNC) from occurring
1372 * Use this to make the volume package less busy; for example, during
1373 * shutdown. This doesn't actually shutdown/detach anything in the
1374 * volume package, but prevents certain processes from ocurring. For
1375 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1376 * could also use this to prevent new volume attachment, or prevent
1377 * other programs from checking out volumes, etc.
1382 #ifdef AFS_DEMAND_ATTACH_FS
1383 /* make sure we don't try to contact the salvageserver, since it may
1384 * not be around anymore */
1385 vol_disallow_salvsync = 1;
1389 #ifdef AFS_DEMAND_ATTACH_FS
1392 * shutdown control thread
1395 ShutdownController(vshutdown_thread_t * params)
1398 struct DiskPartition64 * diskP;
1400 vshutdown_thread_t shadow;
1402 ShutdownCreateSchedule(params);
1404 while ((params->pass < 4) &&
1405 (params->n_threads_complete < params->n_threads)) {
1406 /* recompute schedule once per second */
1408 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1412 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1413 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1414 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1415 shadow.n_threads_complete, shadow.n_parts_done_pass);
1416 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1418 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1420 diskP->vol_list.len,
1421 shadow.part_thread_target[id],
1422 shadow.part_done_pass[id],
1423 shadow.part_pass_head[id]);
1429 ShutdownCreateSchedule(params);
1433 /* create the shutdown thread work schedule.
1434 * this scheduler tries to implement fairness
1435 * by allocating at least 1 thread to each
1436 * partition with volumes to be shutdown,
1437 * and then it attempts to allocate remaining
1438 * threads based upon the amount of work left
1441 ShutdownCreateSchedule(vshutdown_thread_t * params)
1443 struct DiskPartition64 * diskP;
1444 int sum, thr_workload, thr_left;
1445 int part_residue[VOLMAXPARTS+1];
1448 /* compute the total number of outstanding volumes */
1450 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1451 sum += diskP->vol_list.len;
1454 params->schedule_version++;
1455 params->vol_remaining = sum;
1460 /* compute average per-thread workload */
1461 thr_workload = sum / params->n_threads;
1462 if (sum % params->n_threads)
1465 thr_left = params->n_threads;
1466 memset(&part_residue, 0, sizeof(part_residue));
1468 /* for fairness, give every partition with volumes remaining
1469 * at least one thread */
1470 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1472 if (diskP->vol_list.len) {
1473 params->part_thread_target[id] = 1;
1476 params->part_thread_target[id] = 0;
1480 if (thr_left && thr_workload) {
1481 /* compute length-weighted workloads */
1484 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1486 delta = (diskP->vol_list.len / thr_workload) -
1487 params->part_thread_target[id];
1491 if (delta < thr_left) {
1492 params->part_thread_target[id] += delta;
1495 params->part_thread_target[id] += thr_left;
1503 /* try to assign any leftover threads to partitions that
1504 * had volume lengths closer to needing thread_target+1 */
1505 int max_residue, max_id = 0;
1507 /* compute the residues */
1508 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1510 part_residue[id] = diskP->vol_list.len -
1511 (params->part_thread_target[id] * thr_workload);
1514 /* now try to allocate remaining threads to partitions with the
1515 * highest residues */
1518 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1520 if (part_residue[id] > max_residue) {
1521 max_residue = part_residue[id];
1530 params->part_thread_target[max_id]++;
1532 part_residue[max_id] = 0;
1537 /* punt and give any remaining threads equally to each partition */
1539 if (thr_left >= params->n_parts) {
1540 alloc = thr_left / params->n_parts;
1541 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1543 params->part_thread_target[id] += alloc;
1548 /* finish off the last of the threads */
1549 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1551 params->part_thread_target[id]++;
1557 /* worker thread for parallel shutdown */
1559 VShutdownThread(void * args)
1561 vshutdown_thread_t * params;
1562 int found, pass, schedule_version_save, count;
1563 struct DiskPartition64 *diskP;
1564 struct diskpartition_queue_t * dpq;
1567 params = (vshutdown_thread_t *) args;
1569 /* acquire the shutdown pass 0 lock */
1570 MUTEX_ENTER(¶ms->lock);
1572 /* if there's still pass 0 work to be done,
1573 * get a work entry, and do a pass 0 shutdown */
1574 if (queue_IsNotEmpty(params)) {
1575 dpq = queue_First(params, diskpartition_queue_t);
1577 MUTEX_EXIT(¶ms->lock);
1583 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1585 params->stats[0][diskP->index] = count;
1586 MUTEX_ENTER(¶ms->lock);
1589 params->n_threads_complete++;
1590 if (params->n_threads_complete == params->n_threads) {
1591 /* notify control thread that all workers have completed pass 0 */
1592 CV_SIGNAL(¶ms->master_cv);
1594 while (params->pass == 0) {
1595 CV_WAIT(¶ms->cv, ¶ms->lock);
1599 MUTEX_EXIT(¶ms->lock);
1602 pass = params->pass;
1603 osi_Assert(pass > 0);
1605 /* now escalate through the more complicated shutdowns */
1607 schedule_version_save = params->schedule_version;
1609 /* find a disk partition to work on */
1610 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1612 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1613 params->part_thread_target[id]--;
1620 /* hmm. for some reason the controller thread couldn't find anything for
1621 * us to do. let's see if there's anything we can do */
1622 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1624 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1627 } else if (!params->part_done_pass[id]) {
1628 params->part_done_pass[id] = 1;
1629 params->n_parts_done_pass++;
1631 Log("VShutdown: done shutting down volumes on partition %s.\n",
1632 VPartitionPath(diskP));
1638 /* do work on this partition until either the controller
1639 * creates a new schedule, or we run out of things to do
1640 * on this partition */
1643 while (!params->part_done_pass[id] &&
1644 (schedule_version_save == params->schedule_version)) {
1645 /* ShutdownVolumeWalk_r will drop the glock internally */
1646 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1647 if (!params->part_done_pass[id]) {
1648 params->part_done_pass[id] = 1;
1649 params->n_parts_done_pass++;
1651 Log("VShutdown: done shutting down volumes on partition %s.\n",
1652 VPartitionPath(diskP));
1660 params->stats[pass][id] += count;
1662 /* ok, everyone is done this pass, proceed */
1665 params->n_threads_complete++;
1666 while (params->pass == pass) {
1667 if (params->n_threads_complete == params->n_threads) {
1668 /* we are the last thread to complete, so we will
1669 * reinitialize worker pool state for the next pass */
1670 params->n_threads_complete = 0;
1671 params->n_parts_done_pass = 0;
1673 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1675 params->part_done_pass[id] = 0;
1676 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1679 /* compute a new thread schedule before releasing all the workers */
1680 ShutdownCreateSchedule(params);
1682 /* wake up all the workers */
1683 CV_BROADCAST(¶ms->cv);
1686 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1687 pass, params->n_threads, params->n_parts);
1690 VOL_CV_WAIT(¶ms->cv);
1693 pass = params->pass;
1707 /* shut down all volumes on a given disk partition
1709 * note that this function will not allow mp-fast
1710 * shutdown of a partition */
1712 VShutdownByPartition_r(struct DiskPartition64 * dp)
1718 /* wait for other exclusive ops to finish */
1719 VVByPListWait_r(dp);
1721 /* begin exclusive access */
1722 VVByPListBeginExclusive_r(dp);
1724 /* pick the low-hanging fruit first,
1725 * then do the complicated ones last
1726 * (has the advantage of keeping
1727 * in-use volumes up until the bitter end) */
1728 for (pass = 0, total=0; pass < 4; pass++) {
1729 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1730 total += pass_stats[pass];
1733 /* end exclusive access */
1734 VVByPListEndExclusive_r(dp);
1736 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1737 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1742 /* internal shutdown functionality
1744 * for multi-pass shutdown:
1745 * 0 to only "shutdown" {pre,un}attached and error state volumes
1746 * 1 to also shutdown attached volumes w/ volume header loaded
1747 * 2 to also shutdown attached volumes w/o volume header loaded
1748 * 3 to also shutdown exclusive state volumes
1750 * caller MUST hold exclusive access on the hash chain
1751 * because we drop vol_glock_mutex internally
1753 * this function is reentrant for passes 1--3
1754 * (e.g. multiple threads can cooperate to
1755 * shutdown a partition mp-fast)
1757 * pass 0 is not scaleable because the volume state data is
1758 * synchronized by vol_glock mutex, and the locking overhead
1759 * is too high to drop the lock long enough to do linked list
1763 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1765 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1768 while (ShutdownVolumeWalk_r(dp, pass, &q))
1774 /* conditionally shutdown one volume on partition dp
1775 * returns 1 if a volume was shutdown in this pass,
1778 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1779 struct rx_queue ** idx)
1781 struct rx_queue *qp, *nqp;
1786 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1787 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1791 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1792 (V_attachState(vp) != VOL_STATE_ERROR) &&
1793 (V_attachState(vp) != VOL_STATE_DELETED) &&
1794 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1798 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1799 (vp->header == NULL)) {
1803 if (VIsExclusiveState(V_attachState(vp))) {
1808 DeleteVolumeFromVByPList_r(vp);
1809 VShutdownVolume_r(vp);
1819 * shutdown a specific volume
1821 /* caller MUST NOT hold a heavyweight ref on vp */
1823 VShutdownVolume_r(Volume * vp)
1827 VCreateReservation_r(vp);
1829 if (LogLevel >= 5) {
1830 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1831 vp->hashid, vp->partition->device, V_attachState(vp));
1834 /* wait for other blocking ops to finish */
1835 VWaitExclusiveState_r(vp);
1837 osi_Assert(VIsValidState(V_attachState(vp)));
1839 switch(V_attachState(vp)) {
1840 case VOL_STATE_SALVAGING:
1841 /* Leave salvaging volumes alone. Any in-progress salvages will
1842 * continue working after viced shuts down. This is intentional.
1845 case VOL_STATE_PREATTACHED:
1846 case VOL_STATE_ERROR:
1847 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1848 case VOL_STATE_UNATTACHED:
1849 case VOL_STATE_DELETED:
1851 case VOL_STATE_GOING_OFFLINE:
1852 case VOL_STATE_SHUTTING_DOWN:
1853 case VOL_STATE_ATTACHED:
1857 Log("VShutdown: Attempting to take volume %u offline.\n",
1860 /* take the volume offline (drops reference count) */
1861 VOffline_r(vp, "File server was shut down");
1868 VCancelReservation_r(vp);
1872 #endif /* AFS_DEMAND_ATTACH_FS */
1875 /***************************************************/
1876 /* Header I/O routines */
1877 /***************************************************/
1880 HeaderName(bit32 magic)
1883 case VOLUMEINFOMAGIC:
1884 return "volume info";
1885 case SMALLINDEXMAGIC:
1886 return "small index";
1887 case LARGEINDEXMAGIC:
1888 return "large index";
1889 case LINKTABLEMAGIC:
1890 return "link table";
1895 /* open a descriptor for the inode (h),
1896 * read in an on-disk structure into buffer (to) of size (size),
1897 * verify versionstamp in structure has magic (magic) and
1898 * optionally verify version (version) if (version) is nonzero
1901 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1904 struct versionStamp *vsn;
1906 afs_sfsize_t nbytes;
1911 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1919 Log("ReadHeader: Failed to open %s header file "
1920 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1921 PrintInode(stmp, h->ih_ino), errno);
1926 vsn = (struct versionStamp *)to;
1927 nbytes = FDH_PREAD(fdP, to, size, 0);
1929 Log("ReadHeader: Failed to read %s header file "
1930 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1931 PrintInode(stmp, h->ih_ino), errno);
1933 FDH_REALLYCLOSE(fdP);
1936 if (nbytes != size) {
1937 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1938 "(volume=%u, inode=%s); expected=%d, read=%d\n",
1939 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), size,
1942 FDH_REALLYCLOSE(fdP);
1945 if (vsn->magic != magic) {
1946 Log("ReadHeader: Incorrect magic for %s header file "
1947 "(volume=%u, inode=%s); expected=0x%x, read=0x%x\n",
1948 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), magic,
1951 FDH_REALLYCLOSE(fdP);
1957 /* Check is conditional, in case caller wants to inspect version himself */
1958 if (version && vsn->version != version) {
1959 Log("ReadHeader: Incorrect version for %s header file "
1960 "(volume=%u, inode=%s); expected=%x, read=%x\n",
1961 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino),
1962 version, vsn->version);
1968 WriteVolumeHeader_r(Error * ec, Volume * vp)
1970 IHandle_t *h = V_diskDataHandle(vp);
1980 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1981 != sizeof(V_disk(vp))) {
1983 FDH_REALLYCLOSE(fdP);
1989 /* VolumeHeaderToDisk
1990 * Allows for storing 64 bit inode numbers in on-disk volume header
1993 /* convert in-memory representation of a volume header to the
1994 * on-disk representation of a volume header */
1996 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1999 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2000 dh->stamp = h->stamp;
2002 dh->parent = h->parent;
2004 #ifdef AFS_64BIT_IOPS_ENV
2005 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2006 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2007 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2008 dh->smallVnodeIndex_hi =
2009 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2010 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2011 dh->largeVnodeIndex_hi =
2012 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2013 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2014 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2016 dh->volumeInfo_lo = h->volumeInfo;
2017 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2018 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2019 dh->linkTable_lo = h->linkTable;
2023 /* DiskToVolumeHeader
2024 * Converts an on-disk representation of a volume header to
2025 * the in-memory representation of a volume header.
2027 * Makes the assumption that AFS has *always*
2028 * zero'd the volume header file so that high parts of inode
2029 * numbers are 0 in older (SGI EFS) volume header files.
2032 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2034 memset(h, 0, sizeof(VolumeHeader_t));
2035 h->stamp = dh->stamp;
2037 h->parent = dh->parent;
2039 #ifdef AFS_64BIT_IOPS_ENV
2041 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2043 h->smallVnodeIndex =
2044 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2045 smallVnodeIndex_hi << 32);
2047 h->largeVnodeIndex =
2048 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2049 largeVnodeIndex_hi << 32);
2051 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2053 h->volumeInfo = dh->volumeInfo_lo;
2054 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2055 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2056 h->linkTable = dh->linkTable_lo;
2061 /***************************************************/
2062 /* Volume Attachment routines */
2063 /***************************************************/
2065 #ifdef AFS_DEMAND_ATTACH_FS
2067 * pre-attach a volume given its path.
2069 * @param[out] ec outbound error code
2070 * @param[in] partition partition path string
2071 * @param[in] name volume id string
2073 * @return volume object pointer
2075 * @note A pre-attached volume will only have its partition
2076 * and hashid fields initialized. At first call to
2077 * VGetVolume, the volume will be fully attached.
2081 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2085 vp = VPreAttachVolumeByName_r(ec, partition, name);
2091 * pre-attach a volume given its path.
2093 * @param[out] ec outbound error code
2094 * @param[in] partition path to vice partition
2095 * @param[in] name volume id string
2097 * @return volume object pointer
2099 * @pre VOL_LOCK held
2101 * @internal volume package internal use only.
2104 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2106 return VPreAttachVolumeById_r(ec,
2108 VolumeNumber(name));
2112 * pre-attach a volume given its path and numeric volume id.
2114 * @param[out] ec error code return
2115 * @param[in] partition path to vice partition
2116 * @param[in] volumeId numeric volume id
2118 * @return volume object pointer
2120 * @pre VOL_LOCK held
2122 * @internal volume package internal use only.
2125 VPreAttachVolumeById_r(Error * ec,
2130 struct DiskPartition64 *partp;
2134 osi_Assert(programType == fileServer);
2136 if (!(partp = VGetPartition_r(partition, 0))) {
2138 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2142 vp = VLookupVolume_r(ec, volumeId, NULL);
2147 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2151 * preattach a volume.
2153 * @param[out] ec outbound error code
2154 * @param[in] partp pointer to partition object
2155 * @param[in] vp pointer to volume object
2156 * @param[in] vid volume id
2158 * @return volume object pointer
2160 * @pre VOL_LOCK is held.
2162 * @warning Returned volume object pointer does not have to
2163 * equal the pointer passed in as argument vp. There
2164 * are potential race conditions which can result in
2165 * the pointers having different values. It is up to
2166 * the caller to make sure that references are handled
2167 * properly in this case.
2169 * @note If there is already a volume object registered with
2170 * the same volume id, its pointer MUST be passed as
2171 * argument vp. Failure to do so will result in a silent
2172 * failure to preattach.
2174 * @internal volume package internal use only.
2177 VPreAttachVolumeByVp_r(Error * ec,
2178 struct DiskPartition64 * partp,
2186 /* check to see if pre-attach already happened */
2188 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2189 (V_attachState(vp) != VOL_STATE_DELETED) &&
2190 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2191 !VIsErrorState(V_attachState(vp))) {
2193 * pre-attach is a no-op in all but the following cases:
2195 * - volume is unattached
2196 * - volume is in an error state
2197 * - volume is pre-attached
2199 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state (state %u flags 0x%x)\n",
2200 vid, V_attachState(vp), V_attachFlags(vp));
2203 /* we're re-attaching a volume; clear out some old state */
2204 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2206 if (V_partition(vp) != partp) {
2207 /* XXX potential race */
2208 DeleteVolumeFromVByPList_r(vp);
2211 /* if we need to allocate a new Volume struct,
2212 * go ahead and drop the vol glock, otherwise
2213 * do the basic setup synchronised, as it's
2214 * probably not worth dropping the lock */
2217 /* allocate the volume structure */
2218 vp = nvp = (Volume *) malloc(sizeof(Volume));
2219 osi_Assert(vp != NULL);
2220 memset(vp, 0, sizeof(Volume));
2221 queue_Init(&vp->vnode_list);
2222 queue_Init(&vp->rx_call_list);
2223 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2226 /* link the volume with its associated vice partition */
2227 vp->device = partp->device;
2228 vp->partition = partp;
2231 vp->specialStatus = 0;
2233 /* if we dropped the lock, reacquire the lock,
2234 * check for pre-attach races, and then add
2235 * the volume to the hash table */
2238 nvp = VLookupVolume_r(ec, vid, NULL);
2243 } else if (nvp) { /* race detected */
2248 /* hack to make up for VChangeState_r() decrementing
2249 * the old state counter */
2250 VStats.state_levels[0]++;
2254 /* put pre-attached volume onto the hash table
2255 * and bring it up to the pre-attached state */
2256 AddVolumeToHashTable(vp, vp->hashid);
2257 AddVolumeToVByPList_r(vp);
2258 VLRU_Init_Node_r(vp);
2259 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2262 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2270 #endif /* AFS_DEMAND_ATTACH_FS */
2272 /* Attach an existing volume, given its pathname, and return a
2273 pointer to the volume header information. The volume also
2274 normally goes online at this time. An offline volume
2275 must be reattached to make it go online */
2277 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2281 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2287 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2290 struct DiskPartition64 *partp;
2295 #ifdef AFS_DEMAND_ATTACH_FS
2296 VolumeStats stats_save;
2298 #endif /* AFS_DEMAND_ATTACH_FS */
2302 volumeId = VolumeNumber(name);
2304 if (!(partp = VGetPartition_r(partition, 0))) {
2306 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2310 if (VRequiresPartLock()) {
2311 osi_Assert(VInit == 3);
2312 VLockPartition_r(partition);
2313 } else if (programType == fileServer) {
2314 #ifdef AFS_DEMAND_ATTACH_FS
2315 /* lookup the volume in the hash table */
2316 vp = VLookupVolume_r(ec, volumeId, NULL);
2322 /* save any counters that are supposed to
2323 * be monotonically increasing over the
2324 * lifetime of the fileserver */
2325 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2327 memset(&stats_save, 0, sizeof(VolumeStats));
2330 /* if there's something in the hash table, and it's not
2331 * in the pre-attach state, then we may need to detach
2332 * it before proceeding */
2333 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2334 VCreateReservation_r(vp);
2335 VWaitExclusiveState_r(vp);
2337 /* at this point state must be one of:
2347 if (vp->specialStatus == VBUSY)
2350 /* if it's already attached, see if we can return it */
2351 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2352 VGetVolumeByVp_r(ec, vp);
2353 if (V_inUse(vp) == fileServer) {
2354 VCancelReservation_r(vp);
2358 /* otherwise, we need to detach, and attempt to re-attach */
2359 VDetachVolume_r(ec, vp);
2361 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2364 /* if it isn't fully attached, delete from the hash tables,
2365 and let the refcounter handle the rest */
2366 DeleteVolumeFromHashTable(vp);
2367 DeleteVolumeFromVByPList_r(vp);
2370 VCancelReservation_r(vp);
2374 /* pre-attach volume if it hasn't been done yet */
2376 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2377 (V_attachState(vp) == VOL_STATE_DELETED) ||
2378 (V_attachState(vp) == VOL_STATE_ERROR)) {
2380 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2386 osi_Assert(vp != NULL);
2388 /* handle pre-attach races
2390 * multiple threads can race to pre-attach a volume,
2391 * but we can't let them race beyond that
2393 * our solution is to let the first thread to bring
2394 * the volume into an exclusive state win; the other
2395 * threads just wait until it finishes bringing the
2396 * volume online, and then they do a vgetvolumebyvp
2398 if (svp && (svp != vp)) {
2399 /* wait for other exclusive ops to finish */
2400 VCreateReservation_r(vp);
2401 VWaitExclusiveState_r(vp);
2403 /* get a heavyweight ref, kill the lightweight ref, and return */
2404 VGetVolumeByVp_r(ec, vp);
2405 VCancelReservation_r(vp);
2409 /* at this point, we are chosen as the thread to do
2410 * demand attachment for this volume. all other threads
2411 * doing a getvolume on vp->hashid will block until we finish */
2413 /* make sure any old header cache entries are invalidated
2414 * before proceeding */
2415 FreeVolumeHeader(vp);
2417 VChangeState_r(vp, VOL_STATE_ATTACHING);
2419 /* restore any saved counters */
2420 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2421 #else /* AFS_DEMAND_ATTACH_FS */
2422 vp = VGetVolume_r(ec, volumeId);
2424 if (V_inUse(vp) == fileServer)
2426 if (vp->specialStatus == VBUSY)
2428 VDetachVolume_r(ec, vp);
2430 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2434 #endif /* AFS_DEMAND_ATTACH_FS */
2438 strcpy(path, VPartitionPath(partp));
2442 strcat(path, OS_DIRSEP);
2446 vp = (Volume *) calloc(1, sizeof(Volume));
2447 osi_Assert(vp != NULL);
2448 vp->hashid = volumeId;
2449 vp->device = partp->device;
2450 vp->partition = partp;
2451 queue_Init(&vp->vnode_list);
2452 queue_Init(&vp->rx_call_list);
2453 #ifdef AFS_DEMAND_ATTACH_FS
2454 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2455 #endif /* AFS_DEMAND_ATTACH_FS */
2458 /* attach2 is entered without any locks, and returns
2459 * with vol_glock_mutex held */
2460 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2462 if (VCanUseFSSYNC() && vp) {
2463 #ifdef AFS_DEMAND_ATTACH_FS
2464 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2465 /* mark volume header as in use so that volser crashes lead to a
2466 * salvage attempt */
2467 VUpdateVolume_r(ec, vp, 0);
2469 /* for dafs, we should tell the fileserver, except for V_PEEK
2470 * where we know it is not necessary */
2471 if (mode == V_PEEK) {
2472 vp->needsPutBack = 0;
2474 vp->needsPutBack = VOL_PUTBACK;
2476 #else /* !AFS_DEMAND_ATTACH_FS */
2477 /* duplicate computation in fssync.c about whether the server
2478 * takes the volume offline or not. If the volume isn't
2479 * offline, we must not return it when we detach the volume,
2480 * or the server will abort */
2481 if (mode == V_READONLY || mode == V_PEEK
2482 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2483 vp->needsPutBack = 0;
2485 vp->needsPutBack = VOL_PUTBACK;
2486 #endif /* !AFS_DEMAND_ATTACH_FS */
2488 #ifdef FSSYNC_BUILD_CLIENT
2489 /* Only give back the vol to the fileserver if we checked it out; attach2
2490 * will set checkedOut only if we successfully checked it out from the
2492 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2494 #ifdef AFS_DEMAND_ATTACH_FS
2495 /* If we couldn't attach but we scheduled a salvage, we already
2496 * notified the fileserver; don't online it now */
2497 if (*ec != VSALVAGING)
2498 #endif /* AFS_DEMAND_ATTACH_FS */
2499 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2502 if (programType == fileServer && vp) {
2503 #ifdef AFS_DEMAND_ATTACH_FS
2505 * we can get here in cases where we don't "own"
2506 * the volume (e.g. volume owned by a utility).
2507 * short circuit around potential disk header races.
2509 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2513 VUpdateVolume_r(ec, vp, 0);
2515 Log("VAttachVolume: Error updating volume\n");
2520 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2521 #ifndef AFS_DEMAND_ATTACH_FS
2522 /* This is a hack: by temporarily setting the incore
2523 * dontSalvage flag ON, the volume will be put back on the
2524 * Update list (with dontSalvage OFF again). It will then
2525 * come back in N minutes with DONT_SALVAGE eventually
2526 * set. This is the way that volumes that have never had
2527 * it set get it set; or that volumes that have been
2528 * offline without DONT SALVAGE having been set also
2529 * eventually get it set */
2530 V_dontSalvage(vp) = DONT_SALVAGE;
2531 #endif /* !AFS_DEMAND_ATTACH_FS */
2532 VAddToVolumeUpdateList_r(ec, vp);
2534 Log("VAttachVolume: Error adding volume to update list\n");
2541 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2546 if (VRequiresPartLock()) {
2547 VUnlockPartition_r(partition);
2550 #ifdef AFS_DEMAND_ATTACH_FS
2551 /* attach failed; make sure we're in error state */
2552 if (vp && !VIsErrorState(V_attachState(vp))) {
2553 VChangeState_r(vp, VOL_STATE_ERROR);
2555 #endif /* AFS_DEMAND_ATTACH_FS */
2562 #ifdef AFS_DEMAND_ATTACH_FS
2563 /* VAttachVolumeByVp_r
2565 * finish attaching a volume that is
2566 * in a less than fully attached state
2568 /* caller MUST hold a ref count on vp */
2570 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2572 char name[VMAXPATHLEN];
2574 struct DiskPartition64 *partp;
2578 Volume * nvp = NULL;
2579 VolumeStats stats_save;
2583 /* volume utility should never call AttachByVp */
2584 osi_Assert(programType == fileServer);
2586 volumeId = vp->hashid;
2587 partp = vp->partition;
2588 VolumeExternalName_r(volumeId, name, sizeof(name));
2591 /* if another thread is performing a blocking op, wait */
2592 VWaitExclusiveState_r(vp);
2594 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2596 /* if it's already attached, see if we can return it */
2597 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2598 VGetVolumeByVp_r(ec, vp);
2599 if (V_inUse(vp) == fileServer) {
2602 if (vp->specialStatus == VBUSY)
2604 VDetachVolume_r(ec, vp);
2606 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2612 /* pre-attach volume if it hasn't been done yet */
2614 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2615 (V_attachState(vp) == VOL_STATE_DELETED) ||
2616 (V_attachState(vp) == VOL_STATE_ERROR)) {
2617 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2623 VCreateReservation_r(nvp);
2628 osi_Assert(vp != NULL);
2629 VChangeState_r(vp, VOL_STATE_ATTACHING);
2631 /* restore monotonically increasing stats */
2632 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2636 /* compute path to disk header */
2637 strcpy(path, VPartitionPath(partp));
2641 strcat(path, OS_DIRSEP);
2646 * NOTE: attach2 is entered without any locks, and returns
2647 * with vol_glock_mutex held */
2648 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2651 * the event that an error was encountered, or
2652 * the volume was not brought to an attached state
2653 * for any reason, skip to the end. We cannot
2654 * safely call VUpdateVolume unless we "own" it.
2658 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2662 VUpdateVolume_r(ec, vp, 0);
2664 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2668 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2669 #ifndef AFS_DEMAND_ATTACH_FS
2670 /* This is a hack: by temporarily setting the incore
2671 * dontSalvage flag ON, the volume will be put back on the
2672 * Update list (with dontSalvage OFF again). It will then
2673 * come back in N minutes with DONT_SALVAGE eventually
2674 * set. This is the way that volumes that have never had
2675 * it set get it set; or that volumes that have been
2676 * offline without DONT SALVAGE having been set also
2677 * eventually get it set */
2678 V_dontSalvage(vp) = DONT_SALVAGE;
2679 #endif /* !AFS_DEMAND_ATTACH_FS */
2680 VAddToVolumeUpdateList_r(ec, vp);
2682 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2689 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2693 VCancelReservation_r(nvp);
2696 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2697 if (vp && !VIsErrorState(V_attachState(vp))) {
2698 VChangeState_r(vp, VOL_STATE_ERROR);
2707 * lock a volume on disk (non-blocking).
2709 * @param[in] vp The volume to lock
2710 * @param[in] locktype READ_LOCK or WRITE_LOCK
2712 * @return operation status
2713 * @retval 0 success, lock was obtained
2714 * @retval EBUSY a conflicting lock was held by another process
2715 * @retval EIO error acquiring lock
2717 * @pre If we're in the fileserver, vp is in an exclusive state
2719 * @pre vp is not already locked
2722 VLockVolumeNB(Volume *vp, int locktype)
2726 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2727 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2729 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2731 V_attachFlags(vp) |= VOL_LOCKED;
2738 * unlock a volume on disk that was locked with VLockVolumeNB.
2740 * @param[in] vp volume to unlock
2742 * @pre If we're in the fileserver, vp is in an exclusive state
2744 * @pre vp has already been locked
2747 VUnlockVolume(Volume *vp)
2749 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2750 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2752 VUnlockVolumeById(vp->hashid, vp->partition);
2754 V_attachFlags(vp) &= ~VOL_LOCKED;
2756 #endif /* AFS_DEMAND_ATTACH_FS */
2759 * read in a vol header, possibly lock the vol header, and possibly check out
2760 * the vol header from the fileserver, as part of volume attachment.
2762 * @param[out] ec error code
2763 * @param[in] vp volume pointer object
2764 * @param[in] partp disk partition object of the attaching partition
2765 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2767 * @param[in] peek 1 to just try to read in the volume header and make sure
2768 * we don't try to lock the vol, or check it out from
2769 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2771 * @param[out] acheckedOut If we successfully checked-out the volume from
2772 * the fileserver (if we needed to), this is set
2773 * to 1, otherwise it is untouched.
2775 * @note As part of DAFS volume attachment, the volume header may be either
2776 * read- or write-locked to ensure mutual exclusion of certain volume
2777 * operations. In some cases in order to determine whether we need to
2778 * read- or write-lock the header, we need to read in the header to see
2779 * if the volume is RW or not. So, if we read in the header under a
2780 * read-lock and determine that we actually need a write-lock on the
2781 * volume header, this function will drop the read lock, acquire a write
2782 * lock, and read the header in again.
2785 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2786 int mode, int peek, int *acheckedOut)
2788 struct VolumeDiskHeader diskHeader;
2789 struct VolumeHeader header;
2792 int lock_tries = 0, checkout_tries = 0;
2794 VolumeId volid = vp->hashid;
2795 #ifdef FSSYNC_BUILD_CLIENT
2796 int checkout, done_checkout = 0;
2797 #endif /* FSSYNC_BUILD_CLIENT */
2798 #ifdef AFS_DEMAND_ATTACH_FS
2799 int locktype = 0, use_locktype = -1;
2800 #endif /* AFS_DEMAND_ATTACH_FS */
2806 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2807 Log("VAttachVolume: retried too many times trying to lock header for "
2808 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2809 VPartitionPath(partp));
2813 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2814 Log("VAttachVolume: retried too many times trying to checkout "
2815 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2816 VPartitionPath(partp));
2821 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2822 /* short-circuit the 'volume does not exist' case */
2827 #ifdef FSSYNC_BUILD_CLIENT
2828 checkout = !done_checkout;
2830 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2832 memset(&res, 0, sizeof(res));
2834 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2837 if (res.hdr.reason == FSYNC_SALVAGE) {
2838 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2839 afs_printable_uint32_lu(volid));
2842 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2843 afs_printable_uint32_lu(volid));
2844 *ec = VNOVOL; /* XXXX */
2852 #ifdef AFS_DEMAND_ATTACH_FS
2853 if (use_locktype < 0) {
2854 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2855 * if it turns out to be RW */
2856 locktype = VVolLockType(mode, 0);
2859 /* a previous try says we should use use_locktype to lock the volume,
2861 locktype = use_locktype;
2864 if (!peek && locktype) {
2865 code = VLockVolumeNB(vp, locktype);
2867 if (code == EBUSY) {
2868 Log("VAttachVolume: another program has vol %lu locked\n",
2869 afs_printable_uint32_lu(volid));
2871 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2872 code, afs_printable_uint32_lu(volid));
2879 #endif /* AFS_DEMAND_ATTACH_FS */
2881 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2891 DiskToVolumeHeader(&header, &diskHeader);
2893 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2894 header.largeVnodeIndex);
2895 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2896 header.smallVnodeIndex);
2897 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2899 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2902 /* only need to do this once */
2904 GetVolumeHeader(vp);
2908 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2909 /* demand attach changes the V_PEEK mechanism
2911 * we can now suck the current disk data structure over
2912 * the fssync interface without going to disk
2914 * (technically, we don't need to restrict this feature
2915 * to demand attach fileservers. However, I'm trying
2916 * to limit the number of common code changes)
2918 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2920 res.payload.len = sizeof(VolumeDiskData);
2921 res.payload.buf = &vp->header->diskstuff;
2923 if (FSYNC_VolOp(vp->hashid,
2925 FSYNC_VOL_QUERY_HDR,
2928 goto disk_header_loaded;
2931 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2932 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2933 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2935 #ifdef AFS_DEMAND_ATTACH_FS
2938 IncUInt64(&VStats.hdr_loads);
2939 IncUInt64(&vp->stats.hdr_loads);
2941 #endif /* AFS_DEMAND_ATTACH_FS */
2944 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2945 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2949 #ifdef AFS_DEMAND_ATTACH_FS
2950 # ifdef FSSYNC_BUILD_CLIENT
2952 # endif /* FSSYNC_BUILD_CLIENT */
2954 /* if the lock type we actually used to lock the volume is different than
2955 * the lock type we should have used, retry with the lock type we should
2957 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2958 if (locktype != use_locktype) {
2962 #endif /* AFS_DEMAND_ATTACH_FS */
2967 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2968 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2970 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2972 if (code == SYNC_DENIED) {
2973 /* must retry checkout; fileserver no longer thinks we have
2979 } else if (code != SYNC_OK) {
2983 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2986 /* either we are going to be called again for a second pass, or we
2987 * encountered an error; clean up in either case */
2989 #ifdef AFS_DEMAND_ATTACH_FS
2990 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2993 #endif /* AFS_DEMAND_ATTACH_FS */
2994 if (vp->linkHandle) {
2995 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2996 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2997 IH_RELEASE(vp->diskDataHandle);
2998 IH_RELEASE(vp->linkHandle);
3011 #ifdef AFS_DEMAND_ATTACH_FS
3013 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3014 Volume *vp, int *acheckedOut)
3018 if (vp->pending_vol_op) {
3022 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3024 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3026 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3027 } else if (code == 0) {
3028 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3031 /* we need the vol header to determine if the volume can be
3032 * left online for the vop, so... get the header */
3036 /* attach header with peek=1 to avoid checking out the volume
3037 * or locking it; we just want the header info, we're not
3038 * messing with the volume itself at all */
3039 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3046 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3047 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3049 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3052 /* make sure we grab a new vol header and re-open stuff on
3053 * actual attachment; we can't keep the data we grabbed, since
3054 * it was not done under a lock and thus not safe */
3055 FreeVolumeHeader(vp);
3056 VReleaseVolumeHandles_r(vp);
3059 /* see if the pending volume op requires exclusive access */
3060 switch (vp->pending_vol_op->vol_op_state) {
3061 case FSSYNC_VolOpPending:
3062 /* this should never happen */
3063 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3066 case FSSYNC_VolOpRunningUnknown:
3067 /* this should never happen; we resolved 'unknown' above */
3068 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3071 case FSSYNC_VolOpRunningOffline:
3072 /* mark the volume down */
3074 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3076 /* do not set V_offlineMessage here; we don't have ownership of
3077 * the volume (and probably do not have the header loaded), so we
3078 * can't alter the disk header */
3080 /* check to see if we should set the specialStatus flag */
3081 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3082 /* don't overwrite specialStatus if it was already set to
3083 * something else (e.g. VMOVED) */
3084 if (!vp->specialStatus) {
3085 vp->specialStatus = VBUSY;
3097 #endif /* AFS_DEMAND_ATTACH_FS */
3100 * volume attachment helper function.
3102 * @param[out] ec error code
3103 * @param[in] volumeId volume ID of the attaching volume
3104 * @param[in] path full path to the volume header .vol file
3105 * @param[in] partp disk partition object for the attaching partition
3106 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3107 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3108 * DAFS) should already be initialized
3109 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3110 * if there is a volume operation running for this volume
3111 * that should set the volume to VBUSY during its run. 0
3112 * otherwise. (see VVolOpSetVBusy_r)
3113 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3115 * @param[out] acheckedOut If we successfully checked-out the volume from
3116 * the fileserver (if we needed to), this is set
3117 * to 1, otherwise it is 0.
3119 * @return pointer to the semi-attached volume pointer
3120 * @retval NULL an error occurred (check value of *ec)
3121 * @retval vp volume successfully attaching
3123 * @pre no locks held
3125 * @post VOL_LOCK held
3128 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3129 Volume * vp, int isbusy, int mode, int *acheckedOut)
3131 /* have we read in the header successfully? */
3132 int read_header = 0;
3134 #ifdef AFS_DEMAND_ATTACH_FS
3135 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3139 /* in the case of an error, to what state should the volume be
3141 VolState error_state = VOL_STATE_ERROR;
3142 #endif /* AFS_DEMAND_ATTACH_FS */
3146 vp->vnodeIndex[vLarge].handle = NULL;
3147 vp->vnodeIndex[vSmall].handle = NULL;
3148 vp->diskDataHandle = NULL;
3149 vp->linkHandle = NULL;
3153 #ifdef AFS_DEMAND_ATTACH_FS
3154 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3156 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3159 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3160 #endif /* !AFS_DEMAND_ATTACH_FS */
3162 if (*ec == VNOVOL) {
3163 /* if the volume doesn't exist, skip straight to 'error' so we don't
3164 * request a salvage */
3166 goto error_notbroken;
3172 /* ensure that we don't override specialStatus if it was set to
3173 * something else (e.g. VMOVED) */
3174 if (isbusy && !vp->specialStatus) {
3175 vp->specialStatus = VBUSY;
3177 vp->shuttingDown = 0;
3178 vp->goingOffline = 0;
3180 #ifdef AFS_DEMAND_ATTACH_FS
3181 vp->stats.last_attach = FT_ApproxTime();
3182 vp->stats.attaches++;
3186 IncUInt64(&VStats.attaches);
3187 vp->cacheCheck = ++VolumeCacheCheck;
3188 /* just in case this ever rolls over */
3189 if (!vp->cacheCheck)
3190 vp->cacheCheck = ++VolumeCacheCheck;
3193 #ifdef AFS_DEMAND_ATTACH_FS
3194 V_attachFlags(vp) |= VOL_HDR_LOADED;
3195 vp->stats.last_hdr_load = vp->stats.last_attach;
3196 #endif /* AFS_DEMAND_ATTACH_FS */
3200 struct IndexFileHeader iHead;
3203 * We just read in the diskstuff part of the header. If the detailed
3204 * volume stats area has not yet been initialized, we should bzero the
3205 * area and mark it as initialized.
3207 if (!(V_stat_initialized(vp))) {
3208 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3209 V_stat_initialized(vp) = 1;
3212 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3213 (char *)&iHead, sizeof(iHead),
3214 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3217 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3222 struct IndexFileHeader iHead;
3224 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3225 (char *)&iHead, sizeof(iHead),
3226 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3229 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3233 #ifdef AFS_NAMEI_ENV
3235 struct versionStamp stamp;
3237 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3238 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3241 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3244 #endif /* AFS_NAMEI_ENV */
3246 #if defined(AFS_DEMAND_ATTACH_FS)
3247 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3249 if (!VCanScheduleSalvage()) {
3250 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3252 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3257 /* volume operation in progress */
3259 goto error_notbroken;
3261 #else /* AFS_DEMAND_ATTACH_FS */
3263 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3264 goto unlocked_error;
3266 #endif /* AFS_DEMAND_ATTACH_FS */
3268 if (V_needsSalvaged(vp)) {
3269 if (vp->specialStatus)
3270 vp->specialStatus = 0;
3272 #if defined(AFS_DEMAND_ATTACH_FS)
3273 if (!VCanScheduleSalvage()) {
3274 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3276 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3279 #else /* AFS_DEMAND_ATTACH_FS */
3281 #endif /* AFS_DEMAND_ATTACH_FS */
3287 vp->nextVnodeUnique = V_uniquifier(vp);
3289 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3290 if (!V_needsSalvaged(vp)) {
3291 V_needsSalvaged(vp) = 1;
3292 VUpdateVolume_r(ec, vp, 0);
3294 #if defined(AFS_DEMAND_ATTACH_FS)
3295 if (!VCanScheduleSalvage()) {
3296 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3298 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3301 #else /* AFS_DEMAND_ATTACH_FS */
3302 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3304 #endif /* AFS_DEMAND_ATTACH_FS */
3309 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3310 /* Only check destroyMe if we are the fileserver, since the
3311 * volserver et al sometimes need to work with volumes with
3312 * destroyMe set. Examples are 'temporary' volumes the
3313 * volserver creates, and when we create a volume (destroyMe
3314 * is set on creation; sometimes a separate volserver
3315 * transaction is created to clear destroyMe).
3318 #if defined(AFS_DEMAND_ATTACH_FS)
3319 /* schedule a salvage so the volume goes away on disk */
3320 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3321 VChangeState_r(vp, VOL_STATE_ERROR);
3324 #endif /* AFS_DEMAND_ATTACH_FS */
3325 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3330 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3331 #ifndef BITMAP_LATER
3332 if (programType == fileServer && VolumeWriteable(vp)) {
3334 for (i = 0; i < nVNODECLASSES; i++) {
3335 VGetBitmap_r(ec, vp, i);
3337 #ifdef AFS_DEMAND_ATTACH_FS
3338 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3340 #endif /* AFS_DEMAND_ATTACH_FS */
3341 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3347 #endif /* BITMAP_LATER */
3349 if (VInit >= 2 && V_needsCallback(vp)) {
3350 if (V_BreakVolumeCallbacks) {
3351 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3352 afs_printable_uint32_lu(V_id(vp)));
3353 V_needsCallback(vp) = 0;
3355 (*V_BreakVolumeCallbacks) (V_id(vp));
3358 VUpdateVolume_r(ec, vp, 0);
3360 #ifdef FSSYNC_BUILD_CLIENT
3361 else if (VCanUseFSSYNC()) {
3362 afs_int32 fsync_code;
3364 V_needsCallback(vp) = 0;
3366 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3370 V_needsCallback(vp) = 1;
3371 Log("Error trying to tell the fileserver to break callbacks for "
3372 "changed volume %lu; error code %ld\n",
3373 afs_printable_uint32_lu(V_id(vp)),
3374 afs_printable_int32_ld(fsync_code));
3376 VUpdateVolume_r(ec, vp, 0);
3379 #endif /* FSSYNC_BUILD_CLIENT */
3382 Log("VAttachVolume: error %d clearing needsCallback on volume "
3383 "%lu; needs salvage\n", (int)*ec,
3384 afs_printable_uint32_lu(V_id(vp)));
3385 #ifdef AFS_DEMAND_ATTACH_FS
3386 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3388 #else /* !AFS_DEMAND_ATTACH_FS */
3390 #endif /* !AFS_DEMAND_ATTACh_FS */
3395 if (programType == fileServer) {
3396 if (vp->specialStatus)
3397 vp->specialStatus = 0;
3398 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3399 V_inUse(vp) = fileServer;
3400 V_offlineMessage(vp)[0] = '\0';
3404 #ifdef AFS_DEMAND_ATTACH_FS
3405 /* Put the vol into PREATTACHED state, so if someone tries to
3406 * access it again, we try to attach, see that we're not blessed,
3407 * and give a VNOVOL error again. Putting it into UNATTACHED state
3408 * would result in a VOFFLINE error instead. */
3409 error_state = VOL_STATE_PREATTACHED;
3410 #endif /* AFS_DEMAND_ATTACH_FS */
3412 /* mimic e.g. GetVolume errors */
3413 if (!V_blessed(vp)) {
3414 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3415 FreeVolumeHeader(vp);
3416 } else if (!V_inService(vp)) {
3417 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3418 FreeVolumeHeader(vp);
3420 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3422 #ifdef AFS_DEMAND_ATTACH_FS
3423 error_state = VOL_STATE_ERROR;
3424 /* see if we can recover */
3425 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0 /*flags*/);
3428 #ifdef AFS_DEMAND_ATTACH_FS
3434 #ifdef AFS_DEMAND_ATTACH_FS
3435 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3436 V_inUse(vp) = programType;
3437 #endif /* AFS_DEMAND_ATTACH_FS */
3438 V_checkoutMode(vp) = mode;
3441 AddVolumeToHashTable(vp, V_id(vp));
3442 #ifdef AFS_DEMAND_ATTACH_FS
3443 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3446 if ((programType != fileServer) ||
3447 (V_inUse(vp) == fileServer)) {
3448 AddVolumeToVByPList_r(vp);
3450 VChangeState_r(vp, VOL_STATE_ATTACHED);
3452 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3458 #ifndef AFS_DEMAND_ATTACH_FS
3464 #ifdef AFS_DEMAND_ATTACH_FS
3465 if (!VIsErrorState(V_attachState(vp))) {
3466 if (VIsErrorState(error_state)) {
3467 Log("attach2: forcing vol %u to error state (state %u flags 0x%x ec %d)\n",
3468 vp->hashid, V_attachState(vp), V_attachFlags(vp), *ec);
3470 VChangeState_r(vp, error_state);
3472 #endif /* AFS_DEMAND_ATTACH_FS */
3475 VReleaseVolumeHandles_r(vp);
3479 #ifdef AFS_DEMAND_ATTACH_FS
3486 #else /* !AFS_DEMAND_ATTACH_FS */
3488 #endif /* !AFS_DEMAND_ATTACH_FS */
3492 /* Attach an existing volume.
3493 The volume also normally goes online at this time.
3494 An offline volume must be reattached to make it go online.
3498 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3502 retVal = VAttachVolume_r(ec, volumeId, mode);
3508 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3511 VGetVolumePath(ec, volumeId, &part, &name);
3515 vp = VGetVolume_r(&error, volumeId);
3517 osi_Assert(V_inUse(vp) == 0);
3518 VDetachVolume_r(ec, vp);
3522 return VAttachVolumeByName_r(ec, part, name, mode);
3525 /* Increment a reference count to a volume, sans context swaps. Requires
3526 * possibly reading the volume header in from the disk, since there's
3527 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3529 * N.B. This call can fail if we can't read in the header!! In this case
3530 * we still guarantee we won't context swap, but the ref count won't be
3531 * incremented (otherwise we'd violate the invariant).
3533 /* NOTE: with the demand attach fileserver extensions, the global lock
3534 * is dropped within VHold */
3535 #ifdef AFS_DEMAND_ATTACH_FS
3537 VHold_r(Volume * vp)
3541 VCreateReservation_r(vp);
3542 VWaitExclusiveState_r(vp);
3544 LoadVolumeHeader(&error, vp);
3546 VCancelReservation_r(vp);
3550 VCancelReservation_r(vp);
3553 #else /* AFS_DEMAND_ATTACH_FS */
3555 VHold_r(Volume * vp)
3559 LoadVolumeHeader(&error, vp);
3565 #endif /* AFS_DEMAND_ATTACH_FS */
3567 /**** volume timeout-related stuff ****/
3569 #ifdef AFS_PTHREAD_ENV
3571 static struct timespec *shutdown_timeout;
3572 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3575 VTimedOut(const struct timespec *ts)
3580 if (ts->tv_sec == 0) {
3581 /* short-circuit; this will have always timed out */
3585 code = gettimeofday(&tv, NULL);
3587 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3588 /* assume no timeout; failure mode is we just wait longer than normal
3589 * instead of returning errors when we shouldn't */
3593 if (tv.tv_sec < ts->tv_sec ||
3594 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3603 * Calculate an absolute timeout.
3605 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3606 * NULL, the memory is not touched
3607 * @param[in] timeout How long the timeout should be from now
3609 * @return timeout to use
3610 * @retval NULL no timeout; wait forever
3611 * @retval non-NULL the given value for "ts"
3615 static struct timespec *
3616 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3626 ts->tv_sec = ts->tv_nsec = 0;
3630 code = gettimeofday(&now, NULL);
3632 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3636 ts->tv_sec = now.tv_sec + timeout;
3637 ts->tv_nsec = now.tv_usec * 1000;
3643 * Initialize the shutdown_timeout global.
3646 VShutdownTimeoutInit(void)
3648 struct timespec *ts;
3650 ts = malloc(sizeof(*ts));
3652 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3654 if (!shutdown_timeout) {
3660 * Figure out the timeout that should be used for waiting for offline volumes.
3662 * @param[out] ats Storage space for a local timeout value if needed
3664 * @return The timeout value that should be used
3665 * @retval NULL No timeout; wait forever for offlining volumes
3666 * @retval non-NULL A pointer to the absolute time that should be used as
3667 * the deadline for waiting for offlining volumes.
3669 * @note If we return non-NULL, the pointer we return may or may not be the
3672 static const struct timespec *
3673 VOfflineTimeout(struct timespec *ats)
3675 if (vol_shutting_down) {
3676 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3677 return shutdown_timeout;
3679 return VCalcTimeout(ats, vol_opts.offline_timeout);
3683 #else /* AFS_PTHREAD_ENV */
3685 /* Waiting a certain amount of time for offlining volumes is not supported
3686 * for LWP due to a lack of primitives. So, we never time out */
3687 # define VTimedOut(x) (0)
3688 # define VOfflineTimeout(x) (NULL)
3690 #endif /* !AFS_PTHREAD_ENV */
3698 retVal = VHold_r(vp);
3705 VIsGoingOffline_r(struct Volume *vp)
3709 if (vp->goingOffline) {
3710 if (vp->specialStatus) {
3711 code = vp->specialStatus;
3712 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3723 * Tell the caller if a volume is waiting to go offline.
3725 * @param[in] vp The volume we want to know about
3727 * @return volume status
3728 * @retval 0 volume is not waiting to go offline, go ahead and use it
3729 * @retval nonzero volume is waiting to offline, and give the returned code
3730 * as an error to anyone accessing the volume
3732 * @pre VOL_LOCK is NOT held
3733 * @pre caller holds a heavyweight reference on vp
3736 VIsGoingOffline(struct Volume *vp)
3741 code = VIsGoingOffline_r(vp);
3748 * Register an RX call with a volume.
3750 * @param[inout] ec Error code; if unset when passed in, may be set if
3751 * the volume starts going offline
3752 * @param[out] client_ec @see GetVolume
3753 * @param[in] vp Volume struct
3754 * @param[in] cbv VCallByVol struct containing the RX call to register
3756 * @pre VOL_LOCK held
3757 * @pre caller holds heavy ref on vp
3762 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3765 #ifdef AFS_DEMAND_ATTACH_FS
3767 /* just in case the volume started going offline after we got the
3768 * reference to it... otherwise, if the volume started going
3769 * offline right at the end of GetVolume(), we might race with the
3770 * RX call scanner, and return success and add our cbv to the
3771 * rx_call_list _after_ the scanner has scanned the list. */
3772 *ec = VIsGoingOffline_r(vp);
3778 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3779 VWaitStateChange_r(vp);
3781 #endif /* AFS_DEMAND_ATTACH_FS */
3783 queue_Prepend(&vp->rx_call_list, cbv);
3788 * Deregister an RX call with a volume.
3790 * @param[in] vp Volume struct
3791 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3793 * @pre VOL_LOCK held
3794 * @pre caller holds heavy ref on vp
3799 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3801 if (cbv && queue_IsOnQueue(cbv)) {
3802 #ifdef AFS_DEMAND_ATTACH_FS
3803 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3804 VWaitStateChange_r(vp);
3806 #endif /* AFS_DEMAND_ATTACH_FS */
3812 /***************************************************/
3813 /* get and put volume routines */
3814 /***************************************************/
3817 * put back a heavyweight reference to a volume object.
3819 * @param[in] vp volume object pointer
3821 * @pre VOL_LOCK held
3823 * @post heavyweight volume reference put back.
3824 * depending on state, volume may have been taken offline,
3825 * detached, salvaged, freed, etc.
3827 * @internal volume package internal use only
3830 VPutVolume_r(Volume * vp)
3832 osi_Assert(--vp->nUsers >= 0);
3833 if (vp->nUsers == 0) {
3835 ReleaseVolumeHeader(vp->header);
3836 #ifdef AFS_DEMAND_ATTACH_FS
3837 if (!VCheckDetach(vp)) {
3841 #else /* AFS_DEMAND_ATTACH_FS */
3843 #endif /* AFS_DEMAND_ATTACH_FS */
3848 VPutVolume(Volume * vp)
3856 * Puts a volume reference obtained with VGetVolumeWithCall.
3858 * @param[in] vp Volume struct
3859 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3861 * @pre VOL_LOCK is NOT held
3864 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3867 VDeregisterCall_r(vp, cbv);
3872 /* Get a pointer to an attached volume. The pointer is returned regardless
3873 of whether or not the volume is in service or on/off line. An error
3874 code, however, is returned with an indication of the volume's status */
3876 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3880 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3886 * Get a volume reference associated with an RX call.
3888 * @param[out] ec @see GetVolume
3889 * @param[out] client_ec @see GetVolume
3890 * @param[in] volumeId @see GetVolume
3891 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3892 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3893 * with an error if the volume is going offline.
3894 * @param[in] cbv Contains an RX call to be associated with this volume
3895 * reference. This call may be interrupted if the volume is
3896 * requested to go offline while we hold a ref on it. Give NULL
3897 * to not associate an RX call with this reference.
3899 * @return @see GetVolume
3901 * @note for LWP builds, ts must be NULL
3903 * @note A reference obtained with this function MUST be put back with
3904 * VPutVolumeWithCall
3907 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3908 const struct timespec *ts, struct VCallByVol *cbv)
3912 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3913 VRegisterCall_r(ec, client_ec, retVal, cbv);
3919 VGetVolume_r(Error * ec, VolId volumeId)
3921 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3924 /* try to get a volume we've previously looked up */
3925 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3927 VGetVolumeByVp_r(Error * ec, Volume * vp)
3929 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3933 * private interface for getting a volume handle
3935 * @param[out] ec error code (0 if no error)
3936 * @param[out] client_ec wire error code to be given to clients
3937 * @param[in] volumeId ID of the volume we want
3938 * @param[in] hint optional hint for hash lookups, or NULL
3939 * @param[in] timeout absolute deadline for waiting for the volume to go
3940 * offline, if it is going offline. NULL to wait forever.
3942 * @return a volume handle for the specified volume
3943 * @retval NULL an error occurred, or the volume is in such a state that
3944 * we cannot load a header or return any volume struct
3946 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3948 * @note 'timeout' is only checked if the volume is actually going offline; so
3949 * if you pass timeout->tv_sec = 0, this will exhibit typical
3950 * nonblocking behavior.
3952 * @note for LWP builds, 'timeout' must be NULL
3955 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3956 const struct timespec *timeout)
3959 /* pull this profiling/debugging code out of regular builds */
3961 #define VGET_CTR_INC(x) x++
3962 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3963 0, V7 = 0, V8 = 0, V9 = 0;
3964 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3966 #define VGET_CTR_INC(x)
3968 #ifdef AFS_DEMAND_ATTACH_FS
3969 Volume *avp, * rvp = hint;
3973 * if VInit is zero, the volume package dynamic
3974 * data structures have not been initialized yet,
3975 * and we must immediately return an error
3981 *client_ec = VOFFLINE;
3986 #ifdef AFS_DEMAND_ATTACH_FS
3988 VCreateReservation_r(rvp);
3990 #endif /* AFS_DEMAND_ATTACH_FS */
3998 vp = VLookupVolume_r(ec, volumeId, vp);
4004 #ifdef AFS_DEMAND_ATTACH_FS
4005 if (rvp && (rvp != vp)) {
4006 /* break reservation on old vp */
4007 VCancelReservation_r(rvp);
4010 #endif /* AFS_DEMAND_ATTACH_FS */
4016 /* Until we have reached an initialization level of 2
4017 * we don't know whether this volume exists or not.
4018 * We can't sleep and retry later because before a volume
4019 * is attached, the caller tries to get it first. Just
4020 * return VOFFLINE and the caller can choose whether to
4021 * retry the command or not. */
4031 IncUInt64(&VStats.hdr_gets);
4033 #ifdef AFS_DEMAND_ATTACH_FS
4034 /* block if someone else is performing an exclusive op on this volume */
4037 VCreateReservation_r(rvp);
4039 VWaitExclusiveState_r(vp);
4041 /* short circuit with VNOVOL in the following circumstances:
4044 * - VOL_STATE_SHUTTING_DOWN
4046 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4047 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
4048 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
4055 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
4056 * VNOVOL for VOL_STATE_DELETED
4058 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4059 (V_attachState(vp) == VOL_STATE_DELETED)) {
4060 if (vp->specialStatus) {
4061 *ec = vp->specialStatus;
4062 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4071 /* allowable states:
4078 if (vp->salvage.requested) {
4079 VUpdateSalvagePriority_r(vp);
4082 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4083 if (vp->specialStatus) {
4084 *ec = vp->specialStatus;
4088 avp = VAttachVolumeByVp_r(ec, vp, 0);
4091 /* VAttachVolumeByVp_r can return a pointer
4092 * != the vp passed to it under certain
4093 * conditions; make sure we don't leak
4094 * reservations if that happens */
4096 VCancelReservation_r(rvp);
4098 VCreateReservation_r(rvp);
4108 if (!vp->pending_vol_op) {
4123 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4125 /* see CheckVnode() in afsfileprocs.c for an explanation
4126 * of this error code logic */
4127 afs_uint32 now = FT_ApproxTime();
4128 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4131 *client_ec = VRESTARTING;
4139 if (VIsErrorState(V_attachState(vp))) {
4140 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4141 * it, or transition it out of that state */
4150 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
4151 * not VolOpRunningUnknown (attach2 would have converted it to Online
4155 /* only valid before/during demand attachment */
4156 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
4158 /* deny getvolume due to running mutually exclusive vol op */
4159 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
4161 * volume cannot remain online during this volume operation.
4164 if (vp->specialStatus) {
4166 * special status codes outrank normal VOFFLINE code
4168 *ec = vp->specialStatus;
4170 *client_ec = vp->specialStatus;
4174 /* see CheckVnode() in afsfileprocs.c for an explanation
4175 * of this error code logic */
4176 afs_uint32 now = FT_ApproxTime();
4177 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
4180 *client_ec = VRESTARTING;
4185 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4186 FreeVolumeHeader(vp);
4190 #endif /* AFS_DEMAND_ATTACH_FS */
4192 LoadVolumeHeader(ec, vp);
4195 /* Only log the error if it was a totally unexpected error. Simply
4196 * a missing inode is likely to be caused by the volume being deleted */
4197 if (errno != ENXIO || LogLevel)
4198 Log("Volume %u: couldn't reread volume header\n",
4200 #ifdef AFS_DEMAND_ATTACH_FS
4201 if (VCanScheduleSalvage()) {
4202 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4207 #else /* AFS_DEMAND_ATTACH_FS */
4210 #endif /* AFS_DEMAND_ATTACH_FS */
4215 if (vp->shuttingDown) {
4222 if (programType == fileServer) {
4224 if (vp->goingOffline) {
4225 if (timeout && VTimedOut(timeout)) {
4226 /* we've timed out; don't wait for the vol */
4229 #ifdef AFS_DEMAND_ATTACH_FS
4230 /* wait for the volume to go offline */
4231 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4232 VTimedWaitStateChange_r(vp, timeout, NULL);
4234 #elif defined(AFS_PTHREAD_ENV)
4235 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4236 #else /* AFS_PTHREAD_ENV */
4237 /* LWP has no timed wait, so the caller better not be
4239 osi_Assert(!timeout);
4240 LWP_WaitProcess(VPutVolume);
4241 #endif /* AFS_PTHREAD_ENV */
4245 if (vp->specialStatus) {
4247 *ec = vp->specialStatus;
4248 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4251 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4262 #ifdef AFS_DEMAND_ATTACH_FS
4263 /* if no error, bump nUsers */
4266 VLRU_UpdateAccess_r(vp);
4269 VCancelReservation_r(rvp);
4272 if (client_ec && !*client_ec) {
4275 #else /* AFS_DEMAND_ATTACH_FS */
4276 /* if no error, bump nUsers */
4283 #endif /* AFS_DEMAND_ATTACH_FS */
4286 osi_Assert(vp || *ec);
4291 /***************************************************/
4292 /* Volume offline/detach routines */
4293 /***************************************************/
4295 /* caller MUST hold a heavyweight ref on vp */
4296 #ifdef AFS_DEMAND_ATTACH_FS
4298 VTakeOffline_r(Volume * vp)
4302 osi_Assert(vp->nUsers > 0);
4303 osi_Assert(programType == fileServer);
4305 VCreateReservation_r(vp);
4306 VWaitExclusiveState_r(vp);
4308 vp->goingOffline = 1;
4309 V_needsSalvaged(vp) = 1;
4311 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4312 VCancelReservation_r(vp);
4314 #else /* AFS_DEMAND_ATTACH_FS */
4316 VTakeOffline_r(Volume * vp)
4318 osi_Assert(vp->nUsers > 0);
4319 osi_Assert(programType == fileServer);
4321 vp->goingOffline = 1;
4322 V_needsSalvaged(vp) = 1;
4324 #endif /* AFS_DEMAND_ATTACH_FS */
4327 VTakeOffline(Volume * vp)
4335 * force a volume offline.
4337 * @param[in] vp volume object pointer
4338 * @param[in] flags flags (see note below)
4340 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4341 * used when VUpdateVolume_r needs to call VForceOffline_r
4342 * (which in turn would normally call VUpdateVolume_r)
4344 * @see VUpdateVolume_r
4346 * @pre VOL_LOCK must be held.
4347 * for DAFS, caller must hold ref.
4349 * @note for DAFS, it _is safe_ to call this function from an
4352 * @post needsSalvaged flag is set.
4353 * for DAFS, salvage is requested.
4354 * no further references to the volume through the volume
4355 * package will be honored.
4356 * all file descriptor and vnode caches are invalidated.
4358 * @warning this is a heavy-handed interface. it results in
4359 * a volume going offline regardless of the current
4360 * reference count state.
4362 * @internal volume package internal use only
4365 VForceOffline_r(Volume * vp, int flags)
4369 #ifdef AFS_DEMAND_ATTACH_FS
4370 VChangeState_r(vp, VOL_STATE_ERROR);
4375 strcpy(V_offlineMessage(vp),
4376 "Forced offline due to internal error: volume needs to be salvaged");
4377 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4380 vp->goingOffline = 0;
4381 V_needsSalvaged(vp) = 1;
4382 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4383 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4386 #ifdef AFS_DEMAND_ATTACH_FS
4387 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4388 #endif /* AFS_DEMAND_ATTACH_FS */
4390 #ifdef AFS_PTHREAD_ENV
4391 CV_BROADCAST(&vol_put_volume_cond);
4392 #else /* AFS_PTHREAD_ENV */
4393 LWP_NoYieldSignal(VPutVolume);
4394 #endif /* AFS_PTHREAD_ENV */
4396 VReleaseVolumeHandles_r(vp);
4400 * force a volume offline.
4402 * @param[in] vp volume object pointer
4404 * @see VForceOffline_r
4407 VForceOffline(Volume * vp)
4410 VForceOffline_r(vp, 0);
4415 * Iterate over the RX calls associated with a volume, and interrupt them.
4417 * @param[in] vp The volume whose RX calls we want to scan
4419 * @pre VOL_LOCK held
4422 VScanCalls_r(struct Volume *vp)
4424 struct VCallByVol *cbv, *ncbv;
4426 #ifdef AFS_DEMAND_ATTACH_FS
4427 VolState state_save;
4430 if (queue_IsEmpty(&vp->rx_call_list))
4431 return; /* no calls to interrupt */
4432 if (!vol_opts.interrupt_rxcall)
4433 return; /* we have no function with which to interrupt calls */
4434 err = VIsGoingOffline_r(vp);
4436 return; /* we're not going offline anymore */
4438 #ifdef AFS_DEMAND_ATTACH_FS
4439 VWaitExclusiveState_r(vp);
4440 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4442 #endif /* AFS_DEMAND_ATTACH_FS */
4444 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4446 struct rx_peer *peer;
4448 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4450 Log("Offlining volume %lu while client %s:%u is trying to read "
4451 "from it; kicking client off with error %ld\n",
4452 (long unsigned) vp->hashid,
4453 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4454 (unsigned) ntohs(rx_PortOf(peer)),
4457 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4460 #ifdef AFS_DEMAND_ATTACH_FS
4462 VChangeState_r(vp, state_save);
4463 #endif /* AFS_DEMAND_ATTACH_FS */
4466 #ifdef AFS_DEMAND_ATTACH_FS
4468 * Wait for a vp to go offline.
4470 * @param[out] ec 1 if a salvage on the volume has been requested and
4471 * salvok == 0, 0 otherwise
4472 * @param[in] vp The volume to wait for
4473 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4474 * has been requested to salvage. Otherwise we keep waiting
4475 * until the volume has gone offline.
4477 * @pre VOL_LOCK held
4478 * @pre caller holds a lightweight ref on vp
4483 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4485 struct timespec timeout_ts;
4486 const struct timespec *ts;
4489 ts = VOfflineTimeout(&timeout_ts);
4493 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4494 if (!salvok && vp->salvage.requested) {
4498 VTimedWaitStateChange_r(vp, ts, &timedout);
4501 /* we didn't time out, so the volume must be offline, so we're done */
4505 /* If we got here, we timed out waiting for the volume to go offline.
4506 * Kick off the accessing RX calls and wait again */
4510 while (!VIsOfflineState(V_attachState(vp))) {
4511 if (!salvok && vp->salvage.requested) {
4516 VWaitStateChange_r(vp);
4520 #else /* AFS_DEMAND_ATTACH_FS */
4523 * Wait for a volume to go offline.
4525 * @pre VOL_LOCK held
4527 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4530 VWaitForOffline_r(Error *ec, VolumeId volid)
4533 const struct timespec *ts;
4534 #ifdef AFS_PTHREAD_ENV
4535 struct timespec timeout_ts;
4538 ts = VOfflineTimeout(&timeout_ts);
4540 vp = GetVolume(ec, NULL, volid, NULL, ts);
4542 /* error occurred so bad that we can't even get a vp; we have no
4543 * information on the vol so we don't know whether to wait, so just
4547 if (!VIsGoingOffline_r(vp)) {
4548 /* volume is no longer going offline, so we're done */
4553 /* If we got here, we timed out waiting for the volume to go offline.
4554 * Kick off the accessing RX calls and wait again */
4560 vp = VGetVolume_r(ec, volid);
4562 /* In case it was reattached... */
4566 #endif /* !AFS_DEMAND_ATTACH_FS */
4568 /* The opposite of VAttachVolume. The volume header is written to disk, with
4569 the inUse bit turned off. A copy of the header is maintained in memory,
4570 however (which is why this is VOffline, not VDetach).
4573 VOffline_r(Volume * vp, char *message)
4576 #ifndef AFS_DEMAND_ATTACH_FS
4577 VolumeId vid = V_id(vp);
4580 osi_Assert(programType != volumeUtility && programType != volumeServer);
4585 if (V_offlineMessage(vp)[0] == '\0')
4586 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4587 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4589 vp->goingOffline = 1;
4590 #ifdef AFS_DEMAND_ATTACH_FS
4591 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4592 VCreateReservation_r(vp);
4594 VWaitForOfflineByVp_r(&error, vp, 1);
4595 VCancelReservation_r(vp);
4596 #else /* AFS_DEMAND_ATTACH_FS */
4598 VWaitForOffline_r(&error, vid);
4599 #endif /* AFS_DEMAND_ATTACH_FS */
4602 #ifdef AFS_DEMAND_ATTACH_FS
4604 * Take a volume offline in order to perform a volume operation.
4606 * @param[inout] ec address in which to store error code
4607 * @param[in] vp volume object pointer
4608 * @param[in] message volume offline status message
4611 * - VOL_LOCK is held
4612 * - caller MUST hold a heavyweight ref on vp
4615 * - volume is taken offline
4616 * - if possible, volume operation is promoted to running state
4617 * - on failure, *ec is set to nonzero
4619 * @note Although this function does not return any value, it may
4620 * still fail to promote our pending volume operation to
4621 * a running state. Any caller MUST check the value of *ec,
4622 * and MUST NOT blindly assume success.
4624 * @warning if the caller does not hold a lightweight ref on vp,
4625 * then it MUST NOT reference vp after this function
4626 * returns to the caller.
4628 * @internal volume package internal use only
4631 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4634 osi_Assert(vp->pending_vol_op);
4640 if (V_offlineMessage(vp)[0] == '\0')
4641 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4642 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4644 vp->goingOffline = 1;
4645 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4646 VCreateReservation_r(vp);
4649 if (vp->pending_vol_op->com.programType != salvageServer) {
4650 /* do not give corrupted volumes to the volserver */
4655 VWaitForOfflineByVp_r(ec, vp, salvok);
4657 VCancelReservation_r(vp);
4659 #endif /* AFS_DEMAND_ATTACH_FS */
4662 VOffline(Volume * vp, char *message)
4665 VOffline_r(vp, message);
4669 /* This gets used for the most part by utility routines that don't want
4670 * to keep all the volume headers around. Generally, the file server won't
4671 * call this routine, because then the offline message in the volume header
4672 * (or other information) won't be available to clients. For NAMEI, also
4673 * close the file handles. However, the fileserver does call this during
4674 * an attach following a volume operation.
4677 VDetachVolume_r(Error * ec, Volume * vp)
4679 #ifdef FSSYNC_BUILD_CLIENT
4681 struct DiskPartition64 *tpartp;
4682 int notifyServer = 0;
4683 int useDone = FSYNC_VOL_ON;
4685 if (VCanUseFSSYNC()) {
4686 notifyServer = vp->needsPutBack;
4687 if (V_destroyMe(vp) == DESTROY_ME)
4688 useDone = FSYNC_VOL_LEAVE_OFF;
4689 # ifdef AFS_DEMAND_ATTACH_FS
4690 else if (!V_blessed(vp) || !V_inService(vp))
4691 useDone = FSYNC_VOL_LEAVE_OFF;
4694 # ifdef AFS_DEMAND_ATTACH_FS
4695 if (V_needsSalvaged(vp)) {
4697 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4700 tpartp = vp->partition;
4702 #endif /* FSSYNC_BUILD_CLIENT */
4704 *ec = 0; /* always "succeeds" */
4705 DeleteVolumeFromHashTable(vp);
4706 vp->shuttingDown = 1;
4707 #ifdef AFS_DEMAND_ATTACH_FS
4708 DeleteVolumeFromVByPList_r(vp);
4710 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4712 if (programType != fileServer)
4714 #endif /* AFS_DEMAND_ATTACH_FS */
4716 /* Will be detached sometime in the future--this is OK since volume is offline */
4718 /* XXX the following code should really be moved to VCheckDetach() since the volume
4719 * is not technically detached until the refcounts reach zero
4721 #ifdef FSSYNC_BUILD_CLIENT
4722 if (VCanUseFSSYNC() && notifyServer) {
4723 if (notifyServer == VOL_PUTBACK_DELETE) {
4724 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4725 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4726 * to signify a deleted volume. */
4727 useDone = FSYNC_VOL_DONE;
4730 * Note: The server is not notified in the case of a bogus volume
4731 * explicitly to make it possible to create a volume, do a partial
4732 * restore, then abort the operation without ever putting the volume
4733 * online. This is essential in the case of a volume move operation
4734 * between two partitions on the same server. In that case, there
4735 * would be two instances of the same volume, one of them bogus,
4736 * which the file server would attempt to put on line
4738 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4739 /* XXX this code path is only hit by volume utilities, thus
4740 * V_BreakVolumeCallbacks will always be NULL. if we really
4741 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4743 /* Dettaching it so break all callbacks on it */
4744 if (V_BreakVolumeCallbacks) {
4745 Log("volume %u detached; breaking all call backs\n", volume);
4746 (*V_BreakVolumeCallbacks) (volume);
4750 #endif /* FSSYNC_BUILD_CLIENT */
4754 VDetachVolume(Error * ec, Volume * vp)
4757 VDetachVolume_r(ec, vp);
4762 /***************************************************/
4763 /* Volume fd/inode handle closing routines */
4764 /***************************************************/
4766 /* For VDetachVolume, we close all cached file descriptors, but keep
4767 * the Inode handles in case we need to read from a busy volume.
4769 /* for demand attach, caller MUST hold ref count on vp */
4771 VCloseVolumeHandles_r(Volume * vp)
4773 #ifdef AFS_DEMAND_ATTACH_FS
4774 VolState state_save;
4776 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4781 DFlushVolume(vp->hashid);
4783 #ifdef AFS_DEMAND_ATTACH_FS
4787 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4788 VCloseVnodeFiles_r(vp);
4790 #ifdef AFS_DEMAND_ATTACH_FS
4794 /* Too time consuming and unnecessary for the volserver */
4795 if (programType == fileServer) {
4796 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4797 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4798 IH_CONDSYNC(vp->diskDataHandle);
4800 IH_CONDSYNC(vp->linkHandle);
4801 #endif /* AFS_NT40_ENV */
4804 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4805 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4806 IH_REALLYCLOSE(vp->diskDataHandle);
4807 IH_REALLYCLOSE(vp->linkHandle);
4809 #ifdef AFS_DEMAND_ATTACH_FS
4810 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4815 VChangeState_r(vp, state_save);
4819 /* For both VForceOffline and VOffline, we close all relevant handles.
4820 * For VOffline, if we re-attach the volume, the files may possible be
4821 * different than before.
4823 /* for demand attach, caller MUST hold a ref count on vp */
4825 VReleaseVolumeHandles_r(Volume * vp)
4827 #ifdef AFS_DEMAND_ATTACH_FS
4828 VolState state_save;
4830 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4835 DFlushVolume(vp->hashid);
4837 #ifdef AFS_DEMAND_ATTACH_FS
4841 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4843 #ifdef AFS_DEMAND_ATTACH_FS
4847 /* Too time consuming and unnecessary for the volserver */
4848 if (programType == fileServer) {
4849 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4850 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4851 IH_CONDSYNC(vp->diskDataHandle);
4853 IH_CONDSYNC(vp->linkHandle);
4854 #endif /* AFS_NT40_ENV */
4857 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4858 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4859 IH_RELEASE(vp->diskDataHandle);
4860 IH_RELEASE(vp->linkHandle);
4862 #ifdef AFS_DEMAND_ATTACH_FS
4863 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4868 VChangeState_r(vp, state_save);
4873 /***************************************************/
4874 /* Volume write and fsync routines */
4875 /***************************************************/
4878 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4880 #ifdef AFS_DEMAND_ATTACH_FS
4881 VolState state_save;
4883 if (flags & VOL_UPDATE_WAIT) {
4884 VCreateReservation_r(vp);
4885 VWaitExclusiveState_r(vp);
4890 if (programType == fileServer)
4892 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4893 200 : V_nextVnodeUnique(vp));
4895 #ifdef AFS_DEMAND_ATTACH_FS
4896 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4900 WriteVolumeHeader_r(ec, vp);
4902 #ifdef AFS_DEMAND_ATTACH_FS
4904 VChangeState_r(vp, state_save);
4905 if (flags & VOL_UPDATE_WAIT) {
4906 VCancelReservation_r(vp);
4911 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4912 V_id(vp), V_name(vp));
4913 /* try to update on-disk header,
4914 * while preventing infinite recursion */
4915 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4916 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4922 VUpdateVolume(Error * ec, Volume * vp)
4925 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4930 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4934 #ifdef AFS_DEMAND_ATTACH_FS
4935 VolState state_save;
4938 if (flags & VOL_SYNC_WAIT) {
4939 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4941 VUpdateVolume_r(ec, vp, 0);
4944 #ifdef AFS_DEMAND_ATTACH_FS
4945 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4948 fdP = IH_OPEN(V_diskDataHandle(vp));
4949 osi_Assert(fdP != NULL);
4950 code = FDH_SYNC(fdP);
4951 osi_Assert(code == 0);
4953 #ifdef AFS_DEMAND_ATTACH_FS
4955 VChangeState_r(vp, state_save);
4961 VSyncVolume(Error * ec, Volume * vp)
4964 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4969 /***************************************************/
4970 /* Volume dealloaction routines */
4971 /***************************************************/
4973 #ifdef AFS_DEMAND_ATTACH_FS
4975 FreeVolume(Volume * vp)
4977 /* free the heap space, iff it's safe.
4978 * otherwise, pull it out of the hash table, so it
4979 * will get deallocated when all refs to it go away */
4980 if (!VCheckFree(vp)) {
4981 DeleteVolumeFromHashTable(vp);
4982 DeleteVolumeFromVByPList_r(vp);
4984 /* make sure we invalidate the header cache entry */
4985 FreeVolumeHeader(vp);
4988 #endif /* AFS_DEMAND_ATTACH_FS */
4991 ReallyFreeVolume(Volume * vp)
4996 #ifdef AFS_DEMAND_ATTACH_FS
4998 VChangeState_r(vp, VOL_STATE_FREED);
4999 if (vp->pending_vol_op)
5000 free(vp->pending_vol_op);
5001 #endif /* AFS_DEMAND_ATTACH_FS */
5002 for (i = 0; i < nVNODECLASSES; i++)
5003 if (vp->vnodeIndex[i].bitmap)
5004 free(vp->vnodeIndex[i].bitmap);
5005 FreeVolumeHeader(vp);
5006 #ifndef AFS_DEMAND_ATTACH_FS
5007 DeleteVolumeFromHashTable(vp);
5008 #endif /* AFS_DEMAND_ATTACH_FS */
5012 /* check to see if we should shutdown this volume
5013 * returns 1 if volume was freed, 0 otherwise */
5014 #ifdef AFS_DEMAND_ATTACH_FS
5016 VCheckDetach(Volume * vp)
5021 if (vp->nUsers || vp->nWaiters)
5024 if (vp->shuttingDown) {
5026 if ((programType != fileServer) &&
5027 (V_inUse(vp) == programType) &&
5028 ((V_checkoutMode(vp) == V_VOLUPD) ||
5029 (V_checkoutMode(vp) == V_SECRETLY) ||
5030 ((V_checkoutMode(vp) == V_CLONE) &&
5031 (VolumeWriteable(vp))))) {
5033 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5035 Log("VCheckDetach: volume header update for volume %u "
5036 "failed with errno %d\n", vp->hashid, errno);
5039 VReleaseVolumeHandles_r(vp);
5041 ReallyFreeVolume(vp);
5042 if (programType == fileServer) {
5043 CV_BROADCAST(&vol_put_volume_cond);
5048 #else /* AFS_DEMAND_ATTACH_FS */
5050 VCheckDetach(Volume * vp)
5058 if (vp->shuttingDown) {
5060 if ((programType != fileServer) &&
5061 (V_inUse(vp) == programType) &&
5062 ((V_checkoutMode(vp) == V_VOLUPD) ||
5063 (V_checkoutMode(vp) == V_SECRETLY) ||
5064 ((V_checkoutMode(vp) == V_CLONE) &&
5065 (VolumeWriteable(vp))))) {
5067 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5069 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5073 VReleaseVolumeHandles_r(vp);
5074 ReallyFreeVolume(vp);
5075 if (programType == fileServer) {
5076 #if defined(AFS_PTHREAD_ENV)
5077 CV_BROADCAST(&vol_put_volume_cond);
5078 #else /* AFS_PTHREAD_ENV */
5079 LWP_NoYieldSignal(VPutVolume);
5080 #endif /* AFS_PTHREAD_ENV */
5085 #endif /* AFS_DEMAND_ATTACH_FS */
5087 /* check to see if we should offline this volume
5088 * return 1 if volume went offline, 0 otherwise */
5089 #ifdef AFS_DEMAND_ATTACH_FS
5091 VCheckOffline(Volume * vp)
5095 if (vp->goingOffline && !vp->nUsers) {
5097 osi_Assert(programType == fileServer);
5098 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5099 (V_attachState(vp) != VOL_STATE_FREED) &&
5100 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5101 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5102 (V_attachState(vp) != VOL_STATE_DELETED));
5106 * VOL_STATE_GOING_OFFLINE
5107 * VOL_STATE_SHUTTING_DOWN
5108 * VIsErrorState(V_attachState(vp))
5109 * VIsExclusiveState(V_attachState(vp))
5112 VCreateReservation_r(vp);
5113 VChangeState_r(vp, VOL_STATE_OFFLINING);
5116 /* must clear the goingOffline flag before we drop the glock */
5117 vp->goingOffline = 0;
5122 /* perform async operations */
5123 VUpdateVolume_r(&error, vp, 0);
5124 VCloseVolumeHandles_r(vp);
5127 if (V_offlineMessage(vp)[0]) {
5128 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5129 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5130 V_offlineMessage(vp));
5132 Log("VOffline: Volume %lu (%s) is now offline\n",
5133 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5137 /* invalidate the volume header cache entry */
5138 FreeVolumeHeader(vp);
5140 /* if nothing changed state to error or salvaging,
5141 * drop state to unattached */
5142 if (!VIsErrorState(V_attachState(vp))) {
5143 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5145 VCancelReservation_r(vp);
5146 /* no usage of vp is safe beyond this point */
5150 #else /* AFS_DEMAND_ATTACH_FS */
5152 VCheckOffline(Volume * vp)
5156 if (vp->goingOffline && !vp->nUsers) {
5158 osi_Assert(programType == fileServer);
5161 vp->goingOffline = 0;
5163 VUpdateVolume_r(&error, vp, 0);
5164 VCloseVolumeHandles_r(vp);
5166 if (V_offlineMessage(vp)[0]) {
5167 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5168 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5169 V_offlineMessage(vp));
5171 Log("VOffline: Volume %lu (%s) is now offline\n",
5172 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5175 FreeVolumeHeader(vp);
5176 #ifdef AFS_PTHREAD_ENV
5177 CV_BROADCAST(&vol_put_volume_cond);
5178 #else /* AFS_PTHREAD_ENV */
5179 LWP_NoYieldSignal(VPutVolume);
5180 #endif /* AFS_PTHREAD_ENV */
5184 #endif /* AFS_DEMAND_ATTACH_FS */
5186 /***************************************************/
5187 /* demand attach fs ref counting routines */
5188 /***************************************************/
5190 #ifdef AFS_DEMAND_ATTACH_FS
5191 /* the following two functions handle reference counting for
5192 * asynchronous operations on volume structs.
5194 * their purpose is to prevent a VDetachVolume or VShutdown
5195 * from free()ing the Volume struct during an async i/o op */
5197 /* register with the async volume op ref counter */
5198 /* VCreateReservation_r moved into inline code header because it
5199 * is now needed in vnode.c -- tkeiser 11/20/2007
5203 * decrement volume-package internal refcount.
5205 * @param vp volume object pointer
5207 * @internal volume package internal use only
5210 * @arg VOL_LOCK is held
5211 * @arg lightweight refcount held
5213 * @post volume waiters refcount is decremented; volume may
5214 * have been deallocated/shutdown/offlined/salvaged/
5215 * whatever during the process
5217 * @warning once you have tossed your last reference (you can acquire
5218 * lightweight refs recursively) it is NOT SAFE to reference
5219 * a volume object pointer ever again
5221 * @see VCreateReservation_r
5223 * @note DEMAND_ATTACH_FS only
5226 VCancelReservation_r(Volume * vp)
5228 osi_Assert(--vp->nWaiters >= 0);
5229 if (vp->nWaiters == 0) {
5231 if (!VCheckDetach(vp)) {
5238 /* check to see if we should free this volume now
5239 * return 1 if volume was freed, 0 otherwise */
5241 VCheckFree(Volume * vp)
5244 if ((vp->nUsers == 0) &&
5245 (vp->nWaiters == 0) &&
5246 !(V_attachFlags(vp) & (VOL_IN_HASH |
5250 ReallyFreeVolume(vp);
5255 #endif /* AFS_DEMAND_ATTACH_FS */
5258 /***************************************************/
5259 /* online volume operations routines */
5260 /***************************************************/
5262 #ifdef AFS_DEMAND_ATTACH_FS
5264 * register a volume operation on a given volume.
5266 * @param[in] vp volume object
5267 * @param[in] vopinfo volume operation info object
5269 * @pre VOL_LOCK is held
5271 * @post volume operation info object attached to volume object.
5272 * volume operation statistics updated.
5274 * @note by "attached" we mean a copy of the passed in object is made
5276 * @internal volume package internal use only
5279 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5281 FSSYNC_VolOp_info * info;
5283 /* attach a vol op info node to the volume struct */
5284 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5285 osi_Assert(info != NULL);
5286 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5287 vp->pending_vol_op = info;
5290 vp->stats.last_vol_op = FT_ApproxTime();
5291 vp->stats.vol_ops++;
5292 IncUInt64(&VStats.vol_ops);
5298 * deregister the volume operation attached to this volume.
5300 * @param[in] vp volume object pointer
5302 * @pre VOL_LOCK is held
5304 * @post the volume operation info object is detached from the volume object
5306 * @internal volume package internal use only
5309 VDeregisterVolOp_r(Volume * vp)
5311 if (vp->pending_vol_op) {
5312 free(vp->pending_vol_op);
5313 vp->pending_vol_op = NULL;
5317 #endif /* AFS_DEMAND_ATTACH_FS */
5320 * determine whether it is safe to leave a volume online during
5321 * the volume operation described by the vopinfo object.
5323 * @param[in] vp volume object
5324 * @param[in] vopinfo volume operation info object
5326 * @return whether it is safe to leave volume online
5327 * @retval 0 it is NOT SAFE to leave the volume online
5328 * @retval 1 it is safe to leave the volume online during the operation
5331 * @arg VOL_LOCK is held
5332 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5333 * this condition is met)
5335 * @internal volume package internal use only
5338 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5340 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5341 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5342 (vopinfo->com.reason == V_READONLY ||
5343 (!VolumeWriteable(vp) &&
5344 (vopinfo->com.reason == V_CLONE ||
5345 vopinfo->com.reason == V_DUMP)))));
5349 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5352 * @param[in] vp volume object
5353 * @param[in] vopinfo volume operation info object
5355 * @return whether it is safe to leave volume online
5356 * @retval 0 it is NOT SAFE to leave the volume online
5357 * @retval 1 it is safe to leave the volume online during the operation
5358 * @retval -1 unsure; volume header is required in order to know whether or
5359 * not is is safe to leave the volume online
5361 * @pre VOL_LOCK is held
5363 * @internal volume package internal use only
5366 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5368 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5369 * assume that we don't know VolumeWriteable; return -1 if the answer
5370 * depends on VolumeWriteable */
5372 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5375 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5376 vopinfo->com.reason == V_READONLY) {
5380 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5381 (vopinfo->com.reason == V_CLONE ||
5382 vopinfo->com.reason == V_DUMP)) {
5384 /* must know VolumeWriteable */
5391 * determine whether VBUSY should be set during this volume operation.
5393 * @param[in] vp volume object
5394 * @param[in] vopinfo volume operation info object
5396 * @return whether VBUSY should be set
5397 * @retval 0 VBUSY does NOT need to be set
5398 * @retval 1 VBUSY SHOULD be set
5400 * @pre VOL_LOCK is held
5402 * @internal volume package internal use only
5405 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5407 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5408 vopinfo->com.reason == FSYNC_SALVAGE) ||
5409 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5410 (vopinfo->com.reason == V_CLONE ||
5411 vopinfo->com.reason == V_DUMP)));
5415 /***************************************************/
5416 /* online salvager routines */
5417 /***************************************************/
5418 #if defined(AFS_DEMAND_ATTACH_FS)
5421 * offline a volume to let it be salvaged.
5423 * @param[in] vp Volume to offline
5425 * @return whether we offlined the volume successfully
5426 * @retval 0 volume was not offlined
5427 * @retval 1 volume is now offline
5429 * @note This is similar to VCheckOffline, but slightly different. We do not
5430 * deal with vp->goingOffline, and we try to avoid touching the volume
5431 * header except just to set needsSalvaged
5433 * @pre VOL_LOCK held
5434 * @pre vp->nUsers == 0
5435 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5438 VOfflineForSalvage_r(struct Volume *vp)
5442 VCreateReservation_r(vp);
5443 VWaitExclusiveState_r(vp);
5445 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5446 /* Someone's using the volume, or someone got to scheduling the salvage
5447 * before us. I don't think either of these should be possible, as we
5448 * should gain no new heavyweight references while we're trying to
5449 * salvage, but just to be sure... */
5450 VCancelReservation_r(vp);
5454 VChangeState_r(vp, VOL_STATE_OFFLINING);
5458 V_needsSalvaged(vp) = 1;
5459 /* ignore error; updating needsSalvaged is just best effort */
5460 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5462 VCloseVolumeHandles_r(vp);
5464 FreeVolumeHeader(vp);
5466 /* volume has been effectively offlined; we can mark it in the SALVAGING
5467 * state now, which lets FSSYNC give it away */
5468 VChangeState_r(vp, VOL_STATE_SALVAGING);
5470 VCancelReservation_r(vp);
5476 * check whether a salvage needs to be performed on this volume.
5478 * @param[in] vp pointer to volume object
5480 * @return status code
5481 * @retval 0 no salvage scheduled
5482 * @retval 1 a salvage has been scheduled with the salvageserver
5484 * @pre VOL_LOCK is held
5486 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5487 * then a salvage will be requested
5489 * @note this is one of the event handlers called by VCancelReservation_r
5491 * @note the caller must check if the volume needs to be freed after calling
5492 * this; the volume may not have any references or be on any lists after
5493 * we return, and we do not free it
5495 * @see VCancelReservation_r
5497 * @internal volume package internal use only.
5500 VCheckSalvage(Volume * vp)
5503 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5506 if (!vp->salvage.requested) {
5510 /* prevent recursion; some of the code below creates and removes
5511 * lightweight refs, which can call VCheckSalvage */
5512 if (vp->salvage.scheduling) {
5515 vp->salvage.scheduling = 1;
5517 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5518 if (!VOfflineForSalvage_r(vp)) {
5519 vp->salvage.scheduling = 0;
5524 if (vp->salvage.requested) {
5525 VScheduleSalvage_r(vp);
5528 vp->salvage.scheduling = 0;
5529 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5534 * request volume salvage.
5536 * @param[out] ec computed client error code
5537 * @param[in] vp volume object pointer
5538 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5539 * @param[in] flags see flags note below
5542 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5543 * not been fully attached
5545 * @pre VOL_LOCK is held.
5547 * @post volume state is changed.
5548 * for fileserver, salvage will be requested once refcount reaches zero.
5550 * @return operation status code
5551 * @retval 0 volume salvage will occur
5552 * @retval 1 volume salvage could not be scheduled
5556 * @note in the fileserver, this call does not synchronously schedule a volume
5557 * salvage. rather, it sets volume state so that when volume refcounts
5558 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5559 * nUsers and nWaiters must be zero.
5561 * @internal volume package internal use only.
5564 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5568 * for DAFS volume utilities that are not supposed to schedule salvages,
5569 * just transition to error state instead
5571 if (!VCanScheduleSalvage()) {
5572 VChangeState_r(vp, VOL_STATE_ERROR);
5577 if (programType != fileServer && !VCanUseFSSYNC()) {
5578 VChangeState_r(vp, VOL_STATE_ERROR);
5583 if (!vp->salvage.requested) {
5584 vp->salvage.requested = 1;
5585 vp->salvage.reason = reason;
5586 vp->stats.last_salvage = FT_ApproxTime();
5588 /* Note that it is not possible for us to reach this point if a
5589 * salvage is already running on this volume (even if the fileserver
5590 * was restarted during the salvage). If a salvage were running, the
5591 * salvager would have write-locked the volume header file, so when
5592 * we tried to lock the volume header, the lock would have failed,
5593 * and we would have failed during attachment prior to calling
5594 * VRequestSalvage. So we know that we can schedule salvages without
5595 * fear of a salvage already running for this volume. */
5597 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5599 /* if we don't need to offline the volume, we can go directly
5600 * to SALVAGING. SALVAGING says the volume is offline and is
5601 * either salvaging or ready to be handed to the salvager.
5602 * SALVAGE_REQ says that we want to salvage the volume, but we
5603 * are waiting for it to go offline first. */
5604 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5605 VChangeState_r(vp, VOL_STATE_SALVAGING);
5607 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5608 if (vp->nUsers == 0) {
5609 /* normally VOfflineForSalvage_r would be called from
5610 * PutVolume et al when nUsers reaches 0, but if
5611 * it's already 0, just do it ourselves, since PutVolume
5612 * isn't going to get called */
5613 VOfflineForSalvage_r(vp);
5616 /* If we are non-fileserver, we're telling the fileserver to
5617 * salvage the vol, so we don't need to give it back separately. */
5618 vp->needsPutBack = 0;
5622 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5624 /* make sure neither VScheduleSalvage_r nor
5625 * VUpdateSalvagePriority_r try to schedule another salvage */
5626 vp->salvage.requested = vp->salvage.scheduled = 0;
5628 VChangeState_r(vp, VOL_STATE_ERROR);
5637 * update salvageserver scheduling priority for a volume.
5639 * @param[in] vp pointer to volume object
5641 * @return operation status
5643 * @retval 1 request denied, or SALVSYNC communications failure
5645 * @pre VOL_LOCK is held.
5647 * @post in-core salvage priority counter is incremented. if at least
5648 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5649 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5650 * to update its priority queue. if no salvage is scheduled,
5651 * this function is a no-op.
5653 * @note DAFS fileserver only
5655 * @note this should be called whenever a VGetVolume fails due to a
5656 * pending salvage request
5658 * @todo should set exclusive state and drop glock around salvsync call
5660 * @internal volume package internal use only.
5663 VUpdateSalvagePriority_r(Volume * vp)
5667 #ifdef SALVSYNC_BUILD_CLIENT
5672 now = FT_ApproxTime();
5674 /* update the salvageserver priority queue occasionally so that
5675 * frequently requested volumes get moved to the head of the queue
5677 if ((vp->salvage.scheduled) &&
5678 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5679 code = SALVSYNC_SalvageVolume(vp->hashid,
5680 VPartitionPath(vp->partition),
5685 vp->stats.last_salvage_req = now;
5686 if (code != SYNC_OK) {
5690 #endif /* SALVSYNC_BUILD_CLIENT */
5695 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5697 /* A couple of little helper functions. These return true if we tried to
5698 * use this mechanism to schedule a salvage, false if we haven't tried.
5699 * If we did try a salvage then the results are contained in code.
5703 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5704 #ifdef SALVSYNC_BUILD_CLIENT
5705 if (VCanUseSALVSYNC()) {
5706 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5707 afs_printable_uint32_lu(vp->hashid), partName);
5709 /* can't use V_id() since there's no guarantee
5710 * we have the disk data header at this point */
5711 *code = SALVSYNC_SalvageVolume(vp->hashid,
5724 try_FSSYNC(Volume *vp, char *partName, int *code) {
5725 #ifdef FSSYNC_BUILD_CLIENT
5726 if (VCanUseFSSYNC()) {
5727 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5728 afs_printable_uint32_lu(vp->hashid), partName);
5731 * If we aren't the fileserver, tell the fileserver the volume
5732 * needs to be salvaged. We could directly tell the
5733 * salvageserver, but the fileserver keeps track of some stats
5734 * related to salvages, and handles some other salvage-related
5735 * complications for us.
5737 *code = FSYNC_VolOp(vp->hashid, partName,
5738 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5741 #endif /* FSSYNC_BUILD_CLIENT */
5746 * schedule a salvage with the salvage server or fileserver.
5748 * @param[in] vp pointer to volume object
5750 * @return operation status
5751 * @retval 0 salvage scheduled successfully
5752 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5755 * @arg VOL_LOCK is held.
5756 * @arg nUsers and nWaiters should be zero.
5758 * @post salvageserver or fileserver is sent a salvage request
5760 * @note If we are the fileserver, the request will be sent to the salvage
5761 * server over SALVSYNC. If we are not the fileserver, the request will be
5762 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5764 * @note the caller must check if the volume needs to be freed after calling
5765 * this; the volume may not have any references or be on any lists after
5766 * we return, and we do not free it
5770 * @internal volume package internal use only.
5773 VScheduleSalvage_r(Volume * vp)
5777 VolState state_save;
5778 VThreadOptions_t * thread_opts;
5781 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5783 if (vp->nWaiters || vp->nUsers) {
5787 /* prevent endless salvage,attach,salvage,attach,... loops */
5788 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5792 * don't perform salvsync ops on certain threads
5794 thread_opts = pthread_getspecific(VThread_key);
5795 if (thread_opts == NULL) {
5796 thread_opts = &VThread_defaults;
5798 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5802 if (vp->salvage.scheduled) {
5806 VCreateReservation_r(vp);
5807 VWaitExclusiveState_r(vp);
5810 * XXX the scheduling process should really be done asynchronously
5811 * to avoid fssync deadlocks
5813 if (!vp->salvage.scheduled) {
5814 /* if we haven't previously scheduled a salvage, do so now
5816 * set the volume to an exclusive state and drop the lock
5817 * around the SALVSYNC call
5819 strlcpy(partName, vp->partition->name, sizeof(partName));
5820 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5823 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5824 try_FSSYNC(vp, partName, &code));
5827 VChangeState_r(vp, state_save);
5829 if (code == SYNC_OK) {
5830 vp->salvage.scheduled = 1;
5831 vp->stats.last_salvage_req = FT_ApproxTime();
5832 if (VCanUseSALVSYNC()) {
5833 /* don't record these stats for non-fileservers; let the
5834 * fileserver take care of these */
5835 vp->stats.salvages++;
5836 IncUInt64(&VStats.salvages);
5841 case SYNC_BAD_COMMAND:
5842 case SYNC_COM_ERROR:
5845 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5846 "denied\n", afs_printable_uint32_lu(vp->hashid));
5849 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5850 "failed\n", afs_printable_uint32_lu(vp->hashid));
5853 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5854 "received unknown protocol error %d\n",
5855 afs_printable_uint32_lu(vp->hashid), code);
5859 if (VCanUseFSSYNC()) {
5860 VChangeState_r(vp, VOL_STATE_ERROR);
5865 /* NB: this is cancelling the reservation we obtained above, but we do
5866 * not call VCancelReservation_r, since that may trigger the vp dtor,
5867 * possibly free'ing the vp. We need to keep the vp around after
5868 * this, as the caller may reference vp without any refs. Instead, it
5869 * is the duty of the caller to inspect 'vp' after we return to see if
5870 * needs to be freed. */
5871 osi_Assert(--vp->nWaiters >= 0);
5874 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5876 #ifdef SALVSYNC_BUILD_CLIENT
5879 * connect to the salvageserver SYNC service.
5881 * @return operation status
5885 * @post connection to salvageserver SYNC service established
5887 * @see VConnectSALV_r
5888 * @see VDisconnectSALV
5889 * @see VReconnectSALV
5896 retVal = VConnectSALV_r();
5902 * connect to the salvageserver SYNC service.
5904 * @return operation status
5908 * @pre VOL_LOCK is held.
5910 * @post connection to salvageserver SYNC service established
5913 * @see VDisconnectSALV_r
5914 * @see VReconnectSALV_r
5915 * @see SALVSYNC_clientInit
5917 * @internal volume package internal use only.
5920 VConnectSALV_r(void)
5922 return SALVSYNC_clientInit();
5926 * disconnect from the salvageserver SYNC service.
5928 * @return operation status
5931 * @pre client should have a live connection to the salvageserver
5933 * @post connection to salvageserver SYNC service destroyed
5935 * @see VDisconnectSALV_r
5937 * @see VReconnectSALV
5940 VDisconnectSALV(void)
5943 VDisconnectSALV_r();
5949 * disconnect from the salvageserver SYNC service.
5951 * @return operation status
5955 * @arg VOL_LOCK is held.
5956 * @arg client should have a live connection to the salvageserver.
5958 * @post connection to salvageserver SYNC service destroyed
5960 * @see VDisconnectSALV
5961 * @see VConnectSALV_r
5962 * @see VReconnectSALV_r
5963 * @see SALVSYNC_clientFinis
5965 * @internal volume package internal use only.
5968 VDisconnectSALV_r(void)
5970 return SALVSYNC_clientFinis();
5974 * disconnect and then re-connect to the salvageserver SYNC service.
5976 * @return operation status
5980 * @pre client should have a live connection to the salvageserver
5982 * @post old connection is dropped, and a new one is established
5985 * @see VDisconnectSALV
5986 * @see VReconnectSALV_r
5989 VReconnectSALV(void)
5993 retVal = VReconnectSALV_r();
5999 * disconnect and then re-connect to the salvageserver SYNC service.
6001 * @return operation status
6006 * @arg VOL_LOCK is held.
6007 * @arg client should have a live connection to the salvageserver.
6009 * @post old connection is dropped, and a new one is established
6011 * @see VConnectSALV_r
6012 * @see VDisconnectSALV
6013 * @see VReconnectSALV
6014 * @see SALVSYNC_clientReconnect
6016 * @internal volume package internal use only.
6019 VReconnectSALV_r(void)
6021 return SALVSYNC_clientReconnect();
6023 #endif /* SALVSYNC_BUILD_CLIENT */
6024 #endif /* AFS_DEMAND_ATTACH_FS */
6027 /***************************************************/
6028 /* FSSYNC routines */
6029 /***************************************************/
6031 /* This must be called by any volume utility which needs to run while the
6032 file server is also running. This is separated from VInitVolumePackage2 so
6033 that a utility can fork--and each of the children can independently
6034 initialize communication with the file server */
6035 #ifdef FSSYNC_BUILD_CLIENT
6037 * connect to the fileserver SYNC service.
6039 * @return operation status
6044 * @arg VInit must equal 2.
6045 * @arg Program Type must not be fileserver or salvager.
6047 * @post connection to fileserver SYNC service established
6050 * @see VDisconnectFS
6051 * @see VChildProcReconnectFS
6058 retVal = VConnectFS_r();
6064 * connect to the fileserver SYNC service.
6066 * @return operation status
6071 * @arg VInit must equal 2.
6072 * @arg Program Type must not be fileserver or salvager.
6073 * @arg VOL_LOCK is held.
6075 * @post connection to fileserver SYNC service established
6078 * @see VDisconnectFS_r
6079 * @see VChildProcReconnectFS_r
6081 * @internal volume package internal use only.
6087 osi_Assert((VInit == 2) &&
6088 (programType != fileServer) &&
6089 (programType != salvager));
6090 rc = FSYNC_clientInit();
6098 * disconnect from the fileserver SYNC service.
6101 * @arg client should have a live connection to the fileserver.
6102 * @arg VOL_LOCK is held.
6103 * @arg Program Type must not be fileserver or salvager.
6105 * @post connection to fileserver SYNC service destroyed
6107 * @see VDisconnectFS
6109 * @see VChildProcReconnectFS_r
6111 * @internal volume package internal use only.
6114 VDisconnectFS_r(void)
6116 osi_Assert((programType != fileServer) &&
6117 (programType != salvager));
6118 FSYNC_clientFinis();
6123 * disconnect from the fileserver SYNC service.
6126 * @arg client should have a live connection to the fileserver.
6127 * @arg Program Type must not be fileserver or salvager.
6129 * @post connection to fileserver SYNC service destroyed
6131 * @see VDisconnectFS_r
6133 * @see VChildProcReconnectFS
6144 * connect to the fileserver SYNC service from a child process following a fork.
6146 * @return operation status
6151 * @arg VOL_LOCK is held.
6152 * @arg current FSYNC handle is shared with a parent process
6154 * @post current FSYNC handle is discarded and a new connection to the
6155 * fileserver SYNC service is established
6157 * @see VChildProcReconnectFS
6159 * @see VDisconnectFS_r
6161 * @internal volume package internal use only.
6164 VChildProcReconnectFS_r(void)
6166 return FSYNC_clientChildProcReconnect();
6170 * connect to the fileserver SYNC service from a child process following a fork.
6172 * @return operation status
6176 * @pre current FSYNC handle is shared with a parent process
6178 * @post current FSYNC handle is discarded and a new connection to the
6179 * fileserver SYNC service is established
6181 * @see VChildProcReconnectFS_r
6183 * @see VDisconnectFS
6186 VChildProcReconnectFS(void)
6190 ret = VChildProcReconnectFS_r();
6194 #endif /* FSSYNC_BUILD_CLIENT */
6197 /***************************************************/
6198 /* volume bitmap routines */
6199 /***************************************************/
6202 * Grow the bitmap by the defined increment
6205 VGrowBitmap(struct vnodeIndex *index)
6209 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6210 osi_Assert(bp != NULL);
6212 bp += index->bitmapSize;
6213 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6214 index->bitmapOffset = index->bitmapSize;
6215 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6221 * allocate a vnode bitmap number for the vnode
6223 * @param[out] ec error code
6224 * @param[in] vp volume object pointer
6225 * @param[in] index vnode index number for the vnode
6226 * @param[in] flags flag values described in note
6228 * @note for DAFS, flags parameter controls locking behavior.
6229 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6230 * will create a reservation and block on any other exclusive
6231 * operations. Otherwise, this function assumes the caller
6232 * already has exclusive access to vp, and we just change the
6235 * @pre VOL_LOCK held
6237 * @return bit number allocated
6243 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6244 struct vnodeIndex *index, int flags)
6248 #ifdef AFS_DEMAND_ATTACH_FS
6249 VolState state_save;
6250 #endif /* AFS_DEMAND_ATTACH_FS */
6254 /* This test is probably redundant */
6255 if (!VolumeWriteable(vp)) {
6256 *ec = (bit32) VREADONLY;
6260 #ifdef AFS_DEMAND_ATTACH_FS
6261 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6262 VCreateReservation_r(vp);
6263 VWaitExclusiveState_r(vp);
6265 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6266 #endif /* AFS_DEMAND_ATTACH_FS */
6269 if ((programType == fileServer) && !index->bitmap) {
6271 #ifndef AFS_DEMAND_ATTACH_FS
6272 /* demand attach fs uses the volume state to avoid races.
6273 * specialStatus field is not used at all */
6275 if (vp->specialStatus == VBUSY) {
6276 if (vp->goingOffline) { /* vos dump waiting for the volume to
6277 * go offline. We probably come here
6278 * from AddNewReadableResidency */
6281 while (vp->specialStatus == VBUSY) {
6282 #ifdef AFS_PTHREAD_ENV
6286 #else /* !AFS_PTHREAD_ENV */
6288 #endif /* !AFS_PTHREAD_ENV */
6292 #endif /* !AFS_DEMAND_ATTACH_FS */
6294 if (!index->bitmap) {
6295 #ifndef AFS_DEMAND_ATTACH_FS
6296 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6297 #endif /* AFS_DEMAND_ATTACH_FS */
6298 for (i = 0; i < nVNODECLASSES; i++) {
6299 VGetBitmap_r(ec, vp, i);
6301 #ifdef AFS_DEMAND_ATTACH_FS
6302 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6303 #else /* AFS_DEMAND_ATTACH_FS */
6304 DeleteVolumeFromHashTable(vp);
6305 vp->shuttingDown = 1; /* Let who has it free it. */
6306 vp->specialStatus = 0;
6307 #endif /* AFS_DEMAND_ATTACH_FS */
6311 #ifndef AFS_DEMAND_ATTACH_FS
6313 vp->specialStatus = 0; /* Allow others to have access. */
6314 #endif /* AFS_DEMAND_ATTACH_FS */
6317 #endif /* BITMAP_LATER */
6319 #ifdef AFS_DEMAND_ATTACH_FS
6321 #endif /* AFS_DEMAND_ATTACH_FS */
6322 bp = index->bitmap + index->bitmapOffset;
6323 ep = index->bitmap + index->bitmapSize;
6325 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6327 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6330 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6332 ret = ((bp - index->bitmap) * 8 + o);
6333 #ifdef AFS_DEMAND_ATTACH_FS
6335 #endif /* AFS_DEMAND_ATTACH_FS */
6338 bp += sizeof(bit32) /* i.e. 4 */ ;
6340 /* No bit map entry--must grow bitmap */
6344 ret = index->bitmapOffset * 8;
6345 #ifdef AFS_DEMAND_ATTACH_FS
6347 #endif /* AFS_DEMAND_ATTACH_FS */
6350 #ifdef AFS_DEMAND_ATTACH_FS
6351 VChangeState_r(vp, state_save);
6352 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6353 VCancelReservation_r(vp);
6355 #endif /* AFS_DEMAND_ATTACH_FS */
6360 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6364 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6370 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6371 unsigned bitNumber, int flags)
6373 unsigned int offset;
6377 #ifdef AFS_DEMAND_ATTACH_FS
6378 if (flags & VOL_FREE_BITMAP_WAIT) {
6379 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6380 * state, so ensure we're not in an exclusive volume state when we update
6382 VCreateReservation_r(vp);
6383 VWaitExclusiveState_r(vp);
6390 #endif /* BITMAP_LATER */
6392 offset = bitNumber >> 3;
6393 if (offset >= index->bitmapSize) {
6397 if (offset < index->bitmapOffset)
6398 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6399 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6402 #ifdef AFS_DEMAND_ATTACH_FS
6403 VCancelReservation_r(vp);
6405 return; /* make the compiler happy for non-DAFS */
6409 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6413 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6417 /* this function will drop the glock internally.
6418 * for old pthread fileservers, this is safe thanks to vbusy.
6420 * for demand attach fs, caller must have already called
6421 * VCreateReservation_r and VWaitExclusiveState_r */
6423 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6425 StreamHandle_t *file;
6426 afs_sfsize_t nVnodes, size;
6427 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6428 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6429 struct VnodeDiskObject *vnode;
6430 unsigned int unique = 0;
6434 #endif /* BITMAP_LATER */
6435 #ifdef AFS_DEMAND_ATTACH_FS
6436 VolState state_save;
6437 #endif /* AFS_DEMAND_ATTACH_FS */
6441 #ifdef AFS_DEMAND_ATTACH_FS
6442 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6443 #endif /* AFS_DEMAND_ATTACH_FS */
6446 fdP = IH_OPEN(vip->handle);
6447 osi_Assert(fdP != NULL);
6448 file = FDH_FDOPEN(fdP, "r");
6449 osi_Assert(file != NULL);
6450 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6451 osi_Assert(vnode != NULL);
6452 size = OS_SIZE(fdP->fd_fd);
6453 osi_Assert(size != -1);
6454 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6456 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6457 * a few files can be created in this volume,
6458 * the whole thing is rounded up to nearest 4
6459 * bytes, because the bit map allocator likes
6462 BitMap = (byte *) calloc(1, vip->bitmapSize);
6463 osi_Assert(BitMap != NULL);
6464 #else /* BITMAP_LATER */
6465 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6466 osi_Assert(vip->bitmap != NULL);
6467 vip->bitmapOffset = 0;
6468 #endif /* BITMAP_LATER */
6469 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6471 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6472 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6474 if (vnode->type != vNull) {
6475 if (vnode->vnodeMagic != vcp->magic) {
6476 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6481 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6482 #else /* BITMAP_LATER */
6483 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6484 #endif /* BITMAP_LATER */
6485 if (unique <= vnode->uniquifier)
6486 unique = vnode->uniquifier + 1;
6488 #ifndef AFS_PTHREAD_ENV
6489 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6492 #endif /* !AFS_PTHREAD_ENV */
6495 if (vp->nextVnodeUnique < unique) {
6496 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6499 /* Paranoia, partly justified--I think fclose after fdopen
6500 * doesn't seem to close fd. In any event, the documentation
6501 * doesn't specify, so it's safer to close it twice.
6509 /* There may have been a racing condition with some other thread, both
6510 * creating the bitmaps for this volume. If the other thread was faster
6511 * the pointer to bitmap should already be filled and we can free ours.
6513 if (vip->bitmap == NULL) {
6514 vip->bitmap = BitMap;
6515 vip->bitmapOffset = 0;
6517 free((byte *) BitMap);
6518 #endif /* BITMAP_LATER */
6519 #ifdef AFS_DEMAND_ATTACH_FS
6520 VChangeState_r(vp, state_save);
6521 #endif /* AFS_DEMAND_ATTACH_FS */
6525 /***************************************************/
6526 /* Volume Path and Volume Number utility routines */
6527 /***************************************************/
6530 * find the first occurrence of a volume header file and return the path.
6532 * @param[out] ec outbound error code
6533 * @param[in] volumeId volume id to find
6534 * @param[out] partitionp pointer to disk partition path string
6535 * @param[out] namep pointer to volume header file name string
6537 * @post path to first occurrence of volume header is returned in partitionp
6538 * and namep, or ec is set accordingly.
6540 * @warning this function is NOT re-entrant -- partitionp and namep point to
6541 * static data segments
6543 * @note if a volume utility inadvertently leaves behind a stale volume header
6544 * on a vice partition, it is possible for callers to get the wrong one,
6545 * depending on the order of the disk partition linked list.
6549 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6551 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6552 char path[VMAXPATHLEN];
6554 struct DiskPartition64 *dp;
6557 name[0] = OS_DIRSEPC;
6558 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6559 afs_printable_uint32_lu(volumeId));
6560 for (dp = DiskPartitionList; dp; dp = dp->next) {
6561 struct afs_stat_st status;
6562 strcpy(path, VPartitionPath(dp));
6564 if (afs_stat(path, &status) == 0) {
6565 strcpy(partition, dp->name);
6572 *partitionp = *namep = NULL;
6574 *partitionp = partition;
6580 * extract a volume number from a volume header filename string.
6582 * @param[in] name volume header filename string
6584 * @return volume number
6586 * @note the string must be of the form VFORMAT. the only permissible
6587 * deviation is a leading OS_DIRSEPC character.
6592 VolumeNumber(char *name)
6594 if (*name == OS_DIRSEPC)
6596 return strtoul(name + 1, NULL, 10);
6600 * compute the volume header filename.
6602 * @param[in] volumeId
6604 * @return volume header filename
6606 * @post volume header filename string is constructed
6608 * @warning this function is NOT re-entrant -- the returned string is
6609 * stored in a static char array. see VolumeExternalName_r
6610 * for a re-entrant equivalent.
6612 * @see VolumeExternalName_r
6614 * @deprecated due to the above re-entrancy warning, this interface should
6615 * be considered deprecated. Please use VolumeExternalName_r
6619 VolumeExternalName(VolumeId volumeId)
6621 static char name[VMAXPATHLEN];
6622 snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6627 * compute the volume header filename.
6629 * @param[in] volumeId
6630 * @param[inout] name array in which to store filename
6631 * @param[in] len length of name array
6633 * @return result code from afs_snprintf
6635 * @see VolumeExternalName
6638 * @note re-entrant equivalent of VolumeExternalName
6641 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6643 return snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6647 /***************************************************/
6648 /* Volume Usage Statistics routines */
6649 /***************************************************/
6651 #define OneDay (86400) /* 24 hours' worth of seconds */
6654 Midnight(time_t t) {
6655 struct tm local, *l;
6658 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6659 l = localtime_r(&t, &local);
6665 /* the following is strictly speaking problematic on the
6666 switching day to daylight saving time, after the switch,
6667 as tm_isdst does not match. Similarly, on the looong day when
6668 switching back the OneDay check will not do what naively expected!
6669 The effects are minor, though, and more a matter of interpreting
6671 #ifndef AFS_PTHREAD_ENV
6674 local.tm_hour = local.tm_min=local.tm_sec = 0;
6675 midnight = mktime(&local);
6676 if (midnight != (time_t) -1) return(midnight);
6678 return( (t/OneDay)*OneDay );
6682 /*------------------------------------------------------------------------
6683 * [export] VAdjustVolumeStatistics
6686 * If we've passed midnight, we need to update all the day use
6687 * statistics as well as zeroing the detailed volume statistics
6688 * (if we are implementing them).
6691 * vp : Pointer to the volume structure describing the lucky
6692 * volume being considered for update.
6698 * Nothing interesting.
6702 *------------------------------------------------------------------------*/
6705 VAdjustVolumeStatistics_r(Volume * vp)
6707 unsigned int now = FT_ApproxTime();
6709 if (now - V_dayUseDate(vp) > OneDay) {
6712 ndays = (now - V_dayUseDate(vp)) / OneDay;
6713 for (i = 6; i > ndays - 1; i--)
6714 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6715 for (i = 0; i < ndays - 1 && i < 7; i++)
6716 V_weekUse(vp)[i] = 0;
6718 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6720 V_dayUseDate(vp) = Midnight(now);
6723 * All we need to do is bzero the entire VOL_STATS_BYTES of
6724 * the detailed volume statistics area.
6726 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6729 /*It's been more than a day of collection */
6731 * Always return happily.
6734 } /*VAdjustVolumeStatistics */
6737 VAdjustVolumeStatistics(Volume * vp)
6741 retVal = VAdjustVolumeStatistics_r(vp);
6747 VBumpVolumeUsage_r(Volume * vp)
6749 unsigned int now = FT_ApproxTime();
6750 V_accessDate(vp) = now;
6751 if (now - V_dayUseDate(vp) > OneDay)
6752 VAdjustVolumeStatistics_r(vp);
6754 * Save the volume header image to disk after a threshold of bumps to dayUse,
6755 * at most every usage_rate_limit seconds.
6758 vp->usage_bumps_outstanding++;
6759 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6760 && vp->usage_bumps_next_write <= now) {
6762 vp->usage_bumps_outstanding = 0;
6763 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6764 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6769 VBumpVolumeUsage(Volume * vp)
6772 VBumpVolumeUsage_r(vp);
6777 VSetDiskUsage_r(void)
6779 #ifndef AFS_DEMAND_ATTACH_FS
6780 static int FifteenMinuteCounter = 0;
6784 /* NOTE: Don't attempt to access the partitions list until the
6785 * initialization level indicates that all volumes are attached,
6786 * which implies that all partitions are initialized. */
6787 #ifdef AFS_PTHREAD_ENV
6788 VOL_CV_WAIT(&vol_vinit_cond);
6789 #else /* AFS_PTHREAD_ENV */
6791 #endif /* AFS_PTHREAD_ENV */
6794 VResetDiskUsage_r();
6796 #ifndef AFS_DEMAND_ATTACH_FS
6797 if (++FifteenMinuteCounter == 3) {
6798 FifteenMinuteCounter = 0;
6801 #endif /* !AFS_DEMAND_ATTACH_FS */
6813 /***************************************************/
6814 /* Volume Update List routines */
6815 /***************************************************/
6817 /* The number of minutes that a volume hasn't been updated before the
6818 * "Dont salvage" flag in the volume header will be turned on */
6819 #define SALVAGE_INTERVAL (10*60)
6824 * volume update list functionality has been moved into the VLRU
6825 * the DONT_SALVAGE flag is now set during VLRU demotion
6828 #ifndef AFS_DEMAND_ATTACH_FS
6829 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6830 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6831 static int updateSize = 0; /* number of entries possible */
6832 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6833 #endif /* !AFS_DEMAND_ATTACH_FS */
6836 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6839 vp->updateTime = FT_ApproxTime();
6840 if (V_dontSalvage(vp) == 0)
6842 V_dontSalvage(vp) = 0;
6843 VSyncVolume_r(ec, vp, 0);
6844 #ifdef AFS_DEMAND_ATTACH_FS
6845 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6846 #else /* !AFS_DEMAND_ATTACH_FS */
6849 if (UpdateList == NULL) {
6850 updateSize = UPDATE_LIST_SIZE;
6851 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6853 if (nUpdatedVolumes == updateSize) {
6855 if (updateSize > 524288) {
6856 Log("warning: there is likely a bug in the volume update scanner\n");
6860 (VolumeId *) realloc(UpdateList,
6861 sizeof(VolumeId) * updateSize);
6864 osi_Assert(UpdateList != NULL);
6865 UpdateList[nUpdatedVolumes++] = V_id(vp);
6866 #endif /* !AFS_DEMAND_ATTACH_FS */
6869 #ifndef AFS_DEMAND_ATTACH_FS
6871 VScanUpdateList(void)
6876 afs_uint32 now = FT_ApproxTime();
6877 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6878 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6880 UpdateList[i - gap] = UpdateList[i];
6882 /* XXX this routine needlessly messes up the Volume LRU by
6883 * breaking the LRU temporal-locality assumptions.....
6884 * we should use a special volume header allocator here */
6885 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6888 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6889 V_dontSalvage(vp) = DONT_SALVAGE;
6890 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6898 #ifndef AFS_PTHREAD_ENV
6900 #endif /* !AFS_PTHREAD_ENV */
6902 nUpdatedVolumes -= gap;
6904 #endif /* !AFS_DEMAND_ATTACH_FS */
6907 /***************************************************/
6908 /* Volume LRU routines */
6909 /***************************************************/
6914 * with demand attach fs, we attempt to soft detach(1)
6915 * volumes which have not been accessed in a long time
6916 * in order to speed up fileserver shutdown
6918 * (1) by soft detach we mean a process very similar
6919 * to VOffline, except the final state of the
6920 * Volume will be VOL_STATE_PREATTACHED, instead
6921 * of the usual VOL_STATE_UNATTACHED
6923 #ifdef AFS_DEMAND_ATTACH_FS
6925 /* implementation is reminiscent of a generational GC
6927 * queue 0 is newly attached volumes. this queue is
6928 * sorted by attach timestamp
6930 * queue 1 is volumes that have been around a bit
6931 * longer than queue 0. this queue is sorted by
6934 * queue 2 is volumes tha have been around the longest.
6935 * this queue is unsorted
6937 * queue 3 is volumes that have been marked as
6938 * candidates for soft detachment. this queue is
6941 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6942 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6945 * definition of a VLRU queue.
6948 volatile struct rx_queue q;
6955 * main VLRU data structure.
6958 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6961 /** time interval (in seconds) between promotion passes for
6962 * each young generation queue. */
6963 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6965 /** time interval (in seconds) between soft detach candidate
6966 * scans for each generation queue.
6968 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6969 * we perform a soft detach pass. */
6970 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6972 /* scheduler state */
6973 int next_idx; /**< next queue to receive attention */
6974 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6975 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6977 int scanner_state; /**< state of scanner thread */
6978 pthread_cond_t cv; /**< state transition CV */
6981 /** global VLRU state */
6982 static struct VLRU volume_LRU;
6985 * defined states for VLRU scanner thread.
6988 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6989 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6990 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6991 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6992 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6993 } vlru_thread_state_t;
6995 /* vlru disk data header stuff */
6996 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6997 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6999 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7000 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7003 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7004 * soft detachment. */
7005 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7007 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7008 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7010 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7011 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7013 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7014 static afs_uint32 VLRU_enabled = 1;
7016 /* queue synchronization routines */
7017 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7018 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7019 static void VLRU_Wait_r(struct VLRU_q * q);
7022 * set VLRU subsystem tunable parameters.
7024 * @param[in] option tunable option to modify
7025 * @param[in] val new value for tunable parameter
7027 * @pre @c VInitVolumePackage2 has not yet been called.
7029 * @post tunable parameter is modified
7033 * @note valid option parameters are:
7034 * @arg @c VLRU_SET_THRESH
7035 * set the period of inactivity after which
7036 * volumes are eligible for soft detachment
7037 * @arg @c VLRU_SET_INTERVAL
7038 * set the time interval between calls
7039 * to the volume LRU "garbage collector"
7040 * @arg @c VLRU_SET_MAX
7041 * set the max number of volumes to deallocate
7045 VLRU_SetOptions(int option, afs_uint32 val)
7047 if (option == VLRU_SET_THRESH) {
7048 VLRU_offline_thresh = val;
7049 } else if (option == VLRU_SET_INTERVAL) {
7050 VLRU_offline_interval = val;
7051 } else if (option == VLRU_SET_MAX) {
7052 VLRU_offline_max = val;
7053 } else if (option == VLRU_SET_ENABLED) {
7056 VLRU_ComputeConstants();
7060 * compute VLRU internal timing parameters.
7062 * @post VLRU scanner thread internal timing parameters are computed
7064 * @note computes internal timing parameters based upon user-modifiable
7065 * tunable parameters.
7069 * @internal volume package internal use only.
7072 VLRU_ComputeConstants(void)
7074 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7076 /* compute the candidate scan interval */
7077 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7079 /* compute the promotion intervals */
7080 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7081 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7084 /* compute the gen 0 scan interval */
7085 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7087 /* compute the gen 0 scan interval */
7088 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7093 * initialize VLRU subsystem.
7095 * @pre this function has not yet been called
7097 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7101 * @internal volume package internal use only.
7107 pthread_attr_t attrs;
7110 if (!VLRU_enabled) {
7111 Log("VLRU: disabled\n");
7115 /* initialize each of the VLRU queues */
7116 for (i = 0; i < VLRU_QUEUES; i++) {
7117 queue_Init(&volume_LRU.q[i]);
7118 volume_LRU.q[i].len = 0;
7119 volume_LRU.q[i].busy = 0;
7120 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7123 /* setup the timing constants */
7124 VLRU_ComputeConstants();
7126 /* XXX put inside LogLevel check? */
7127 Log("VLRU: starting scanner with the following configuration parameters:\n");
7128 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7129 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7130 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7131 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7132 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7133 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7135 /* start up the VLRU scanner */
7136 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7137 if (programType == fileServer) {
7138 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7139 osi_Assert(pthread_attr_init(&attrs) == 0);
7140 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7141 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7146 * initialize the VLRU-related fields of a newly allocated volume object.
7148 * @param[in] vp pointer to volume object
7151 * @arg @c VOL_LOCK is held.
7152 * @arg volume object is not on a VLRU queue.
7154 * @post VLRU fields are initialized to indicate that volume object is not
7155 * currently registered with the VLRU subsystem
7159 * @internal volume package interal use only.
7162 VLRU_Init_Node_r(Volume * vp)
7167 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7168 vp->vlru.idx = VLRU_QUEUE_INVALID;
7172 * add a volume object to a VLRU queue.
7174 * @param[in] vp pointer to volume object
7177 * @arg @c VOL_LOCK is held.
7178 * @arg caller MUST hold a lightweight ref on @p vp.
7179 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7181 * @post the volume object is added to the appropriate VLRU queue
7183 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7184 * then the volume is added to that queue. Otherwise, the value
7185 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7186 * volume is added to the NEW generation queue.
7188 * @note @c VOL_LOCK may be dropped internally
7190 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7191 * during the add operation, and is restored to the previous
7192 * state prior to return.
7196 * @internal volume package internal use only.
7199 VLRU_Add_r(Volume * vp)
7202 VolState state_save;
7207 if (queue_IsOnQueue(&vp->vlru))
7210 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7213 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7214 idx = VLRU_QUEUE_NEW;
7217 VLRU_Wait_r(&volume_LRU.q[idx]);
7219 /* repeat check since VLRU_Wait_r may have dropped
7221 if (queue_IsNotOnQueue(&vp->vlru)) {
7223 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7224 volume_LRU.q[idx].len++;
7225 V_attachFlags(vp) |= VOL_ON_VLRU;
7226 vp->stats.last_promote = FT_ApproxTime();
7229 VChangeState_r(vp, state_save);
7233 * delete a volume object from a VLRU queue.
7235 * @param[in] vp pointer to volume object
7238 * @arg @c VOL_LOCK is held.
7239 * @arg caller MUST hold a lightweight ref on @p vp.
7240 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7242 * @post volume object is removed from the VLRU queue
7244 * @note @c VOL_LOCK may be dropped internally
7248 * @todo We should probably set volume state to something exlcusive
7249 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7251 * @internal volume package internal use only.
7254 VLRU_Delete_r(Volume * vp)
7261 if (queue_IsNotOnQueue(&vp->vlru))
7267 if (idx == VLRU_QUEUE_INVALID)
7269 VLRU_Wait_r(&volume_LRU.q[idx]);
7270 } while (idx != vp->vlru.idx);
7272 /* now remove from the VLRU and update
7273 * the appropriate counter */
7274 queue_Remove(&vp->vlru);
7275 volume_LRU.q[idx].len--;
7276 vp->vlru.idx = VLRU_QUEUE_INVALID;
7277 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7281 * tell the VLRU subsystem that a volume was just accessed.
7283 * @param[in] vp pointer to volume object
7286 * @arg @c VOL_LOCK is held
7287 * @arg caller MUST hold a lightweight ref on @p vp
7288 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7290 * @post volume VLRU access statistics are updated. If the volume was on
7291 * the VLRU soft detach candidate queue, it is moved to the NEW
7294 * @note @c VOL_LOCK may be dropped internally
7298 * @internal volume package internal use only.
7301 VLRU_UpdateAccess_r(Volume * vp)
7303 Volume * rvp = NULL;
7308 if (queue_IsNotOnQueue(&vp->vlru))
7311 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7313 /* update the access timestamp */
7314 vp->stats.last_get = FT_ApproxTime();
7317 * if the volume is on the soft detach candidate
7318 * list, we need to safely move it back to a
7319 * regular generation. this has to be done
7320 * carefully so we don't race against the scanner
7324 /* if this volume is on the soft detach candidate queue,
7325 * then grab exclusive access to the necessary queues */
7326 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7328 VCreateReservation_r(rvp);
7330 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7331 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7332 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7333 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7336 /* make sure multiple threads don't race to update */
7337 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7338 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7342 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7343 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7344 VCancelReservation_r(rvp);
7349 * switch a volume between two VLRU queues.
7351 * @param[in] vp pointer to volume object
7352 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7353 * @param[in] append controls whether the volume will be appended or
7354 * prepended to the queue. A nonzero value means it will
7355 * be appended; zero means it will be prepended.
7357 * @pre The new (and old, if applicable) queue(s) must either be owned
7358 * exclusively by the calling thread for asynchronous manipulation,
7359 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7360 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7361 * for further details of the queue asynchronous processing mechanism.
7363 * @post If the volume object was already on a VLRU queue, it is
7364 * removed from the queue. Depending on the value of the append
7365 * parameter, the volume object is either appended or prepended
7366 * to the VLRU queue referenced by the new_idx parameter.
7370 * @see VLRU_BeginExclusive_r
7371 * @see VLRU_EndExclusive_r
7374 * @internal volume package internal use only.
7377 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7379 if (queue_IsNotOnQueue(&vp->vlru))
7382 queue_Remove(&vp->vlru);
7383 volume_LRU.q[vp->vlru.idx].len--;
7385 /* put the volume back on the correct generational queue */
7387 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7389 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7392 volume_LRU.q[new_idx].len++;
7393 vp->vlru.idx = new_idx;
7397 * VLRU background thread.
7399 * The VLRU Scanner Thread is responsible for periodically scanning through
7400 * each VLRU queue looking for volumes which should be moved to another
7401 * queue, or soft detached.
7403 * @param[in] args unused thread arguments parameter
7405 * @return unused thread return value
7406 * @retval NULL always
7408 * @internal volume package internal use only.
7411 VLRU_ScannerThread(void * args)
7413 afs_uint32 now, min_delay, delay;
7414 int i, min_idx, min_op, overdue, state;
7416 /* set t=0 for promotion cycle to be
7417 * fileserver startup */
7418 now = FT_ApproxTime();
7419 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7420 volume_LRU.last_promotion[i] = now;
7423 /* don't start the scanner until VLRU_offline_thresh
7424 * plus a small delay for VInitVolumePackage2 to finish
7427 sleep(VLRU_offline_thresh + 60);
7429 /* set t=0 for scan cycle to be now */
7430 now = FT_ApproxTime();
7431 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7432 volume_LRU.last_scan[i] = now;
7436 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7437 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7440 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7441 /* check to see if we've been asked to pause */
7442 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7443 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7444 CV_BROADCAST(&volume_LRU.cv);
7446 VOL_CV_WAIT(&volume_LRU.cv);
7447 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7450 /* scheduling can happen outside the glock */
7453 /* figure out what is next on the schedule */
7455 /* figure out a potential schedule for the new generation first */
7457 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7460 if (min_delay > volume_LRU.scan_interval[0]) {
7461 /* unsigned overflow -- we're overdue to run this scan */
7466 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7468 i = VLRU_QUEUE_CANDIDATE;
7469 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7470 if (delay < min_delay) {
7474 if (delay > volume_LRU.scan_interval[i]) {
7475 /* unsigned overflow -- we're overdue to run this scan */
7482 /* if we're still not overdue for something, figure out schedules for promotions */
7483 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7484 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7485 if (delay < min_delay) {
7490 if (delay > volume_LRU.promotion_interval[i]) {
7491 /* unsigned overflow -- we're overdue to run this promotion */
7500 /* sleep as needed */
7505 /* do whatever is next */
7508 VLRU_Promote_r(min_idx);
7509 VLRU_Demote_r(min_idx+1);
7511 VLRU_Scan_r(min_idx);
7513 now = FT_ApproxTime();
7516 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7518 /* signal that scanner is down */
7519 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7520 CV_BROADCAST(&volume_LRU.cv);
7526 * promote volumes from one VLRU generation to the next.
7528 * This routine scans a VLRU generation looking for volumes which are
7529 * eligible to be promoted to the next generation. All volumes which
7530 * meet the eligibility requirement are promoted.
7532 * Promotion eligibility is based upon meeting both of the following
7535 * @arg The volume has been accessed since the last promotion:
7536 * @c (vp->stats.last_get >= vp->stats.last_promote)
7537 * @arg The last promotion occurred at least
7538 * @c volume_LRU.promotion_interval[idx] seconds ago
7540 * As a performance optimization, promotions are "globbed". In other
7541 * words, we promote arbitrarily large contiguous sublists of elements
7544 * @param[in] idx VLRU queue index to scan
7548 * @internal VLRU internal use only.
7551 VLRU_Promote_r(int idx)
7553 int len, chaining, promote;
7554 afs_uint32 now, thresh;
7555 struct rx_queue *qp, *nqp;
7556 Volume * vp, *start = NULL, *end = NULL;
7558 /* get exclusive access to two chains, and drop the glock */
7559 VLRU_Wait_r(&volume_LRU.q[idx]);
7560 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7561 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7562 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7565 thresh = volume_LRU.promotion_interval[idx];
7566 now = FT_ApproxTime();
7569 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7570 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7571 promote = (((vp->stats.last_promote + thresh) <= now) &&
7572 (vp->stats.last_get >= vp->stats.last_promote));
7580 /* promote and prepend chain */
7581 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7595 /* promote and prepend */
7596 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7600 volume_LRU.q[idx].len -= len;
7601 volume_LRU.q[idx+1].len += len;
7604 /* release exclusive access to the two chains */
7606 volume_LRU.last_promotion[idx] = now;
7607 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7608 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7611 /* run the demotions */
7613 VLRU_Demote_r(int idx)
7616 int len, chaining, demote;
7617 afs_uint32 now, thresh;
7618 struct rx_queue *qp, *nqp;
7619 Volume * vp, *start = NULL, *end = NULL;
7620 Volume ** salv_flag_vec = NULL;
7621 int salv_vec_offset = 0;
7623 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7625 /* get exclusive access to two chains, and drop the glock */
7626 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7627 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7628 VLRU_Wait_r(&volume_LRU.q[idx]);
7629 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7632 /* no big deal if this allocation fails */
7633 if (volume_LRU.q[idx].len) {
7634 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7637 now = FT_ApproxTime();
7638 thresh = volume_LRU.promotion_interval[idx-1];
7641 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7642 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7643 demote = (((vp->stats.last_promote + thresh) <= now) &&
7644 (vp->stats.last_get < (now - thresh)));
7646 /* we now do volume update list DONT_SALVAGE flag setting during
7647 * demotion passes */
7648 if (salv_flag_vec &&
7649 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7651 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7652 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7653 salv_flag_vec[salv_vec_offset++] = vp;
7654 VCreateReservation_r(vp);
7663 /* demote and append chain */
7664 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7678 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7682 volume_LRU.q[idx].len -= len;
7683 volume_LRU.q[idx-1].len += len;
7686 /* release exclusive access to the two chains */
7688 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7689 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7691 /* now go back and set the DONT_SALVAGE flags as appropriate */
7692 if (salv_flag_vec) {
7694 for (i = 0; i < salv_vec_offset; i++) {
7695 vp = salv_flag_vec[i];
7696 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7697 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7698 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7701 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7702 V_dontSalvage(vp) = DONT_SALVAGE;
7703 VUpdateVolume_r(&ec, vp, 0);
7707 VCancelReservation_r(vp);
7709 free(salv_flag_vec);
7713 /* run a pass of the VLRU GC scanner */
7715 VLRU_Scan_r(int idx)
7717 afs_uint32 now, thresh;
7718 struct rx_queue *qp, *nqp;
7722 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7724 /* gain exclusive access to the idx VLRU */
7725 VLRU_Wait_r(&volume_LRU.q[idx]);
7726 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7728 if (idx != VLRU_QUEUE_CANDIDATE) {
7729 /* gain exclusive access to the candidate VLRU */
7730 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7731 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7734 now = FT_ApproxTime();
7735 thresh = now - VLRU_offline_thresh;
7737 /* perform candidate selection and soft detaching */
7738 if (idx == VLRU_QUEUE_CANDIDATE) {
7739 /* soft detach some volumes from the candidate pool */
7743 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7744 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7745 if (i >= VLRU_offline_max) {
7748 /* check timestamp to see if it's a candidate for soft detaching */
7749 if (vp->stats.last_get <= thresh) {
7751 if (VCheckSoftDetach(vp, thresh))
7757 /* scan for volumes to become soft detach candidates */
7758 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7759 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7761 /* check timestamp to see if it's a candidate for soft detaching */
7762 if (vp->stats.last_get <= thresh) {
7763 VCheckSoftDetachCandidate(vp, thresh);
7766 if (!(i&0x7f)) { /* lock coarsening optimization */
7774 /* relinquish exclusive access to the VLRU chains */
7778 volume_LRU.last_scan[idx] = now;
7779 if (idx != VLRU_QUEUE_CANDIDATE) {
7780 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7782 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7785 /* check whether volume is safe to soft detach
7786 * caller MUST NOT hold a ref count on vp */
7788 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7792 if (vp->nUsers || vp->nWaiters)
7795 if (vp->stats.last_get <= thresh) {
7796 ret = VSoftDetachVolume_r(vp, thresh);
7802 /* check whether volume should be made a
7803 * soft detach candidate */
7805 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7808 if (vp->nUsers || vp->nWaiters)
7813 osi_Assert(idx == VLRU_QUEUE_NEW);
7815 if (vp->stats.last_get <= thresh) {
7816 /* move to candidate pool */
7817 queue_Remove(&vp->vlru);
7818 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7819 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7820 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7821 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7829 /* begin exclusive access on VLRU */
7831 VLRU_BeginExclusive_r(struct VLRU_q * q)
7833 osi_Assert(q->busy == 0);
7837 /* end exclusive access on VLRU */
7839 VLRU_EndExclusive_r(struct VLRU_q * q)
7841 osi_Assert(q->busy);
7843 CV_BROADCAST(&q->cv);
7846 /* wait for another thread to end exclusive access on VLRU */
7848 VLRU_Wait_r(struct VLRU_q * q)
7851 VOL_CV_WAIT(&q->cv);
7856 * volume soft detach
7858 * caller MUST NOT hold a ref count on vp */
7860 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7865 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7867 ts_save = vp->stats.last_get;
7868 if (ts_save > thresh)
7871 if (vp->nUsers || vp->nWaiters)
7874 if (VIsExclusiveState(V_attachState(vp))) {
7878 switch (V_attachState(vp)) {
7879 case VOL_STATE_UNATTACHED:
7880 case VOL_STATE_PREATTACHED:
7881 case VOL_STATE_ERROR:
7882 case VOL_STATE_GOING_OFFLINE:
7883 case VOL_STATE_SHUTTING_DOWN:
7884 case VOL_STATE_SALVAGING:
7885 case VOL_STATE_DELETED:
7886 volume_LRU.q[vp->vlru.idx].len--;
7888 /* create and cancel a reservation to
7889 * give the volume an opportunity to
7891 VCreateReservation_r(vp);
7892 queue_Remove(&vp->vlru);
7893 vp->vlru.idx = VLRU_QUEUE_INVALID;
7894 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7895 VCancelReservation_r(vp);
7901 /* hold the volume and take it offline.
7902 * no need for reservations, as VHold_r
7903 * takes care of that internally. */
7904 if (VHold_r(vp) == 0) {
7905 /* vhold drops the glock, so now we should
7906 * check to make sure we aren't racing against
7907 * other threads. if we are racing, offlining vp
7908 * would be wasteful, and block the scanner for a while
7912 (vp->shuttingDown) ||
7913 (vp->goingOffline) ||
7914 (vp->stats.last_get != ts_save)) {
7915 /* looks like we're racing someone else. bail */
7919 /* pull it off the VLRU */
7920 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7921 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7922 queue_Remove(&vp->vlru);
7923 vp->vlru.idx = VLRU_QUEUE_INVALID;
7924 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7926 /* take if offline */
7927 VOffline_r(vp, "volume has been soft detached");
7929 /* invalidate the volume header cache */
7930 FreeVolumeHeader(vp);
7933 IncUInt64(&VStats.soft_detaches);
7934 vp->stats.soft_detaches++;
7936 /* put in pre-attached state so demand
7937 * attacher can work on it */
7938 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7944 #endif /* AFS_DEMAND_ATTACH_FS */
7947 /***************************************************/
7948 /* Volume Header Cache routines */
7949 /***************************************************/
7952 * volume header cache.
7954 struct volume_hdr_LRU_t volume_hdr_LRU;
7957 * initialize the volume header cache.
7959 * @param[in] howMany number of header cache entries to preallocate
7961 * @pre VOL_LOCK held. Function has never been called before.
7963 * @post howMany cache entries are allocated, initialized, and added
7964 * to the LRU list. Header cache statistics are initialized.
7966 * @note only applicable to fileServer program type. Should only be
7967 * called once during volume package initialization.
7969 * @internal volume package internal use only.
7972 VInitVolumeHeaderCache(afs_uint32 howMany)
7974 struct volHeader *hp;
7975 if (programType != fileServer)
7977 queue_Init(&volume_hdr_LRU);
7978 volume_hdr_LRU.stats.free = 0;
7979 volume_hdr_LRU.stats.used = howMany;
7980 volume_hdr_LRU.stats.attached = 0;
7981 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7982 osi_Assert(hp != NULL);
7985 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7986 * to ensure they have the right values
7988 ReleaseVolumeHeader(hp++);
7991 /* get a volume header off of the volume header LRU.
7993 * @return volume header
7994 * @retval NULL no usable volume header is available on the LRU
7996 * @pre VOL_LOCK held
7998 * @post for DAFS, if the returned header is associated with a volume, that
7999 * volume is NOT in an exclusive state
8001 * @internal volume package internal use only.
8003 #ifdef AFS_DEMAND_ATTACH_FS
8004 static struct volHeader*
8005 GetVolHeaderFromLRU(void)
8007 struct volHeader *hd = NULL, *qh, *nqh;
8008 /* Usually, a volume in an exclusive state will not have its header on
8009 * the LRU. However, it is possible for this to occur when a salvage
8010 * request is received over FSSYNC, and possibly in other corner cases.
8011 * So just skip over headers whose volumes are in an exclusive state. We
8012 * could VWaitExclusiveState_r instead, but not waiting is faster and
8014 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8015 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8023 #else /* AFS_DEMAND_ATTACH_FS */
8024 static struct volHeader*
8025 GetVolHeaderFromLRU(void)
8027 struct volHeader *hd = NULL;
8028 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8029 hd = queue_First(&volume_hdr_LRU, volHeader);
8034 #endif /* !AFS_DEMAND_ATTACH_FS */
8037 * get a volume header and attach it to the volume object.
8039 * @param[in] vp pointer to volume object
8041 * @return cache entry status
8042 * @retval 0 volume header was newly attached; cache data is invalid
8043 * @retval 1 volume header was previously attached; cache data is valid
8045 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8047 * @post volume header attached to volume object. if necessary, header cache
8048 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8050 * @note VOL_LOCK may be dropped
8052 * @warning this interface does not load header data from disk. it merely
8053 * attaches a header object to the volume object, and may sync the old
8054 * header cache data out to disk in the process.
8056 * @internal volume package internal use only.
8059 GetVolumeHeader(Volume * vp)
8062 struct volHeader *hd;
8064 static int everLogged = 0;
8066 #ifdef AFS_DEMAND_ATTACH_FS
8067 VolState vp_save = 0, back_save = 0;
8069 /* XXX debug 9/19/05 we've apparently got
8070 * a ref counting bug somewhere that's
8071 * breaking the nUsers == 0 => header on LRU
8073 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8074 Log("nUsers == 0, but header not on LRU\n");
8079 old = (vp->header != NULL); /* old == volume already has a header */
8081 if (programType != fileServer) {
8082 /* for volume utilities, we allocate volHeaders as needed */
8084 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
8085 osi_Assert(hd != NULL);
8088 #ifdef AFS_DEMAND_ATTACH_FS
8089 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8093 /* for the fileserver, we keep a volume header cache */
8095 /* the header we previously dropped in the lru is
8096 * still available. pull it off the lru and return */
8099 osi_Assert(hd->back == vp);
8100 #ifdef AFS_DEMAND_ATTACH_FS
8101 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8104 hd = GetVolHeaderFromLRU();
8106 /* LRU is empty, so allocate a new volHeader
8107 * this is probably indicative of a leak, so let the user know */
8108 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
8109 osi_Assert(hd != NULL);
8111 Log("****Allocated more volume headers, probably leak****\n");
8114 volume_hdr_LRU.stats.free++;
8117 /* this header used to belong to someone else.
8118 * we'll need to check if the header needs to
8119 * be sync'd out to disk */
8121 #ifdef AFS_DEMAND_ATTACH_FS
8122 /* GetVolHeaderFromLRU had better not give us back a header
8123 * with a volume in exclusive state... */
8124 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8127 if (hd->diskstuff.inUse) {
8128 /* volume was in use, so we'll need to sync
8129 * its header to disk */
8131 #ifdef AFS_DEMAND_ATTACH_FS
8132 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8133 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8134 VCreateReservation_r(hd->back);
8138 WriteVolumeHeader_r(&error, hd->back);
8139 /* Ignore errors; catch them later */
8141 #ifdef AFS_DEMAND_ATTACH_FS
8146 hd->back->header = NULL;
8147 #ifdef AFS_DEMAND_ATTACH_FS
8148 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8150 if (hd->diskstuff.inUse) {
8151 VChangeState_r(hd->back, back_save);
8152 VCancelReservation_r(hd->back);
8153 VChangeState_r(vp, vp_save);
8157 volume_hdr_LRU.stats.attached++;
8161 #ifdef AFS_DEMAND_ATTACH_FS
8162 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8165 volume_hdr_LRU.stats.free--;
8166 volume_hdr_LRU.stats.used++;
8168 IncUInt64(&VStats.hdr_gets);
8169 #ifdef AFS_DEMAND_ATTACH_FS
8170 IncUInt64(&vp->stats.hdr_gets);
8171 vp->stats.last_hdr_get = FT_ApproxTime();
8178 * make sure volume header is attached and contains valid cache data.
8180 * @param[out] ec outbound error code
8181 * @param[in] vp pointer to volume object
8183 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8185 * @post header cache entry attached, and loaded with valid data, or
8186 * *ec is nonzero, and the header is released back into the LRU.
8188 * @internal volume package internal use only.
8191 LoadVolumeHeader(Error * ec, Volume * vp)
8193 #ifdef AFS_DEMAND_ATTACH_FS
8194 VolState state_save;
8198 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8199 IncUInt64(&VStats.hdr_loads);
8200 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8203 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8204 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8206 IncUInt64(&vp->stats.hdr_loads);
8207 now = FT_ApproxTime();
8211 V_attachFlags(vp) |= VOL_HDR_LOADED;
8212 vp->stats.last_hdr_load = now;
8214 VChangeState_r(vp, state_save);
8216 #else /* AFS_DEMAND_ATTACH_FS */
8218 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8219 IncUInt64(&VStats.hdr_loads);
8221 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8222 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8225 #endif /* AFS_DEMAND_ATTACH_FS */
8227 /* maintain (nUsers==0) => header in LRU invariant */
8228 FreeVolumeHeader(vp);
8233 * release a header cache entry back into the LRU list.
8235 * @param[in] hd pointer to volume header cache object
8237 * @pre VOL_LOCK held.
8239 * @post header cache object appended onto end of LRU list.
8241 * @note only applicable to fileServer program type.
8243 * @note used to place a header cache entry back into the
8244 * LRU pool without invalidating it as a cache entry.
8246 * @internal volume package internal use only.
8249 ReleaseVolumeHeader(struct volHeader *hd)
8251 if (programType != fileServer)
8253 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8255 queue_Append(&volume_hdr_LRU, hd);
8256 #ifdef AFS_DEMAND_ATTACH_FS
8258 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8261 volume_hdr_LRU.stats.free++;
8262 volume_hdr_LRU.stats.used--;
8266 * free/invalidate a volume header cache entry.
8268 * @param[in] vp pointer to volume object
8270 * @pre VOL_LOCK is held.
8272 * @post For fileserver, header cache entry is returned to LRU, and it is
8273 * invalidated as a cache entry. For volume utilities, the header
8274 * cache entry is freed.
8276 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8277 * whenever it is necessary to invalidate the header cache entry.
8279 * @see ReleaseVolumeHeader
8281 * @internal volume package internal use only.
8284 FreeVolumeHeader(Volume * vp)
8286 struct volHeader *hd = vp->header;
8289 if (programType == fileServer) {
8290 ReleaseVolumeHeader(hd);
8295 #ifdef AFS_DEMAND_ATTACH_FS
8296 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8298 volume_hdr_LRU.stats.attached--;
8303 /***************************************************/
8304 /* Volume Hash Table routines */
8305 /***************************************************/
8308 * set size of volume object hash table.
8310 * @param[in] logsize log(2) of desired hash table size
8312 * @return operation status
8314 * @retval -1 failure
8316 * @pre MUST be called prior to VInitVolumePackage2
8318 * @post Volume Hash Table will have 2^logsize buckets
8321 VSetVolHashSize(int logsize)
8323 /* 64 to 268435456 hash buckets seems like a reasonable range */
8324 if ((logsize < 6 ) || (logsize > 28)) {
8329 VolumeHashTable.Size = 1 << logsize;
8330 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8332 /* we can't yet support runtime modification of this
8333 * parameter. we'll need a configuration rwlock to
8334 * make runtime modification feasible.... */
8341 * initialize dynamic data structures for volume hash table.
8343 * @post hash table is allocated, and fields are initialized.
8345 * @internal volume package internal use only.
8348 VInitVolumeHash(void)
8352 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8353 sizeof(VolumeHashChainHead));
8354 osi_Assert(VolumeHashTable.Table != NULL);
8356 for (i=0; i < VolumeHashTable.Size; i++) {
8357 queue_Init(&VolumeHashTable.Table[i]);
8358 #ifdef AFS_DEMAND_ATTACH_FS
8359 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8360 #endif /* AFS_DEMAND_ATTACH_FS */
8365 * add a volume object to the hash table.
8367 * @param[in] vp pointer to volume object
8368 * @param[in] hashid hash of volume id
8370 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8373 * @post volume is added to hash chain.
8375 * @internal volume package internal use only.
8377 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8378 * asynchronous hash chain reordering to finish.
8381 AddVolumeToHashTable(Volume * vp, int hashid)
8383 VolumeHashChainHead * head;
8385 if (queue_IsOnQueue(vp))
8388 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8390 #ifdef AFS_DEMAND_ATTACH_FS
8391 /* wait for the hash chain to become available */
8394 V_attachFlags(vp) |= VOL_IN_HASH;
8395 vp->chainCacheCheck = ++head->cacheCheck;
8396 #endif /* AFS_DEMAND_ATTACH_FS */
8399 vp->hashid = hashid;
8400 queue_Append(head, vp);
8401 vp->vnodeHashOffset = VolumeHashOffset_r();
8405 * delete a volume object from the hash table.
8407 * @param[in] vp pointer to volume object
8409 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8412 * @post volume is removed from hash chain.
8414 * @internal volume package internal use only.
8416 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8417 * asynchronous hash chain reordering to finish.
8420 DeleteVolumeFromHashTable(Volume * vp)
8422 VolumeHashChainHead * head;
8424 if (!queue_IsOnQueue(vp))
8427 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8429 #ifdef AFS_DEMAND_ATTACH_FS
8430 /* wait for the hash chain to become available */
8433 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8435 #endif /* AFS_DEMAND_ATTACH_FS */
8439 /* do NOT reset hashid to zero, as the online
8440 * salvager package may need to know the volume id
8441 * after the volume is removed from the hash */
8445 * lookup a volume object in the hash table given a volume id.
8447 * @param[out] ec error code return
8448 * @param[in] volumeId volume id
8449 * @param[in] hint volume object which we believe could be the correct
8452 * @return volume object pointer
8453 * @retval NULL no such volume id is registered with the hash table.
8455 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8458 * @post volume object with the given id is returned. volume object and
8459 * hash chain access statistics are updated. hash chain may have
8462 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8463 * asynchronous hash chain reordering operation to finish, or
8464 * in order for us to perform an asynchronous chain reordering.
8466 * @note Hash chain reorderings occur when the access count for the
8467 * volume object being looked up exceeds the sum of the previous
8468 * node's (the node ahead of it in the hash chain linked list)
8469 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8471 * @note For DAFS, the hint parameter allows us to short-circuit if the
8472 * cacheCheck fields match between the hash chain head and the
8473 * hint volume object.
8476 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8480 #ifdef AFS_DEMAND_ATTACH_FS
8483 VolumeHashChainHead * head;
8486 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8488 #ifdef AFS_DEMAND_ATTACH_FS
8489 /* wait for the hash chain to become available */
8492 /* check to see if we can short circuit without walking the hash chain */
8493 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8494 IncUInt64(&hint->stats.hash_short_circuits);
8497 #endif /* AFS_DEMAND_ATTACH_FS */
8499 /* someday we need to either do per-chain locks, RWlocks,
8500 * or both for volhash access.
8501 * (and move to a data structure with better cache locality) */
8503 /* search the chain for this volume id */
8504 for(queue_Scan(head, vp, np, Volume)) {
8506 if (vp->hashid == volumeId) {
8511 if (queue_IsEnd(head, vp)) {
8515 #ifdef AFS_DEMAND_ATTACH_FS
8516 /* update hash chain statistics */
8519 FillInt64(lks, 0, looks);
8520 AddUInt64(head->looks, lks, &head->looks);
8521 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8522 IncUInt64(&head->gets);
8527 IncUInt64(&vp->stats.hash_lookups);
8529 /* for demand attach fileserver, we permit occasional hash chain reordering
8530 * so that frequently looked up volumes move towards the head of the chain */
8531 pp = queue_Prev(vp, Volume);
8532 if (!queue_IsEnd(head, pp)) {
8533 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8534 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8535 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8536 VReorderHash_r(head, pp, vp);
8540 /* update the short-circuit cache check */
8541 vp->chainCacheCheck = head->cacheCheck;
8543 #endif /* AFS_DEMAND_ATTACH_FS */
8548 #ifdef AFS_DEMAND_ATTACH_FS
8549 /* perform volume hash chain reordering.
8551 * advance a subchain beginning at vp ahead of
8552 * the adjacent subchain ending at pp */
8554 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8556 Volume *tp, *np, *lp;
8557 afs_uint64 move_thresh;
8559 /* this should never be called if the chain is already busy, so
8560 * no need to wait for other exclusive chain ops to finish */
8562 /* this is a rather heavy set of operations,
8563 * so let's set the chain busy flag and drop
8565 VHashBeginExclusive_r(head);
8568 /* scan forward in the chain from vp looking for the last element
8569 * in the chain we want to advance */
8570 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8571 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8572 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8573 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8577 lp = queue_Prev(tp, Volume);
8579 /* scan backwards from pp to determine where to splice and
8580 * insert the subchain we're advancing */
8581 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8582 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8586 tp = queue_Next(tp, Volume);
8588 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8589 queue_MoveChainBefore(tp,vp,lp);
8592 IncUInt64(&VStats.hash_reorders);
8594 IncUInt64(&head->reorders);
8596 /* wake up any threads waiting for the hash chain */
8597 VHashEndExclusive_r(head);
8601 /* demand-attach fs volume hash
8602 * asynchronous exclusive operations */
8605 * begin an asynchronous exclusive operation on a volume hash chain.
8607 * @param[in] head pointer to volume hash chain head object
8609 * @pre VOL_LOCK held. hash chain is quiescent.
8611 * @post hash chain marked busy.
8613 * @note this interface is used in conjunction with VHashEndExclusive_r and
8614 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8615 * volume hash chain. Its main use case is hash chain reordering, which
8616 * has the potential to be a highly latent operation.
8618 * @see VHashEndExclusive_r
8623 * @internal volume package internal use only.
8626 VHashBeginExclusive_r(VolumeHashChainHead * head)
8628 osi_Assert(head->busy == 0);
8633 * relinquish exclusive ownership of a volume hash chain.
8635 * @param[in] head pointer to volume hash chain head object
8637 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8639 * @post hash chain is marked quiescent. threads awaiting use of
8640 * chain are awakened.
8642 * @see VHashBeginExclusive_r
8647 * @internal volume package internal use only.
8650 VHashEndExclusive_r(VolumeHashChainHead * head)
8652 osi_Assert(head->busy);
8654 CV_BROADCAST(&head->chain_busy_cv);
8658 * wait for all asynchronous operations on a hash chain to complete.
8660 * @param[in] head pointer to volume hash chain head object
8662 * @pre VOL_LOCK held.
8664 * @post hash chain object is quiescent.
8666 * @see VHashBeginExclusive_r
8667 * @see VHashEndExclusive_r
8671 * @note This interface should be called before any attempt to
8672 * traverse the hash chain. It is permissible for a thread
8673 * to gain exclusive access to the chain, and then perform
8674 * latent operations on the chain asynchronously wrt the
8677 * @warning if waiting is necessary, VOL_LOCK is dropped
8679 * @internal volume package internal use only.
8682 VHashWait_r(VolumeHashChainHead * head)
8684 while (head->busy) {
8685 VOL_CV_WAIT(&head->chain_busy_cv);
8688 #endif /* AFS_DEMAND_ATTACH_FS */
8691 /***************************************************/
8692 /* Volume by Partition List routines */
8693 /***************************************************/
8696 * demand attach fileserver adds a
8697 * linked list of volumes to each
8698 * partition object, thus allowing
8699 * for quick enumeration of all
8700 * volumes on a partition
8703 #ifdef AFS_DEMAND_ATTACH_FS
8705 * add a volume to its disk partition VByPList.
8707 * @param[in] vp pointer to volume object
8709 * @pre either the disk partition VByPList is owned exclusively
8710 * by the calling thread, or the list is quiescent and
8713 * @post volume is added to disk partition VByPList
8717 * @warning it is the caller's responsibility to ensure list
8720 * @see VVByPListWait_r
8721 * @see VVByPListBeginExclusive_r
8722 * @see VVByPListEndExclusive_r
8724 * @internal volume package internal use only.
8727 AddVolumeToVByPList_r(Volume * vp)
8729 if (queue_IsNotOnQueue(&vp->vol_list)) {
8730 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8731 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8732 vp->partition->vol_list.len++;
8737 * delete a volume from its disk partition VByPList.
8739 * @param[in] vp pointer to volume object
8741 * @pre either the disk partition VByPList is owned exclusively
8742 * by the calling thread, or the list is quiescent and
8745 * @post volume is removed from the disk partition VByPList
8749 * @warning it is the caller's responsibility to ensure list
8752 * @see VVByPListWait_r
8753 * @see VVByPListBeginExclusive_r
8754 * @see VVByPListEndExclusive_r
8756 * @internal volume package internal use only.
8759 DeleteVolumeFromVByPList_r(Volume * vp)
8761 if (queue_IsOnQueue(&vp->vol_list)) {
8762 queue_Remove(&vp->vol_list);
8763 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8764 vp->partition->vol_list.len--;
8769 * begin an asynchronous exclusive operation on a VByPList.
8771 * @param[in] dp pointer to disk partition object
8773 * @pre VOL_LOCK held. VByPList is quiescent.
8775 * @post VByPList marked busy.
8777 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8778 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8781 * @see VVByPListEndExclusive_r
8782 * @see VVByPListWait_r
8786 * @internal volume package internal use only.
8788 /* take exclusive control over the list */
8790 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8792 osi_Assert(dp->vol_list.busy == 0);
8793 dp->vol_list.busy = 1;
8797 * relinquish exclusive ownership of a VByPList.
8799 * @param[in] dp pointer to disk partition object
8801 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8803 * @post VByPList is marked quiescent. threads awaiting use of
8804 * the list are awakened.
8806 * @see VVByPListBeginExclusive_r
8807 * @see VVByPListWait_r
8811 * @internal volume package internal use only.
8814 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8816 osi_Assert(dp->vol_list.busy);
8817 dp->vol_list.busy = 0;
8818 CV_BROADCAST(&dp->vol_list.cv);
8822 * wait for all asynchronous operations on a VByPList to complete.
8824 * @param[in] dp pointer to disk partition object
8826 * @pre VOL_LOCK is held.
8828 * @post disk partition's VByP list is quiescent
8832 * @note This interface should be called before any attempt to
8833 * traverse the VByPList. It is permissible for a thread
8834 * to gain exclusive access to the list, and then perform
8835 * latent operations on the list asynchronously wrt the
8838 * @warning if waiting is necessary, VOL_LOCK is dropped
8840 * @see VVByPListEndExclusive_r
8841 * @see VVByPListBeginExclusive_r
8843 * @internal volume package internal use only.
8846 VVByPListWait_r(struct DiskPartition64 * dp)
8848 while (dp->vol_list.busy) {
8849 VOL_CV_WAIT(&dp->vol_list.cv);
8852 #endif /* AFS_DEMAND_ATTACH_FS */
8854 /***************************************************/
8855 /* Volume Cache Statistics routines */
8856 /***************************************************/
8859 VPrintCacheStats_r(void)
8861 struct VnodeClassInfo *vcp;
8862 vcp = &VnodeClassInfo[vLarge];
8863 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);
8864 vcp = &VnodeClassInfo[vSmall];
8865 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);
8866 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8867 "%"AFS_INT64_FMT" replacements\n",
8868 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8872 VPrintCacheStats(void)
8875 VPrintCacheStats_r();
8879 #ifdef AFS_DEMAND_ATTACH_FS
8881 UInt64ToDouble(afs_uint64 * x)
8883 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8885 SplitInt64(*x, h, l);
8886 return (((double)h) * c32) + ((double) l);
8890 DoubleToPrintable(double x, char * buf, int len)
8892 static double billion = 1000000000.0;
8895 y[0] = (afs_uint32) (x / (billion * billion));
8896 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8897 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8900 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8902 snprintf(buf, len, "%d%09d", y[1], y[2]);
8904 snprintf(buf, len, "%d", y[2]);
8910 struct VLRUExtStatsEntry {
8914 struct VLRUExtStats {
8920 } queue_info[VLRU_QUEUE_INVALID];
8921 struct VLRUExtStatsEntry * vec;
8925 * add a 256-entry fudge factor onto the vector in case state changes
8926 * out from under us.
8928 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8931 * collect extended statistics for the VLRU subsystem.
8933 * @param[out] stats pointer to stats structure to be populated
8934 * @param[in] nvols number of volumes currently known to exist
8936 * @pre VOL_LOCK held
8938 * @post stats->vec allocated and populated
8940 * @return operation status
8945 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8947 afs_uint32 cur, idx, len;
8948 struct rx_queue * qp, * nqp;
8950 struct VLRUExtStatsEntry * vec;
8952 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8953 vec = stats->vec = calloc(len,
8954 sizeof(struct VLRUExtStatsEntry));
8960 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8961 VLRU_Wait_r(&volume_LRU.q[idx]);
8962 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8965 stats->queue_info[idx].start = cur;
8967 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8969 /* out of space in vec */
8972 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8973 vec[cur].volid = vp->hashid;
8977 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8980 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8988 #define ENUMTOSTRING(en) #en
8989 #define ENUMCASE(en) \
8990 case en: return ENUMTOSTRING(en)
8993 vlru_idx_to_string(int idx)
8996 ENUMCASE(VLRU_QUEUE_NEW);
8997 ENUMCASE(VLRU_QUEUE_MID);
8998 ENUMCASE(VLRU_QUEUE_OLD);
8999 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9000 ENUMCASE(VLRU_QUEUE_HELD);
9001 ENUMCASE(VLRU_QUEUE_INVALID);
9003 return "**UNKNOWN**";
9008 VPrintExtendedCacheStats_r(int flags)
9011 afs_uint32 vol_sum = 0;
9018 struct stats looks, gets, reorders, len;
9019 struct stats ch_looks, ch_gets, ch_reorders;
9021 VolumeHashChainHead *head;
9023 struct VLRUExtStats vlru_stats;
9025 /* zero out stats */
9026 memset(&looks, 0, sizeof(struct stats));
9027 memset(&gets, 0, sizeof(struct stats));
9028 memset(&reorders, 0, sizeof(struct stats));
9029 memset(&len, 0, sizeof(struct stats));
9030 memset(&ch_looks, 0, sizeof(struct stats));
9031 memset(&ch_gets, 0, sizeof(struct stats));
9032 memset(&ch_reorders, 0, sizeof(struct stats));
9034 for (i = 0; i < VolumeHashTable.Size; i++) {
9035 head = &VolumeHashTable.Table[i];
9038 VHashBeginExclusive_r(head);
9041 ch_looks.sum = UInt64ToDouble(&head->looks);
9042 ch_gets.sum = UInt64ToDouble(&head->gets);
9043 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9045 /* update global statistics */
9047 looks.sum += ch_looks.sum;
9048 gets.sum += ch_gets.sum;
9049 reorders.sum += ch_reorders.sum;
9050 len.sum += (double)head->len;
9051 vol_sum += head->len;
9054 len.min = (double) head->len;
9055 len.max = (double) head->len;
9056 looks.min = ch_looks.sum;
9057 looks.max = ch_looks.sum;
9058 gets.min = ch_gets.sum;
9059 gets.max = ch_gets.sum;
9060 reorders.min = ch_reorders.sum;
9061 reorders.max = ch_reorders.sum;
9063 if (((double)head->len) < len.min)
9064 len.min = (double) head->len;
9065 if (((double)head->len) > len.max)
9066 len.max = (double) head->len;
9067 if (ch_looks.sum < looks.min)
9068 looks.min = ch_looks.sum;
9069 else if (ch_looks.sum > looks.max)
9070 looks.max = ch_looks.sum;
9071 if (ch_gets.sum < gets.min)
9072 gets.min = ch_gets.sum;
9073 else if (ch_gets.sum > gets.max)
9074 gets.max = ch_gets.sum;
9075 if (ch_reorders.sum < reorders.min)
9076 reorders.min = ch_reorders.sum;
9077 else if (ch_reorders.sum > reorders.max)
9078 reorders.max = ch_reorders.sum;
9082 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9083 /* compute detailed per-chain stats */
9084 struct stats hdr_loads, hdr_gets;
9085 double v_looks, v_loads, v_gets;
9087 /* initialize stats with data from first element in chain */
9088 vp = queue_First(head, Volume);
9089 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9090 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9091 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9092 ch_gets.min = ch_gets.max = v_looks;
9093 hdr_loads.min = hdr_loads.max = v_loads;
9094 hdr_gets.min = hdr_gets.max = v_gets;
9095 hdr_loads.sum = hdr_gets.sum = 0;
9097 vp = queue_Next(vp, Volume);
9099 /* pull in stats from remaining elements in chain */
9100 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9101 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9102 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9103 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9105 hdr_loads.sum += v_loads;
9106 hdr_gets.sum += v_gets;
9108 if (v_looks < ch_gets.min)
9109 ch_gets.min = v_looks;
9110 else if (v_looks > ch_gets.max)
9111 ch_gets.max = v_looks;
9113 if (v_loads < hdr_loads.min)
9114 hdr_loads.min = v_loads;
9115 else if (v_loads > hdr_loads.max)
9116 hdr_loads.max = v_loads;
9118 if (v_gets < hdr_gets.min)
9119 hdr_gets.min = v_gets;
9120 else if (v_gets > hdr_gets.max)
9121 hdr_gets.max = v_gets;
9124 /* compute per-chain averages */
9125 ch_gets.avg = ch_gets.sum / ((double)head->len);
9126 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9127 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9129 /* dump per-chain stats */
9130 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9132 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9133 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9134 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9135 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9136 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9137 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9138 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9139 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9140 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9141 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9142 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9143 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9144 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9145 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9146 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9147 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9148 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9149 } else if (flags & VOL_STATS_PER_CHAIN) {
9150 /* dump simple per-chain stats */
9151 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9153 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9154 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9155 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9159 VHashEndExclusive_r(head);
9164 /* compute global averages */
9165 len.avg = len.sum / ((double)VolumeHashTable.Size);
9166 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9167 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9168 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9170 /* dump global stats */
9171 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9172 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9173 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9174 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9175 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9176 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9177 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9178 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9179 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9180 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9181 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9182 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9183 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9184 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9185 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9186 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9187 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9188 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9189 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9190 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9191 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9193 /* print extended disk related statistics */
9195 struct DiskPartition64 * diskP;
9196 afs_uint32 vol_count[VOLMAXPARTS+1];
9197 byte part_exists[VOLMAXPARTS+1];
9201 memset(vol_count, 0, sizeof(vol_count));
9202 memset(part_exists, 0, sizeof(part_exists));
9206 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9208 vol_count[id] = diskP->vol_list.len;
9209 part_exists[id] = 1;
9213 for (i = 0; i <= VOLMAXPARTS; i++) {
9214 if (part_exists[i]) {
9215 /* XXX while this is currently safe, it is a violation
9216 * of the VGetPartitionById_r interface contract. */
9217 diskP = VGetPartitionById_r(i, 0);
9219 Log("Partition %s has %d online volumes\n",
9220 VPartitionPath(diskP), diskP->vol_list.len);
9227 /* print extended VLRU statistics */
9228 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9229 afs_uint32 idx, cur, lpos;
9234 Log("VLRU State Dump:\n\n");
9236 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9237 Log("\t%s:\n", vlru_idx_to_string(idx));
9240 for (cur = vlru_stats.queue_info[idx].start;
9241 cur < vlru_stats.queue_info[idx].len;
9243 line[lpos++] = vlru_stats.vec[cur].volid;
9245 Log("\t\t%u, %u, %u, %u, %u,\n",
9246 line[0], line[1], line[2], line[3], line[4]);
9255 Log("\t\t%u, %u, %u, %u, %u\n",
9256 line[0], line[1], line[2], line[3], line[4]);
9261 free(vlru_stats.vec);
9268 VPrintExtendedCacheStats(int flags)
9271 VPrintExtendedCacheStats_r(flags);
9274 #endif /* AFS_DEMAND_ATTACH_FS */
9277 VCanScheduleSalvage(void)
9279 return vol_opts.canScheduleSalvage;
9285 return vol_opts.canUseFSSYNC;
9289 VCanUseSALVSYNC(void)
9291 return vol_opts.canUseSALVSYNC;
9295 VCanUnsafeAttach(void)
9297 return vol_opts.unsafe_attach;