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);
3004 FreeVolumeHeader(vp);
3014 #ifdef AFS_DEMAND_ATTACH_FS
3016 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3017 Volume *vp, int *acheckedOut)
3021 if (vp->pending_vol_op) {
3025 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3027 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3029 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3030 } else if (code == 0) {
3031 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3034 /* we need the vol header to determine if the volume can be
3035 * left online for the vop, so... get the header */
3039 /* attach header with peek=1 to avoid checking out the volume
3040 * or locking it; we just want the header info, we're not
3041 * messing with the volume itself at all */
3042 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3049 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3050 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3052 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3055 /* make sure we grab a new vol header and re-open stuff on
3056 * actual attachment; we can't keep the data we grabbed, since
3057 * it was not done under a lock and thus not safe */
3058 FreeVolumeHeader(vp);
3059 VReleaseVolumeHandles_r(vp);
3062 /* see if the pending volume op requires exclusive access */
3063 switch (vp->pending_vol_op->vol_op_state) {
3064 case FSSYNC_VolOpPending:
3065 /* this should never happen */
3066 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3069 case FSSYNC_VolOpRunningUnknown:
3070 /* this should never happen; we resolved 'unknown' above */
3071 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3074 case FSSYNC_VolOpRunningOffline:
3075 /* mark the volume down */
3077 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3079 /* do not set V_offlineMessage here; we don't have ownership of
3080 * the volume (and probably do not have the header loaded), so we
3081 * can't alter the disk header */
3083 /* check to see if we should set the specialStatus flag */
3084 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3085 /* don't overwrite specialStatus if it was already set to
3086 * something else (e.g. VMOVED) */
3087 if (!vp->specialStatus) {
3088 vp->specialStatus = VBUSY;
3100 #endif /* AFS_DEMAND_ATTACH_FS */
3103 * volume attachment helper function.
3105 * @param[out] ec error code
3106 * @param[in] volumeId volume ID of the attaching volume
3107 * @param[in] path full path to the volume header .vol file
3108 * @param[in] partp disk partition object for the attaching partition
3109 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3110 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3111 * DAFS) should already be initialized
3112 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3113 * if there is a volume operation running for this volume
3114 * that should set the volume to VBUSY during its run. 0
3115 * otherwise. (see VVolOpSetVBusy_r)
3116 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3118 * @param[out] acheckedOut If we successfully checked-out the volume from
3119 * the fileserver (if we needed to), this is set
3120 * to 1, otherwise it is 0.
3122 * @return pointer to the semi-attached volume pointer
3123 * @retval NULL an error occurred (check value of *ec)
3124 * @retval vp volume successfully attaching
3126 * @pre no locks held
3128 * @post VOL_LOCK held
3131 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3132 Volume * vp, int isbusy, int mode, int *acheckedOut)
3134 /* have we read in the header successfully? */
3135 int read_header = 0;
3137 #ifdef AFS_DEMAND_ATTACH_FS
3138 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3142 /* in the case of an error, to what state should the volume be
3144 VolState error_state = VOL_STATE_ERROR;
3145 #endif /* AFS_DEMAND_ATTACH_FS */
3149 vp->vnodeIndex[vLarge].handle = NULL;
3150 vp->vnodeIndex[vSmall].handle = NULL;
3151 vp->diskDataHandle = NULL;
3152 vp->linkHandle = NULL;
3156 #ifdef AFS_DEMAND_ATTACH_FS
3157 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3159 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3162 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3163 #endif /* !AFS_DEMAND_ATTACH_FS */
3165 if (*ec == VNOVOL) {
3166 /* if the volume doesn't exist, skip straight to 'error' so we don't
3167 * request a salvage */
3169 goto error_notbroken;
3175 /* ensure that we don't override specialStatus if it was set to
3176 * something else (e.g. VMOVED) */
3177 if (isbusy && !vp->specialStatus) {
3178 vp->specialStatus = VBUSY;
3180 vp->shuttingDown = 0;
3181 vp->goingOffline = 0;
3183 #ifdef AFS_DEMAND_ATTACH_FS
3184 vp->stats.last_attach = FT_ApproxTime();
3185 vp->stats.attaches++;
3189 IncUInt64(&VStats.attaches);
3190 vp->cacheCheck = ++VolumeCacheCheck;
3191 /* just in case this ever rolls over */
3192 if (!vp->cacheCheck)
3193 vp->cacheCheck = ++VolumeCacheCheck;
3196 #ifdef AFS_DEMAND_ATTACH_FS
3197 V_attachFlags(vp) |= VOL_HDR_LOADED;
3198 vp->stats.last_hdr_load = vp->stats.last_attach;
3199 #endif /* AFS_DEMAND_ATTACH_FS */
3203 struct IndexFileHeader iHead;
3206 * We just read in the diskstuff part of the header. If the detailed
3207 * volume stats area has not yet been initialized, we should bzero the
3208 * area and mark it as initialized.
3210 if (!(V_stat_initialized(vp))) {
3211 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3212 V_stat_initialized(vp) = 1;
3215 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3216 (char *)&iHead, sizeof(iHead),
3217 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3220 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3225 struct IndexFileHeader iHead;
3227 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3228 (char *)&iHead, sizeof(iHead),
3229 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3232 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3236 #ifdef AFS_NAMEI_ENV
3238 struct versionStamp stamp;
3240 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3241 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3244 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3247 #endif /* AFS_NAMEI_ENV */
3249 #if defined(AFS_DEMAND_ATTACH_FS)
3250 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3252 if (!VCanScheduleSalvage()) {
3253 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3255 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3260 /* volume operation in progress */
3262 goto error_notbroken;
3264 #else /* AFS_DEMAND_ATTACH_FS */
3266 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3267 goto unlocked_error;
3269 #endif /* AFS_DEMAND_ATTACH_FS */
3271 if (V_needsSalvaged(vp)) {
3272 if (vp->specialStatus)
3273 vp->specialStatus = 0;
3275 #if defined(AFS_DEMAND_ATTACH_FS)
3276 if (!VCanScheduleSalvage()) {
3277 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3279 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3282 #else /* AFS_DEMAND_ATTACH_FS */
3284 #endif /* AFS_DEMAND_ATTACH_FS */
3290 vp->nextVnodeUnique = V_uniquifier(vp);
3292 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3293 if (!V_needsSalvaged(vp)) {
3294 V_needsSalvaged(vp) = 1;
3295 VUpdateVolume_r(ec, vp, 0);
3297 #if defined(AFS_DEMAND_ATTACH_FS)
3298 if (!VCanScheduleSalvage()) {
3299 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3301 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3304 #else /* AFS_DEMAND_ATTACH_FS */
3305 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3307 #endif /* AFS_DEMAND_ATTACH_FS */
3312 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3313 /* Only check destroyMe if we are the fileserver, since the
3314 * volserver et al sometimes need to work with volumes with
3315 * destroyMe set. Examples are 'temporary' volumes the
3316 * volserver creates, and when we create a volume (destroyMe
3317 * is set on creation; sometimes a separate volserver
3318 * transaction is created to clear destroyMe).
3321 #if defined(AFS_DEMAND_ATTACH_FS)
3322 /* schedule a salvage so the volume goes away on disk */
3323 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3324 VChangeState_r(vp, VOL_STATE_ERROR);
3327 #endif /* AFS_DEMAND_ATTACH_FS */
3328 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3333 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3334 #ifndef BITMAP_LATER
3335 if (programType == fileServer && VolumeWriteable(vp)) {
3337 for (i = 0; i < nVNODECLASSES; i++) {
3338 VGetBitmap_r(ec, vp, i);
3340 #ifdef AFS_DEMAND_ATTACH_FS
3341 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3343 #endif /* AFS_DEMAND_ATTACH_FS */
3344 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3350 #endif /* BITMAP_LATER */
3352 if (VInit >= 2 && V_needsCallback(vp)) {
3353 if (V_BreakVolumeCallbacks) {
3354 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3355 afs_printable_uint32_lu(V_id(vp)));
3356 V_needsCallback(vp) = 0;
3358 (*V_BreakVolumeCallbacks) (V_id(vp));
3361 VUpdateVolume_r(ec, vp, 0);
3363 #ifdef FSSYNC_BUILD_CLIENT
3364 else if (VCanUseFSSYNC()) {
3365 afs_int32 fsync_code;
3367 V_needsCallback(vp) = 0;
3369 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3373 V_needsCallback(vp) = 1;
3374 Log("Error trying to tell the fileserver to break callbacks for "
3375 "changed volume %lu; error code %ld\n",
3376 afs_printable_uint32_lu(V_id(vp)),
3377 afs_printable_int32_ld(fsync_code));
3379 VUpdateVolume_r(ec, vp, 0);
3382 #endif /* FSSYNC_BUILD_CLIENT */
3385 Log("VAttachVolume: error %d clearing needsCallback on volume "
3386 "%lu; needs salvage\n", (int)*ec,
3387 afs_printable_uint32_lu(V_id(vp)));
3388 #ifdef AFS_DEMAND_ATTACH_FS
3389 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3391 #else /* !AFS_DEMAND_ATTACH_FS */
3393 #endif /* !AFS_DEMAND_ATTACh_FS */
3398 if (programType == fileServer) {
3399 if (vp->specialStatus)
3400 vp->specialStatus = 0;
3401 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3402 V_inUse(vp) = fileServer;
3403 V_offlineMessage(vp)[0] = '\0';
3407 #ifdef AFS_DEMAND_ATTACH_FS
3408 /* Put the vol into PREATTACHED state, so if someone tries to
3409 * access it again, we try to attach, see that we're not blessed,
3410 * and give a VNOVOL error again. Putting it into UNATTACHED state
3411 * would result in a VOFFLINE error instead. */
3412 error_state = VOL_STATE_PREATTACHED;
3413 #endif /* AFS_DEMAND_ATTACH_FS */
3415 /* mimic e.g. GetVolume errors */
3416 if (!V_blessed(vp)) {
3417 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3418 FreeVolumeHeader(vp);
3419 } else if (!V_inService(vp)) {
3420 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3421 FreeVolumeHeader(vp);
3423 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3425 #ifdef AFS_DEMAND_ATTACH_FS
3426 error_state = VOL_STATE_ERROR;
3427 /* see if we can recover */
3428 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0 /*flags*/);
3431 #ifdef AFS_DEMAND_ATTACH_FS
3437 #ifdef AFS_DEMAND_ATTACH_FS
3438 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3439 V_inUse(vp) = programType;
3440 #endif /* AFS_DEMAND_ATTACH_FS */
3441 V_checkoutMode(vp) = mode;
3444 AddVolumeToHashTable(vp, V_id(vp));
3445 #ifdef AFS_DEMAND_ATTACH_FS
3446 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3449 if ((programType != fileServer) ||
3450 (V_inUse(vp) == fileServer)) {
3451 AddVolumeToVByPList_r(vp);
3453 VChangeState_r(vp, VOL_STATE_ATTACHED);
3455 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3461 #ifndef AFS_DEMAND_ATTACH_FS
3467 #ifdef AFS_DEMAND_ATTACH_FS
3468 if (!VIsErrorState(V_attachState(vp))) {
3469 if (VIsErrorState(error_state)) {
3470 Log("attach2: forcing vol %u to error state (state %u flags 0x%x ec %d)\n",
3471 vp->hashid, V_attachState(vp), V_attachFlags(vp), *ec);
3473 VChangeState_r(vp, error_state);
3475 #endif /* AFS_DEMAND_ATTACH_FS */
3478 VReleaseVolumeHandles_r(vp);
3482 #ifdef AFS_DEMAND_ATTACH_FS
3489 #else /* !AFS_DEMAND_ATTACH_FS */
3491 #endif /* !AFS_DEMAND_ATTACH_FS */
3495 /* Attach an existing volume.
3496 The volume also normally goes online at this time.
3497 An offline volume must be reattached to make it go online.
3501 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3505 retVal = VAttachVolume_r(ec, volumeId, mode);
3511 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3514 VGetVolumePath(ec, volumeId, &part, &name);
3518 vp = VGetVolume_r(&error, volumeId);
3520 osi_Assert(V_inUse(vp) == 0);
3521 VDetachVolume_r(ec, vp);
3525 return VAttachVolumeByName_r(ec, part, name, mode);
3528 /* Increment a reference count to a volume, sans context swaps. Requires
3529 * possibly reading the volume header in from the disk, since there's
3530 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3532 * N.B. This call can fail if we can't read in the header!! In this case
3533 * we still guarantee we won't context swap, but the ref count won't be
3534 * incremented (otherwise we'd violate the invariant).
3536 /* NOTE: with the demand attach fileserver extensions, the global lock
3537 * is dropped within VHold */
3538 #ifdef AFS_DEMAND_ATTACH_FS
3540 VHold_r(Volume * vp)
3544 VCreateReservation_r(vp);
3545 VWaitExclusiveState_r(vp);
3547 LoadVolumeHeader(&error, vp);
3549 VCancelReservation_r(vp);
3553 VCancelReservation_r(vp);
3556 #else /* AFS_DEMAND_ATTACH_FS */
3558 VHold_r(Volume * vp)
3562 LoadVolumeHeader(&error, vp);
3568 #endif /* AFS_DEMAND_ATTACH_FS */
3570 /**** volume timeout-related stuff ****/
3572 #ifdef AFS_PTHREAD_ENV
3574 static struct timespec *shutdown_timeout;
3575 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3578 VTimedOut(const struct timespec *ts)
3583 if (ts->tv_sec == 0) {
3584 /* short-circuit; this will have always timed out */
3588 code = gettimeofday(&tv, NULL);
3590 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3591 /* assume no timeout; failure mode is we just wait longer than normal
3592 * instead of returning errors when we shouldn't */
3596 if (tv.tv_sec < ts->tv_sec ||
3597 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3606 * Calculate an absolute timeout.
3608 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3609 * NULL, the memory is not touched
3610 * @param[in] timeout How long the timeout should be from now
3612 * @return timeout to use
3613 * @retval NULL no timeout; wait forever
3614 * @retval non-NULL the given value for "ts"
3618 static struct timespec *
3619 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3629 ts->tv_sec = ts->tv_nsec = 0;
3633 code = gettimeofday(&now, NULL);
3635 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3639 ts->tv_sec = now.tv_sec + timeout;
3640 ts->tv_nsec = now.tv_usec * 1000;
3646 * Initialize the shutdown_timeout global.
3649 VShutdownTimeoutInit(void)
3651 struct timespec *ts;
3653 ts = malloc(sizeof(*ts));
3655 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3657 if (!shutdown_timeout) {
3663 * Figure out the timeout that should be used for waiting for offline volumes.
3665 * @param[out] ats Storage space for a local timeout value if needed
3667 * @return The timeout value that should be used
3668 * @retval NULL No timeout; wait forever for offlining volumes
3669 * @retval non-NULL A pointer to the absolute time that should be used as
3670 * the deadline for waiting for offlining volumes.
3672 * @note If we return non-NULL, the pointer we return may or may not be the
3675 static const struct timespec *
3676 VOfflineTimeout(struct timespec *ats)
3678 if (vol_shutting_down) {
3679 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3680 return shutdown_timeout;
3682 return VCalcTimeout(ats, vol_opts.offline_timeout);
3686 #else /* AFS_PTHREAD_ENV */
3688 /* Waiting a certain amount of time for offlining volumes is not supported
3689 * for LWP due to a lack of primitives. So, we never time out */
3690 # define VTimedOut(x) (0)
3691 # define VOfflineTimeout(x) (NULL)
3693 #endif /* !AFS_PTHREAD_ENV */
3701 retVal = VHold_r(vp);
3708 VIsGoingOffline_r(struct Volume *vp)
3712 if (vp->goingOffline) {
3713 if (vp->specialStatus) {
3714 code = vp->specialStatus;
3715 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3726 * Tell the caller if a volume is waiting to go offline.
3728 * @param[in] vp The volume we want to know about
3730 * @return volume status
3731 * @retval 0 volume is not waiting to go offline, go ahead and use it
3732 * @retval nonzero volume is waiting to offline, and give the returned code
3733 * as an error to anyone accessing the volume
3735 * @pre VOL_LOCK is NOT held
3736 * @pre caller holds a heavyweight reference on vp
3739 VIsGoingOffline(struct Volume *vp)
3744 code = VIsGoingOffline_r(vp);
3751 * Register an RX call with a volume.
3753 * @param[inout] ec Error code; if unset when passed in, may be set if
3754 * the volume starts going offline
3755 * @param[out] client_ec @see GetVolume
3756 * @param[in] vp Volume struct
3757 * @param[in] cbv VCallByVol struct containing the RX call to register
3759 * @pre VOL_LOCK held
3760 * @pre caller holds heavy ref on vp
3765 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3768 #ifdef AFS_DEMAND_ATTACH_FS
3770 /* just in case the volume started going offline after we got the
3771 * reference to it... otherwise, if the volume started going
3772 * offline right at the end of GetVolume(), we might race with the
3773 * RX call scanner, and return success and add our cbv to the
3774 * rx_call_list _after_ the scanner has scanned the list. */
3775 *ec = VIsGoingOffline_r(vp);
3781 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3782 VWaitStateChange_r(vp);
3784 #endif /* AFS_DEMAND_ATTACH_FS */
3786 queue_Prepend(&vp->rx_call_list, cbv);
3791 * Deregister an RX call with a volume.
3793 * @param[in] vp Volume struct
3794 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3796 * @pre VOL_LOCK held
3797 * @pre caller holds heavy ref on vp
3802 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3804 if (cbv && queue_IsOnQueue(cbv)) {
3805 #ifdef AFS_DEMAND_ATTACH_FS
3806 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3807 VWaitStateChange_r(vp);
3809 #endif /* AFS_DEMAND_ATTACH_FS */
3815 /***************************************************/
3816 /* get and put volume routines */
3817 /***************************************************/
3820 * put back a heavyweight reference to a volume object.
3822 * @param[in] vp volume object pointer
3824 * @pre VOL_LOCK held
3826 * @post heavyweight volume reference put back.
3827 * depending on state, volume may have been taken offline,
3828 * detached, salvaged, freed, etc.
3830 * @internal volume package internal use only
3833 VPutVolume_r(Volume * vp)
3835 osi_Assert(--vp->nUsers >= 0);
3836 if (vp->nUsers == 0) {
3838 ReleaseVolumeHeader(vp->header);
3839 #ifdef AFS_DEMAND_ATTACH_FS
3840 if (!VCheckDetach(vp)) {
3844 #else /* AFS_DEMAND_ATTACH_FS */
3846 #endif /* AFS_DEMAND_ATTACH_FS */
3851 VPutVolume(Volume * vp)
3859 * Puts a volume reference obtained with VGetVolumeWithCall.
3861 * @param[in] vp Volume struct
3862 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3864 * @pre VOL_LOCK is NOT held
3867 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3870 VDeregisterCall_r(vp, cbv);
3875 /* Get a pointer to an attached volume. The pointer is returned regardless
3876 of whether or not the volume is in service or on/off line. An error
3877 code, however, is returned with an indication of the volume's status */
3879 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3883 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3889 * Get a volume reference associated with an RX call.
3891 * @param[out] ec @see GetVolume
3892 * @param[out] client_ec @see GetVolume
3893 * @param[in] volumeId @see GetVolume
3894 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3895 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3896 * with an error if the volume is going offline.
3897 * @param[in] cbv Contains an RX call to be associated with this volume
3898 * reference. This call may be interrupted if the volume is
3899 * requested to go offline while we hold a ref on it. Give NULL
3900 * to not associate an RX call with this reference.
3902 * @return @see GetVolume
3904 * @note for LWP builds, ts must be NULL
3906 * @note A reference obtained with this function MUST be put back with
3907 * VPutVolumeWithCall
3910 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3911 const struct timespec *ts, struct VCallByVol *cbv)
3915 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3916 VRegisterCall_r(ec, client_ec, retVal, cbv);
3922 VGetVolume_r(Error * ec, VolId volumeId)
3924 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3927 /* try to get a volume we've previously looked up */
3928 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3930 VGetVolumeByVp_r(Error * ec, Volume * vp)
3932 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3936 * private interface for getting a volume handle
3938 * @param[out] ec error code (0 if no error)
3939 * @param[out] client_ec wire error code to be given to clients
3940 * @param[in] volumeId ID of the volume we want
3941 * @param[in] hint optional hint for hash lookups, or NULL
3942 * @param[in] timeout absolute deadline for waiting for the volume to go
3943 * offline, if it is going offline. NULL to wait forever.
3945 * @return a volume handle for the specified volume
3946 * @retval NULL an error occurred, or the volume is in such a state that
3947 * we cannot load a header or return any volume struct
3949 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3951 * @note 'timeout' is only checked if the volume is actually going offline; so
3952 * if you pass timeout->tv_sec = 0, this will exhibit typical
3953 * nonblocking behavior.
3955 * @note for LWP builds, 'timeout' must be NULL
3958 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3959 const struct timespec *timeout)
3962 /* pull this profiling/debugging code out of regular builds */
3964 #define VGET_CTR_INC(x) x++
3965 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3966 0, V7 = 0, V8 = 0, V9 = 0;
3967 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3969 #define VGET_CTR_INC(x)
3971 #ifdef AFS_DEMAND_ATTACH_FS
3972 Volume *avp, * rvp = hint;
3976 * if VInit is zero, the volume package dynamic
3977 * data structures have not been initialized yet,
3978 * and we must immediately return an error
3984 *client_ec = VOFFLINE;
3989 #ifdef AFS_DEMAND_ATTACH_FS
3991 VCreateReservation_r(rvp);
3993 #endif /* AFS_DEMAND_ATTACH_FS */
4001 vp = VLookupVolume_r(ec, volumeId, vp);
4007 #ifdef AFS_DEMAND_ATTACH_FS
4008 if (rvp && (rvp != vp)) {
4009 /* break reservation on old vp */
4010 VCancelReservation_r(rvp);
4013 #endif /* AFS_DEMAND_ATTACH_FS */
4019 /* Until we have reached an initialization level of 2
4020 * we don't know whether this volume exists or not.
4021 * We can't sleep and retry later because before a volume
4022 * is attached, the caller tries to get it first. Just
4023 * return VOFFLINE and the caller can choose whether to
4024 * retry the command or not. */
4034 IncUInt64(&VStats.hdr_gets);
4036 #ifdef AFS_DEMAND_ATTACH_FS
4037 /* block if someone else is performing an exclusive op on this volume */
4040 VCreateReservation_r(rvp);
4042 VWaitExclusiveState_r(vp);
4044 /* short circuit with VNOVOL in the following circumstances:
4047 * - VOL_STATE_SHUTTING_DOWN
4049 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4050 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4057 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4058 * VNOVOL for VOL_STATE_DELETED
4060 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4061 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4062 (V_attachState(vp) == VOL_STATE_DELETED)) {
4063 if (vp->specialStatus) {
4064 *ec = vp->specialStatus;
4065 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4074 /* allowable states:
4081 if (vp->salvage.requested) {
4082 VUpdateSalvagePriority_r(vp);
4085 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4086 if (vp->specialStatus) {
4087 *ec = vp->specialStatus;
4091 avp = VAttachVolumeByVp_r(ec, vp, 0);
4094 /* VAttachVolumeByVp_r can return a pointer
4095 * != the vp passed to it under certain
4096 * conditions; make sure we don't leak
4097 * reservations if that happens */
4099 VCancelReservation_r(rvp);
4101 VCreateReservation_r(rvp);
4112 if (vp->specialStatus) {
4113 *ec = vp->specialStatus;
4118 if (vp->specialStatus) {
4119 *ec = vp->specialStatus;
4132 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4134 /* see CheckVnode() in afsfileprocs.c for an explanation
4135 * of this error code logic */
4136 afs_uint32 now = FT_ApproxTime();
4137 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4140 *client_ec = VRESTARTING;
4148 if (VIsErrorState(V_attachState(vp))) {
4149 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4150 * it, or transition it out of that state */
4159 * this test MUST happen after VAttachVolymeByVp, so we have no
4160 * conflicting vol op. (attach2 would have errored out if we had one;
4161 * specifically attach_check_vop must have detected a conflicting vop)
4163 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4165 #endif /* AFS_DEMAND_ATTACH_FS */
4167 LoadVolumeHeader(ec, vp);
4170 /* Only log the error if it was a totally unexpected error. Simply
4171 * a missing inode is likely to be caused by the volume being deleted */
4172 if (errno != ENXIO || LogLevel)
4173 Log("Volume %u: couldn't reread volume header\n",
4175 #ifdef AFS_DEMAND_ATTACH_FS
4176 if (VCanScheduleSalvage()) {
4177 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4182 #else /* AFS_DEMAND_ATTACH_FS */
4185 #endif /* AFS_DEMAND_ATTACH_FS */
4190 if (vp->shuttingDown) {
4197 if (programType == fileServer) {
4199 if (vp->goingOffline) {
4200 if (timeout && VTimedOut(timeout)) {
4201 /* we've timed out; don't wait for the vol */
4204 #ifdef AFS_DEMAND_ATTACH_FS
4205 /* wait for the volume to go offline */
4206 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4207 VTimedWaitStateChange_r(vp, timeout, NULL);
4209 #elif defined(AFS_PTHREAD_ENV)
4210 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4211 #else /* AFS_PTHREAD_ENV */
4212 /* LWP has no timed wait, so the caller better not be
4214 osi_Assert(!timeout);
4215 LWP_WaitProcess(VPutVolume);
4216 #endif /* AFS_PTHREAD_ENV */
4220 if (vp->specialStatus) {
4222 *ec = vp->specialStatus;
4223 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4226 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4237 #ifdef AFS_DEMAND_ATTACH_FS
4238 /* if no error, bump nUsers */
4241 VLRU_UpdateAccess_r(vp);
4244 VCancelReservation_r(rvp);
4247 if (client_ec && !*client_ec) {
4250 #else /* AFS_DEMAND_ATTACH_FS */
4251 /* if no error, bump nUsers */
4258 #endif /* AFS_DEMAND_ATTACH_FS */
4261 osi_Assert(vp || *ec);
4266 /***************************************************/
4267 /* Volume offline/detach routines */
4268 /***************************************************/
4270 /* caller MUST hold a heavyweight ref on vp */
4271 #ifdef AFS_DEMAND_ATTACH_FS
4273 VTakeOffline_r(Volume * vp)
4277 osi_Assert(vp->nUsers > 0);
4278 osi_Assert(programType == fileServer);
4280 VCreateReservation_r(vp);
4281 VWaitExclusiveState_r(vp);
4283 vp->goingOffline = 1;
4284 V_needsSalvaged(vp) = 1;
4286 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4287 VCancelReservation_r(vp);
4289 #else /* AFS_DEMAND_ATTACH_FS */
4291 VTakeOffline_r(Volume * vp)
4293 osi_Assert(vp->nUsers > 0);
4294 osi_Assert(programType == fileServer);
4296 vp->goingOffline = 1;
4297 V_needsSalvaged(vp) = 1;
4299 #endif /* AFS_DEMAND_ATTACH_FS */
4302 VTakeOffline(Volume * vp)
4310 * force a volume offline.
4312 * @param[in] vp volume object pointer
4313 * @param[in] flags flags (see note below)
4315 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4316 * used when VUpdateVolume_r needs to call VForceOffline_r
4317 * (which in turn would normally call VUpdateVolume_r)
4319 * @see VUpdateVolume_r
4321 * @pre VOL_LOCK must be held.
4322 * for DAFS, caller must hold ref.
4324 * @note for DAFS, it _is safe_ to call this function from an
4327 * @post needsSalvaged flag is set.
4328 * for DAFS, salvage is requested.
4329 * no further references to the volume through the volume
4330 * package will be honored.
4331 * all file descriptor and vnode caches are invalidated.
4333 * @warning this is a heavy-handed interface. it results in
4334 * a volume going offline regardless of the current
4335 * reference count state.
4337 * @internal volume package internal use only
4340 VForceOffline_r(Volume * vp, int flags)
4344 #ifdef AFS_DEMAND_ATTACH_FS
4345 VChangeState_r(vp, VOL_STATE_ERROR);
4350 strcpy(V_offlineMessage(vp),
4351 "Forced offline due to internal error: volume needs to be salvaged");
4352 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4355 vp->goingOffline = 0;
4356 V_needsSalvaged(vp) = 1;
4357 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4358 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4361 #ifdef AFS_DEMAND_ATTACH_FS
4362 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4363 #endif /* AFS_DEMAND_ATTACH_FS */
4365 #ifdef AFS_PTHREAD_ENV
4366 CV_BROADCAST(&vol_put_volume_cond);
4367 #else /* AFS_PTHREAD_ENV */
4368 LWP_NoYieldSignal(VPutVolume);
4369 #endif /* AFS_PTHREAD_ENV */
4371 VReleaseVolumeHandles_r(vp);
4375 * force a volume offline.
4377 * @param[in] vp volume object pointer
4379 * @see VForceOffline_r
4382 VForceOffline(Volume * vp)
4385 VForceOffline_r(vp, 0);
4390 * Iterate over the RX calls associated with a volume, and interrupt them.
4392 * @param[in] vp The volume whose RX calls we want to scan
4394 * @pre VOL_LOCK held
4397 VScanCalls_r(struct Volume *vp)
4399 struct VCallByVol *cbv, *ncbv;
4401 #ifdef AFS_DEMAND_ATTACH_FS
4402 VolState state_save;
4405 if (queue_IsEmpty(&vp->rx_call_list))
4406 return; /* no calls to interrupt */
4407 if (!vol_opts.interrupt_rxcall)
4408 return; /* we have no function with which to interrupt calls */
4409 err = VIsGoingOffline_r(vp);
4411 return; /* we're not going offline anymore */
4413 #ifdef AFS_DEMAND_ATTACH_FS
4414 VWaitExclusiveState_r(vp);
4415 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4417 #endif /* AFS_DEMAND_ATTACH_FS */
4419 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4421 struct rx_peer *peer;
4423 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4425 Log("Offlining volume %lu while client %s:%u is trying to read "
4426 "from it; kicking client off with error %ld\n",
4427 (long unsigned) vp->hashid,
4428 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4429 (unsigned) ntohs(rx_PortOf(peer)),
4432 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4435 #ifdef AFS_DEMAND_ATTACH_FS
4437 VChangeState_r(vp, state_save);
4438 #endif /* AFS_DEMAND_ATTACH_FS */
4441 #ifdef AFS_DEMAND_ATTACH_FS
4443 * Wait for a vp to go offline.
4445 * @param[out] ec 1 if a salvage on the volume has been requested and
4446 * salvok == 0, 0 otherwise
4447 * @param[in] vp The volume to wait for
4448 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4449 * has been requested to salvage. Otherwise we keep waiting
4450 * until the volume has gone offline.
4452 * @pre VOL_LOCK held
4453 * @pre caller holds a lightweight ref on vp
4458 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4460 struct timespec timeout_ts;
4461 const struct timespec *ts;
4464 ts = VOfflineTimeout(&timeout_ts);
4468 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4469 if (!salvok && vp->salvage.requested) {
4473 VTimedWaitStateChange_r(vp, ts, &timedout);
4476 /* we didn't time out, so the volume must be offline, so we're done */
4480 /* If we got here, we timed out waiting for the volume to go offline.
4481 * Kick off the accessing RX calls and wait again */
4485 while (!VIsOfflineState(V_attachState(vp))) {
4486 if (!salvok && vp->salvage.requested) {
4491 VWaitStateChange_r(vp);
4495 #else /* AFS_DEMAND_ATTACH_FS */
4498 * Wait for a volume to go offline.
4500 * @pre VOL_LOCK held
4502 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4505 VWaitForOffline_r(Error *ec, VolumeId volid)
4508 const struct timespec *ts;
4509 #ifdef AFS_PTHREAD_ENV
4510 struct timespec timeout_ts;
4513 ts = VOfflineTimeout(&timeout_ts);
4515 vp = GetVolume(ec, NULL, volid, NULL, ts);
4517 /* error occurred so bad that we can't even get a vp; we have no
4518 * information on the vol so we don't know whether to wait, so just
4522 if (!VIsGoingOffline_r(vp)) {
4523 /* volume is no longer going offline, so we're done */
4528 /* If we got here, we timed out waiting for the volume to go offline.
4529 * Kick off the accessing RX calls and wait again */
4535 vp = VGetVolume_r(ec, volid);
4537 /* In case it was reattached... */
4541 #endif /* !AFS_DEMAND_ATTACH_FS */
4543 /* The opposite of VAttachVolume. The volume header is written to disk, with
4544 the inUse bit turned off. A copy of the header is maintained in memory,
4545 however (which is why this is VOffline, not VDetach).
4548 VOffline_r(Volume * vp, char *message)
4551 #ifndef AFS_DEMAND_ATTACH_FS
4552 VolumeId vid = V_id(vp);
4555 osi_Assert(programType != volumeUtility && programType != volumeServer);
4560 if (V_offlineMessage(vp)[0] == '\0')
4561 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4562 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4564 vp->goingOffline = 1;
4565 #ifdef AFS_DEMAND_ATTACH_FS
4566 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4567 VCreateReservation_r(vp);
4569 VWaitForOfflineByVp_r(&error, vp, 1);
4570 VCancelReservation_r(vp);
4571 #else /* AFS_DEMAND_ATTACH_FS */
4573 VWaitForOffline_r(&error, vid);
4574 #endif /* AFS_DEMAND_ATTACH_FS */
4577 #ifdef AFS_DEMAND_ATTACH_FS
4579 * Take a volume offline in order to perform a volume operation.
4581 * @param[inout] ec address in which to store error code
4582 * @param[in] vp volume object pointer
4583 * @param[in] message volume offline status message
4586 * - VOL_LOCK is held
4587 * - caller MUST hold a heavyweight ref on vp
4590 * - volume is taken offline
4591 * - if possible, volume operation is promoted to running state
4592 * - on failure, *ec is set to nonzero
4594 * @note Although this function does not return any value, it may
4595 * still fail to promote our pending volume operation to
4596 * a running state. Any caller MUST check the value of *ec,
4597 * and MUST NOT blindly assume success.
4599 * @warning if the caller does not hold a lightweight ref on vp,
4600 * then it MUST NOT reference vp after this function
4601 * returns to the caller.
4603 * @internal volume package internal use only
4606 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4609 osi_Assert(vp->pending_vol_op);
4615 if (V_offlineMessage(vp)[0] == '\0')
4616 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4617 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4619 vp->goingOffline = 1;
4620 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4621 VCreateReservation_r(vp);
4624 if (vp->pending_vol_op->com.programType != salvageServer) {
4625 /* do not give corrupted volumes to the volserver */
4630 VWaitForOfflineByVp_r(ec, vp, salvok);
4632 VCancelReservation_r(vp);
4634 #endif /* AFS_DEMAND_ATTACH_FS */
4637 VOffline(Volume * vp, char *message)
4640 VOffline_r(vp, message);
4644 /* This gets used for the most part by utility routines that don't want
4645 * to keep all the volume headers around. Generally, the file server won't
4646 * call this routine, because then the offline message in the volume header
4647 * (or other information) won't be available to clients. For NAMEI, also
4648 * close the file handles. However, the fileserver does call this during
4649 * an attach following a volume operation.
4652 VDetachVolume_r(Error * ec, Volume * vp)
4654 #ifdef FSSYNC_BUILD_CLIENT
4656 struct DiskPartition64 *tpartp;
4657 int notifyServer = 0;
4658 int useDone = FSYNC_VOL_ON;
4660 if (VCanUseFSSYNC()) {
4661 notifyServer = vp->needsPutBack;
4662 if (V_destroyMe(vp) == DESTROY_ME)
4663 useDone = FSYNC_VOL_LEAVE_OFF;
4664 # ifdef AFS_DEMAND_ATTACH_FS
4665 else if (!V_blessed(vp) || !V_inService(vp))
4666 useDone = FSYNC_VOL_LEAVE_OFF;
4669 # ifdef AFS_DEMAND_ATTACH_FS
4670 if (V_needsSalvaged(vp)) {
4672 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4675 tpartp = vp->partition;
4677 #endif /* FSSYNC_BUILD_CLIENT */
4679 *ec = 0; /* always "succeeds" */
4680 DeleteVolumeFromHashTable(vp);
4681 vp->shuttingDown = 1;
4682 #ifdef AFS_DEMAND_ATTACH_FS
4683 DeleteVolumeFromVByPList_r(vp);
4685 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4687 if (programType != fileServer)
4689 #endif /* AFS_DEMAND_ATTACH_FS */
4691 /* Will be detached sometime in the future--this is OK since volume is offline */
4693 /* XXX the following code should really be moved to VCheckDetach() since the volume
4694 * is not technically detached until the refcounts reach zero
4696 #ifdef FSSYNC_BUILD_CLIENT
4697 if (VCanUseFSSYNC() && notifyServer) {
4698 if (notifyServer == VOL_PUTBACK_DELETE) {
4699 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4700 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4701 * to signify a deleted volume. */
4702 useDone = FSYNC_VOL_DONE;
4705 * Note: The server is not notified in the case of a bogus volume
4706 * explicitly to make it possible to create a volume, do a partial
4707 * restore, then abort the operation without ever putting the volume
4708 * online. This is essential in the case of a volume move operation
4709 * between two partitions on the same server. In that case, there
4710 * would be two instances of the same volume, one of them bogus,
4711 * which the file server would attempt to put on line
4713 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4714 /* XXX this code path is only hit by volume utilities, thus
4715 * V_BreakVolumeCallbacks will always be NULL. if we really
4716 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4718 /* Dettaching it so break all callbacks on it */
4719 if (V_BreakVolumeCallbacks) {
4720 Log("volume %u detached; breaking all call backs\n", volume);
4721 (*V_BreakVolumeCallbacks) (volume);
4725 #endif /* FSSYNC_BUILD_CLIENT */
4729 VDetachVolume(Error * ec, Volume * vp)
4732 VDetachVolume_r(ec, vp);
4737 /***************************************************/
4738 /* Volume fd/inode handle closing routines */
4739 /***************************************************/
4741 /* For VDetachVolume, we close all cached file descriptors, but keep
4742 * the Inode handles in case we need to read from a busy volume.
4744 /* for demand attach, caller MUST hold ref count on vp */
4746 VCloseVolumeHandles_r(Volume * vp)
4748 #ifdef AFS_DEMAND_ATTACH_FS
4749 VolState state_save;
4751 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4756 DFlushVolume(vp->hashid);
4758 #ifdef AFS_DEMAND_ATTACH_FS
4762 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4763 VCloseVnodeFiles_r(vp);
4765 #ifdef AFS_DEMAND_ATTACH_FS
4769 /* Too time consuming and unnecessary for the volserver */
4770 if (programType == fileServer) {
4771 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4772 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4773 IH_CONDSYNC(vp->diskDataHandle);
4775 IH_CONDSYNC(vp->linkHandle);
4776 #endif /* AFS_NT40_ENV */
4779 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4780 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4781 IH_REALLYCLOSE(vp->diskDataHandle);
4782 IH_REALLYCLOSE(vp->linkHandle);
4784 #ifdef AFS_DEMAND_ATTACH_FS
4785 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4790 VChangeState_r(vp, state_save);
4794 /* For both VForceOffline and VOffline, we close all relevant handles.
4795 * For VOffline, if we re-attach the volume, the files may possible be
4796 * different than before.
4798 /* for demand attach, caller MUST hold a ref count on vp */
4800 VReleaseVolumeHandles_r(Volume * vp)
4802 #ifdef AFS_DEMAND_ATTACH_FS
4803 VolState state_save;
4805 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4810 DFlushVolume(vp->hashid);
4812 #ifdef AFS_DEMAND_ATTACH_FS
4816 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4818 #ifdef AFS_DEMAND_ATTACH_FS
4822 /* Too time consuming and unnecessary for the volserver */
4823 if (programType == fileServer) {
4824 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4825 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4826 IH_CONDSYNC(vp->diskDataHandle);
4828 IH_CONDSYNC(vp->linkHandle);
4829 #endif /* AFS_NT40_ENV */
4832 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4833 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4834 IH_RELEASE(vp->diskDataHandle);
4835 IH_RELEASE(vp->linkHandle);
4837 #ifdef AFS_DEMAND_ATTACH_FS
4838 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4843 VChangeState_r(vp, state_save);
4848 /***************************************************/
4849 /* Volume write and fsync routines */
4850 /***************************************************/
4853 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4855 #ifdef AFS_DEMAND_ATTACH_FS
4856 VolState state_save;
4858 if (flags & VOL_UPDATE_WAIT) {
4859 VCreateReservation_r(vp);
4860 VWaitExclusiveState_r(vp);
4865 if (programType == fileServer)
4867 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4868 200 : V_nextVnodeUnique(vp));
4870 #ifdef AFS_DEMAND_ATTACH_FS
4871 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4875 WriteVolumeHeader_r(ec, vp);
4877 #ifdef AFS_DEMAND_ATTACH_FS
4879 VChangeState_r(vp, state_save);
4880 if (flags & VOL_UPDATE_WAIT) {
4881 VCancelReservation_r(vp);
4886 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4887 V_id(vp), V_name(vp));
4888 /* try to update on-disk header,
4889 * while preventing infinite recursion */
4890 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4891 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4897 VUpdateVolume(Error * ec, Volume * vp)
4900 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4905 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4909 #ifdef AFS_DEMAND_ATTACH_FS
4910 VolState state_save;
4913 if (flags & VOL_SYNC_WAIT) {
4914 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4916 VUpdateVolume_r(ec, vp, 0);
4919 #ifdef AFS_DEMAND_ATTACH_FS
4920 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4923 fdP = IH_OPEN(V_diskDataHandle(vp));
4924 osi_Assert(fdP != NULL);
4925 code = FDH_SYNC(fdP);
4926 osi_Assert(code == 0);
4928 #ifdef AFS_DEMAND_ATTACH_FS
4930 VChangeState_r(vp, state_save);
4936 VSyncVolume(Error * ec, Volume * vp)
4939 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4944 /***************************************************/
4945 /* Volume dealloaction routines */
4946 /***************************************************/
4948 #ifdef AFS_DEMAND_ATTACH_FS
4950 FreeVolume(Volume * vp)
4952 /* free the heap space, iff it's safe.
4953 * otherwise, pull it out of the hash table, so it
4954 * will get deallocated when all refs to it go away */
4955 if (!VCheckFree(vp)) {
4956 DeleteVolumeFromHashTable(vp);
4957 DeleteVolumeFromVByPList_r(vp);
4959 /* make sure we invalidate the header cache entry */
4960 FreeVolumeHeader(vp);
4963 #endif /* AFS_DEMAND_ATTACH_FS */
4966 ReallyFreeVolume(Volume * vp)
4971 #ifdef AFS_DEMAND_ATTACH_FS
4973 VChangeState_r(vp, VOL_STATE_FREED);
4974 if (vp->pending_vol_op)
4975 free(vp->pending_vol_op);
4976 #endif /* AFS_DEMAND_ATTACH_FS */
4977 for (i = 0; i < nVNODECLASSES; i++)
4978 if (vp->vnodeIndex[i].bitmap)
4979 free(vp->vnodeIndex[i].bitmap);
4980 FreeVolumeHeader(vp);
4981 #ifndef AFS_DEMAND_ATTACH_FS
4982 DeleteVolumeFromHashTable(vp);
4983 #endif /* AFS_DEMAND_ATTACH_FS */
4987 /* check to see if we should shutdown this volume
4988 * returns 1 if volume was freed, 0 otherwise */
4989 #ifdef AFS_DEMAND_ATTACH_FS
4991 VCheckDetach(Volume * vp)
4996 if (vp->nUsers || vp->nWaiters)
4999 if (vp->shuttingDown) {
5001 if ((programType != fileServer) &&
5002 (V_inUse(vp) == programType) &&
5003 ((V_checkoutMode(vp) == V_VOLUPD) ||
5004 (V_checkoutMode(vp) == V_SECRETLY) ||
5005 ((V_checkoutMode(vp) == V_CLONE) &&
5006 (VolumeWriteable(vp))))) {
5008 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5010 Log("VCheckDetach: volume header update for volume %u "
5011 "failed with errno %d\n", vp->hashid, errno);
5014 VReleaseVolumeHandles_r(vp);
5016 ReallyFreeVolume(vp);
5017 if (programType == fileServer) {
5018 CV_BROADCAST(&vol_put_volume_cond);
5023 #else /* AFS_DEMAND_ATTACH_FS */
5025 VCheckDetach(Volume * vp)
5033 if (vp->shuttingDown) {
5035 if ((programType != fileServer) &&
5036 (V_inUse(vp) == programType) &&
5037 ((V_checkoutMode(vp) == V_VOLUPD) ||
5038 (V_checkoutMode(vp) == V_SECRETLY) ||
5039 ((V_checkoutMode(vp) == V_CLONE) &&
5040 (VolumeWriteable(vp))))) {
5042 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5044 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5048 VReleaseVolumeHandles_r(vp);
5049 ReallyFreeVolume(vp);
5050 if (programType == fileServer) {
5051 #if defined(AFS_PTHREAD_ENV)
5052 CV_BROADCAST(&vol_put_volume_cond);
5053 #else /* AFS_PTHREAD_ENV */
5054 LWP_NoYieldSignal(VPutVolume);
5055 #endif /* AFS_PTHREAD_ENV */
5060 #endif /* AFS_DEMAND_ATTACH_FS */
5062 /* check to see if we should offline this volume
5063 * return 1 if volume went offline, 0 otherwise */
5064 #ifdef AFS_DEMAND_ATTACH_FS
5066 VCheckOffline(Volume * vp)
5070 if (vp->goingOffline && !vp->nUsers) {
5072 osi_Assert(programType == fileServer);
5073 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5074 (V_attachState(vp) != VOL_STATE_FREED) &&
5075 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5076 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5077 (V_attachState(vp) != VOL_STATE_DELETED));
5081 * VOL_STATE_GOING_OFFLINE
5082 * VOL_STATE_SHUTTING_DOWN
5083 * VIsErrorState(V_attachState(vp))
5084 * VIsExclusiveState(V_attachState(vp))
5087 VCreateReservation_r(vp);
5088 VChangeState_r(vp, VOL_STATE_OFFLINING);
5091 /* must clear the goingOffline flag before we drop the glock */
5092 vp->goingOffline = 0;
5097 /* perform async operations */
5098 VUpdateVolume_r(&error, vp, 0);
5099 VCloseVolumeHandles_r(vp);
5102 if (V_offlineMessage(vp)[0]) {
5103 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5104 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5105 V_offlineMessage(vp));
5107 Log("VOffline: Volume %lu (%s) is now offline\n",
5108 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5112 /* invalidate the volume header cache entry */
5113 FreeVolumeHeader(vp);
5115 /* if nothing changed state to error or salvaging,
5116 * drop state to unattached */
5117 if (!VIsErrorState(V_attachState(vp))) {
5118 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5120 VCancelReservation_r(vp);
5121 /* no usage of vp is safe beyond this point */
5125 #else /* AFS_DEMAND_ATTACH_FS */
5127 VCheckOffline(Volume * vp)
5131 if (vp->goingOffline && !vp->nUsers) {
5133 osi_Assert(programType == fileServer);
5136 vp->goingOffline = 0;
5138 VUpdateVolume_r(&error, vp, 0);
5139 VCloseVolumeHandles_r(vp);
5141 if (V_offlineMessage(vp)[0]) {
5142 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5143 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5144 V_offlineMessage(vp));
5146 Log("VOffline: Volume %lu (%s) is now offline\n",
5147 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5150 FreeVolumeHeader(vp);
5151 #ifdef AFS_PTHREAD_ENV
5152 CV_BROADCAST(&vol_put_volume_cond);
5153 #else /* AFS_PTHREAD_ENV */
5154 LWP_NoYieldSignal(VPutVolume);
5155 #endif /* AFS_PTHREAD_ENV */
5159 #endif /* AFS_DEMAND_ATTACH_FS */
5161 /***************************************************/
5162 /* demand attach fs ref counting routines */
5163 /***************************************************/
5165 #ifdef AFS_DEMAND_ATTACH_FS
5166 /* the following two functions handle reference counting for
5167 * asynchronous operations on volume structs.
5169 * their purpose is to prevent a VDetachVolume or VShutdown
5170 * from free()ing the Volume struct during an async i/o op */
5172 /* register with the async volume op ref counter */
5173 /* VCreateReservation_r moved into inline code header because it
5174 * is now needed in vnode.c -- tkeiser 11/20/2007
5178 * decrement volume-package internal refcount.
5180 * @param vp volume object pointer
5182 * @internal volume package internal use only
5185 * @arg VOL_LOCK is held
5186 * @arg lightweight refcount held
5188 * @post volume waiters refcount is decremented; volume may
5189 * have been deallocated/shutdown/offlined/salvaged/
5190 * whatever during the process
5192 * @warning once you have tossed your last reference (you can acquire
5193 * lightweight refs recursively) it is NOT SAFE to reference
5194 * a volume object pointer ever again
5196 * @see VCreateReservation_r
5198 * @note DEMAND_ATTACH_FS only
5201 VCancelReservation_r(Volume * vp)
5203 osi_Assert(--vp->nWaiters >= 0);
5204 if (vp->nWaiters == 0) {
5206 if (!VCheckDetach(vp)) {
5213 /* check to see if we should free this volume now
5214 * return 1 if volume was freed, 0 otherwise */
5216 VCheckFree(Volume * vp)
5219 if ((vp->nUsers == 0) &&
5220 (vp->nWaiters == 0) &&
5221 !(V_attachFlags(vp) & (VOL_IN_HASH |
5225 ReallyFreeVolume(vp);
5230 #endif /* AFS_DEMAND_ATTACH_FS */
5233 /***************************************************/
5234 /* online volume operations routines */
5235 /***************************************************/
5237 #ifdef AFS_DEMAND_ATTACH_FS
5239 * register a volume operation on a given volume.
5241 * @param[in] vp volume object
5242 * @param[in] vopinfo volume operation info object
5244 * @pre VOL_LOCK is held
5246 * @post volume operation info object attached to volume object.
5247 * volume operation statistics updated.
5249 * @note by "attached" we mean a copy of the passed in object is made
5251 * @internal volume package internal use only
5254 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5256 FSSYNC_VolOp_info * info;
5258 /* attach a vol op info node to the volume struct */
5259 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5260 osi_Assert(info != NULL);
5261 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5262 vp->pending_vol_op = info;
5265 vp->stats.last_vol_op = FT_ApproxTime();
5266 vp->stats.vol_ops++;
5267 IncUInt64(&VStats.vol_ops);
5273 * deregister the volume operation attached to this volume.
5275 * @param[in] vp volume object pointer
5277 * @pre VOL_LOCK is held
5279 * @post the volume operation info object is detached from the volume object
5281 * @internal volume package internal use only
5284 VDeregisterVolOp_r(Volume * vp)
5286 if (vp->pending_vol_op) {
5287 free(vp->pending_vol_op);
5288 vp->pending_vol_op = NULL;
5292 #endif /* AFS_DEMAND_ATTACH_FS */
5295 * determine whether it is safe to leave a volume online during
5296 * the volume operation described by the vopinfo object.
5298 * @param[in] vp volume object
5299 * @param[in] vopinfo volume operation info object
5301 * @return whether it is safe to leave volume online
5302 * @retval 0 it is NOT SAFE to leave the volume online
5303 * @retval 1 it is safe to leave the volume online during the operation
5306 * @arg VOL_LOCK is held
5307 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5308 * this condition is met)
5310 * @internal volume package internal use only
5313 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5315 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5316 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5317 (vopinfo->com.reason == V_READONLY ||
5318 (!VolumeWriteable(vp) &&
5319 (vopinfo->com.reason == V_CLONE ||
5320 vopinfo->com.reason == V_DUMP)))));
5324 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5327 * @param[in] vp volume object
5328 * @param[in] vopinfo volume operation info object
5330 * @return whether it is safe to leave volume online
5331 * @retval 0 it is NOT SAFE to leave the volume online
5332 * @retval 1 it is safe to leave the volume online during the operation
5333 * @retval -1 unsure; volume header is required in order to know whether or
5334 * not is is safe to leave the volume online
5336 * @pre VOL_LOCK is held
5338 * @internal volume package internal use only
5341 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5343 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5344 * assume that we don't know VolumeWriteable; return -1 if the answer
5345 * depends on VolumeWriteable */
5347 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5350 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5351 vopinfo->com.reason == V_READONLY) {
5355 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5356 (vopinfo->com.reason == V_CLONE ||
5357 vopinfo->com.reason == V_DUMP)) {
5359 /* must know VolumeWriteable */
5366 * determine whether VBUSY should be set during this volume operation.
5368 * @param[in] vp volume object
5369 * @param[in] vopinfo volume operation info object
5371 * @return whether VBUSY should be set
5372 * @retval 0 VBUSY does NOT need to be set
5373 * @retval 1 VBUSY SHOULD be set
5375 * @pre VOL_LOCK is held
5377 * @internal volume package internal use only
5380 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5382 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5383 vopinfo->com.reason == FSYNC_SALVAGE) ||
5384 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5385 (vopinfo->com.reason == V_CLONE ||
5386 vopinfo->com.reason == V_DUMP)));
5390 /***************************************************/
5391 /* online salvager routines */
5392 /***************************************************/
5393 #if defined(AFS_DEMAND_ATTACH_FS)
5396 * offline a volume to let it be salvaged.
5398 * @param[in] vp Volume to offline
5400 * @return whether we offlined the volume successfully
5401 * @retval 0 volume was not offlined
5402 * @retval 1 volume is now offline
5404 * @note This is similar to VCheckOffline, but slightly different. We do not
5405 * deal with vp->goingOffline, and we try to avoid touching the volume
5406 * header except just to set needsSalvaged
5408 * @pre VOL_LOCK held
5409 * @pre vp->nUsers == 0
5410 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5413 VOfflineForSalvage_r(struct Volume *vp)
5417 VCreateReservation_r(vp);
5418 VWaitExclusiveState_r(vp);
5420 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5421 /* Someone's using the volume, or someone got to scheduling the salvage
5422 * before us. I don't think either of these should be possible, as we
5423 * should gain no new heavyweight references while we're trying to
5424 * salvage, but just to be sure... */
5425 VCancelReservation_r(vp);
5429 VChangeState_r(vp, VOL_STATE_OFFLINING);
5433 V_needsSalvaged(vp) = 1;
5434 /* ignore error; updating needsSalvaged is just best effort */
5435 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5437 VCloseVolumeHandles_r(vp);
5439 FreeVolumeHeader(vp);
5441 /* volume has been effectively offlined; we can mark it in the SALVAGING
5442 * state now, which lets FSSYNC give it away */
5443 VChangeState_r(vp, VOL_STATE_SALVAGING);
5445 VCancelReservation_r(vp);
5451 * check whether a salvage needs to be performed on this volume.
5453 * @param[in] vp pointer to volume object
5455 * @return status code
5456 * @retval 0 no salvage scheduled
5457 * @retval 1 a salvage has been scheduled with the salvageserver
5459 * @pre VOL_LOCK is held
5461 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5462 * then a salvage will be requested
5464 * @note this is one of the event handlers called by VCancelReservation_r
5466 * @note the caller must check if the volume needs to be freed after calling
5467 * this; the volume may not have any references or be on any lists after
5468 * we return, and we do not free it
5470 * @see VCancelReservation_r
5472 * @internal volume package internal use only.
5475 VCheckSalvage(Volume * vp)
5478 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5481 if (!vp->salvage.requested) {
5485 /* prevent recursion; some of the code below creates and removes
5486 * lightweight refs, which can call VCheckSalvage */
5487 if (vp->salvage.scheduling) {
5490 vp->salvage.scheduling = 1;
5492 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5493 if (!VOfflineForSalvage_r(vp)) {
5494 vp->salvage.scheduling = 0;
5499 if (vp->salvage.requested) {
5500 VScheduleSalvage_r(vp);
5503 vp->salvage.scheduling = 0;
5504 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5509 * request volume salvage.
5511 * @param[out] ec computed client error code
5512 * @param[in] vp volume object pointer
5513 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5514 * @param[in] flags see flags note below
5517 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5518 * not been fully attached
5520 * @pre VOL_LOCK is held.
5522 * @post volume state is changed.
5523 * for fileserver, salvage will be requested once refcount reaches zero.
5525 * @return operation status code
5526 * @retval 0 volume salvage will occur
5527 * @retval 1 volume salvage could not be scheduled
5531 * @note in the fileserver, this call does not synchronously schedule a volume
5532 * salvage. rather, it sets volume state so that when volume refcounts
5533 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5534 * nUsers and nWaiters must be zero.
5536 * @internal volume package internal use only.
5539 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5543 * for DAFS volume utilities that are not supposed to schedule salvages,
5544 * just transition to error state instead
5546 if (!VCanScheduleSalvage()) {
5547 VChangeState_r(vp, VOL_STATE_ERROR);
5552 if (programType != fileServer && !VCanUseFSSYNC()) {
5553 VChangeState_r(vp, VOL_STATE_ERROR);
5558 if (!vp->salvage.requested) {
5559 vp->salvage.requested = 1;
5560 vp->salvage.reason = reason;
5561 vp->stats.last_salvage = FT_ApproxTime();
5563 /* Note that it is not possible for us to reach this point if a
5564 * salvage is already running on this volume (even if the fileserver
5565 * was restarted during the salvage). If a salvage were running, the
5566 * salvager would have write-locked the volume header file, so when
5567 * we tried to lock the volume header, the lock would have failed,
5568 * and we would have failed during attachment prior to calling
5569 * VRequestSalvage. So we know that we can schedule salvages without
5570 * fear of a salvage already running for this volume. */
5572 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5574 /* if we don't need to offline the volume, we can go directly
5575 * to SALVAGING. SALVAGING says the volume is offline and is
5576 * either salvaging or ready to be handed to the salvager.
5577 * SALVAGE_REQ says that we want to salvage the volume, but we
5578 * are waiting for it to go offline first. */
5579 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5580 VChangeState_r(vp, VOL_STATE_SALVAGING);
5582 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5583 if (vp->nUsers == 0) {
5584 /* normally VOfflineForSalvage_r would be called from
5585 * PutVolume et al when nUsers reaches 0, but if
5586 * it's already 0, just do it ourselves, since PutVolume
5587 * isn't going to get called */
5588 VOfflineForSalvage_r(vp);
5591 /* If we are non-fileserver, we're telling the fileserver to
5592 * salvage the vol, so we don't need to give it back separately. */
5593 vp->needsPutBack = 0;
5597 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5599 /* make sure neither VScheduleSalvage_r nor
5600 * VUpdateSalvagePriority_r try to schedule another salvage */
5601 vp->salvage.requested = vp->salvage.scheduled = 0;
5603 VChangeState_r(vp, VOL_STATE_ERROR);
5612 * update salvageserver scheduling priority for a volume.
5614 * @param[in] vp pointer to volume object
5616 * @return operation status
5618 * @retval 1 request denied, or SALVSYNC communications failure
5620 * @pre VOL_LOCK is held.
5622 * @post in-core salvage priority counter is incremented. if at least
5623 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5624 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5625 * to update its priority queue. if no salvage is scheduled,
5626 * this function is a no-op.
5628 * @note DAFS fileserver only
5630 * @note this should be called whenever a VGetVolume fails due to a
5631 * pending salvage request
5633 * @todo should set exclusive state and drop glock around salvsync call
5635 * @internal volume package internal use only.
5638 VUpdateSalvagePriority_r(Volume * vp)
5642 #ifdef SALVSYNC_BUILD_CLIENT
5647 now = FT_ApproxTime();
5649 /* update the salvageserver priority queue occasionally so that
5650 * frequently requested volumes get moved to the head of the queue
5652 if ((vp->salvage.scheduled) &&
5653 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5654 code = SALVSYNC_SalvageVolume(vp->hashid,
5655 VPartitionPath(vp->partition),
5660 vp->stats.last_salvage_req = now;
5661 if (code != SYNC_OK) {
5665 #endif /* SALVSYNC_BUILD_CLIENT */
5670 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5672 /* A couple of little helper functions. These return true if we tried to
5673 * use this mechanism to schedule a salvage, false if we haven't tried.
5674 * If we did try a salvage then the results are contained in code.
5678 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5679 #ifdef SALVSYNC_BUILD_CLIENT
5680 if (VCanUseSALVSYNC()) {
5681 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5682 afs_printable_uint32_lu(vp->hashid), partName);
5684 /* can't use V_id() since there's no guarantee
5685 * we have the disk data header at this point */
5686 *code = SALVSYNC_SalvageVolume(vp->hashid,
5699 try_FSSYNC(Volume *vp, char *partName, int *code) {
5700 #ifdef FSSYNC_BUILD_CLIENT
5701 if (VCanUseFSSYNC()) {
5702 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5703 afs_printable_uint32_lu(vp->hashid), partName);
5706 * If we aren't the fileserver, tell the fileserver the volume
5707 * needs to be salvaged. We could directly tell the
5708 * salvageserver, but the fileserver keeps track of some stats
5709 * related to salvages, and handles some other salvage-related
5710 * complications for us.
5712 *code = FSYNC_VolOp(vp->hashid, partName,
5713 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5716 #endif /* FSSYNC_BUILD_CLIENT */
5721 * schedule a salvage with the salvage server or fileserver.
5723 * @param[in] vp pointer to volume object
5725 * @return operation status
5726 * @retval 0 salvage scheduled successfully
5727 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5730 * @arg VOL_LOCK is held.
5731 * @arg nUsers and nWaiters should be zero.
5733 * @post salvageserver or fileserver is sent a salvage request
5735 * @note If we are the fileserver, the request will be sent to the salvage
5736 * server over SALVSYNC. If we are not the fileserver, the request will be
5737 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5739 * @note the caller must check if the volume needs to be freed after calling
5740 * this; the volume may not have any references or be on any lists after
5741 * we return, and we do not free it
5745 * @internal volume package internal use only.
5748 VScheduleSalvage_r(Volume * vp)
5752 VolState state_save;
5753 VThreadOptions_t * thread_opts;
5756 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5758 if (vp->nWaiters || vp->nUsers) {
5762 /* prevent endless salvage,attach,salvage,attach,... loops */
5763 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5767 * don't perform salvsync ops on certain threads
5769 thread_opts = pthread_getspecific(VThread_key);
5770 if (thread_opts == NULL) {
5771 thread_opts = &VThread_defaults;
5773 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5777 if (vp->salvage.scheduled) {
5781 VCreateReservation_r(vp);
5782 VWaitExclusiveState_r(vp);
5785 * XXX the scheduling process should really be done asynchronously
5786 * to avoid fssync deadlocks
5788 if (!vp->salvage.scheduled) {
5789 /* if we haven't previously scheduled a salvage, do so now
5791 * set the volume to an exclusive state and drop the lock
5792 * around the SALVSYNC call
5794 strlcpy(partName, vp->partition->name, sizeof(partName));
5795 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5798 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5799 try_FSSYNC(vp, partName, &code));
5802 VChangeState_r(vp, state_save);
5804 if (code == SYNC_OK) {
5805 vp->salvage.scheduled = 1;
5806 vp->stats.last_salvage_req = FT_ApproxTime();
5807 if (VCanUseSALVSYNC()) {
5808 /* don't record these stats for non-fileservers; let the
5809 * fileserver take care of these */
5810 vp->stats.salvages++;
5811 IncUInt64(&VStats.salvages);
5816 case SYNC_BAD_COMMAND:
5817 case SYNC_COM_ERROR:
5820 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5821 "denied\n", afs_printable_uint32_lu(vp->hashid));
5824 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5825 "failed\n", afs_printable_uint32_lu(vp->hashid));
5828 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5829 "received unknown protocol error %d\n",
5830 afs_printable_uint32_lu(vp->hashid), code);
5834 if (VCanUseFSSYNC()) {
5835 VChangeState_r(vp, VOL_STATE_ERROR);
5840 /* NB: this is cancelling the reservation we obtained above, but we do
5841 * not call VCancelReservation_r, since that may trigger the vp dtor,
5842 * possibly free'ing the vp. We need to keep the vp around after
5843 * this, as the caller may reference vp without any refs. Instead, it
5844 * is the duty of the caller to inspect 'vp' after we return to see if
5845 * needs to be freed. */
5846 osi_Assert(--vp->nWaiters >= 0);
5849 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5851 #ifdef SALVSYNC_BUILD_CLIENT
5854 * connect to the salvageserver SYNC service.
5856 * @return operation status
5860 * @post connection to salvageserver SYNC service established
5862 * @see VConnectSALV_r
5863 * @see VDisconnectSALV
5864 * @see VReconnectSALV
5871 retVal = VConnectSALV_r();
5877 * connect to the salvageserver SYNC service.
5879 * @return operation status
5883 * @pre VOL_LOCK is held.
5885 * @post connection to salvageserver SYNC service established
5888 * @see VDisconnectSALV_r
5889 * @see VReconnectSALV_r
5890 * @see SALVSYNC_clientInit
5892 * @internal volume package internal use only.
5895 VConnectSALV_r(void)
5897 return SALVSYNC_clientInit();
5901 * disconnect from the salvageserver SYNC service.
5903 * @return operation status
5906 * @pre client should have a live connection to the salvageserver
5908 * @post connection to salvageserver SYNC service destroyed
5910 * @see VDisconnectSALV_r
5912 * @see VReconnectSALV
5915 VDisconnectSALV(void)
5918 VDisconnectSALV_r();
5924 * disconnect from the salvageserver SYNC service.
5926 * @return operation status
5930 * @arg VOL_LOCK is held.
5931 * @arg client should have a live connection to the salvageserver.
5933 * @post connection to salvageserver SYNC service destroyed
5935 * @see VDisconnectSALV
5936 * @see VConnectSALV_r
5937 * @see VReconnectSALV_r
5938 * @see SALVSYNC_clientFinis
5940 * @internal volume package internal use only.
5943 VDisconnectSALV_r(void)
5945 return SALVSYNC_clientFinis();
5949 * disconnect and then re-connect to the salvageserver SYNC service.
5951 * @return operation status
5955 * @pre client should have a live connection to the salvageserver
5957 * @post old connection is dropped, and a new one is established
5960 * @see VDisconnectSALV
5961 * @see VReconnectSALV_r
5964 VReconnectSALV(void)
5968 retVal = VReconnectSALV_r();
5974 * disconnect and then re-connect to the salvageserver SYNC service.
5976 * @return operation status
5981 * @arg VOL_LOCK is held.
5982 * @arg client should have a live connection to the salvageserver.
5984 * @post old connection is dropped, and a new one is established
5986 * @see VConnectSALV_r
5987 * @see VDisconnectSALV
5988 * @see VReconnectSALV
5989 * @see SALVSYNC_clientReconnect
5991 * @internal volume package internal use only.
5994 VReconnectSALV_r(void)
5996 return SALVSYNC_clientReconnect();
5998 #endif /* SALVSYNC_BUILD_CLIENT */
5999 #endif /* AFS_DEMAND_ATTACH_FS */
6002 /***************************************************/
6003 /* FSSYNC routines */
6004 /***************************************************/
6006 /* This must be called by any volume utility which needs to run while the
6007 file server is also running. This is separated from VInitVolumePackage2 so
6008 that a utility can fork--and each of the children can independently
6009 initialize communication with the file server */
6010 #ifdef FSSYNC_BUILD_CLIENT
6012 * connect to the fileserver SYNC service.
6014 * @return operation status
6019 * @arg VInit must equal 2.
6020 * @arg Program Type must not be fileserver or salvager.
6022 * @post connection to fileserver SYNC service established
6025 * @see VDisconnectFS
6026 * @see VChildProcReconnectFS
6033 retVal = VConnectFS_r();
6039 * connect to the fileserver SYNC service.
6041 * @return operation status
6046 * @arg VInit must equal 2.
6047 * @arg Program Type must not be fileserver or salvager.
6048 * @arg VOL_LOCK is held.
6050 * @post connection to fileserver SYNC service established
6053 * @see VDisconnectFS_r
6054 * @see VChildProcReconnectFS_r
6056 * @internal volume package internal use only.
6062 osi_Assert((VInit == 2) &&
6063 (programType != fileServer) &&
6064 (programType != salvager));
6065 rc = FSYNC_clientInit();
6073 * disconnect from the fileserver SYNC service.
6076 * @arg client should have a live connection to the fileserver.
6077 * @arg VOL_LOCK is held.
6078 * @arg Program Type must not be fileserver or salvager.
6080 * @post connection to fileserver SYNC service destroyed
6082 * @see VDisconnectFS
6084 * @see VChildProcReconnectFS_r
6086 * @internal volume package internal use only.
6089 VDisconnectFS_r(void)
6091 osi_Assert((programType != fileServer) &&
6092 (programType != salvager));
6093 FSYNC_clientFinis();
6098 * disconnect from the fileserver SYNC service.
6101 * @arg client should have a live connection to the fileserver.
6102 * @arg Program Type must not be fileserver or salvager.
6104 * @post connection to fileserver SYNC service destroyed
6106 * @see VDisconnectFS_r
6108 * @see VChildProcReconnectFS
6119 * connect to the fileserver SYNC service from a child process following a fork.
6121 * @return operation status
6126 * @arg VOL_LOCK is held.
6127 * @arg current FSYNC handle is shared with a parent process
6129 * @post current FSYNC handle is discarded and a new connection to the
6130 * fileserver SYNC service is established
6132 * @see VChildProcReconnectFS
6134 * @see VDisconnectFS_r
6136 * @internal volume package internal use only.
6139 VChildProcReconnectFS_r(void)
6141 return FSYNC_clientChildProcReconnect();
6145 * connect to the fileserver SYNC service from a child process following a fork.
6147 * @return operation status
6151 * @pre current FSYNC handle is shared with a parent process
6153 * @post current FSYNC handle is discarded and a new connection to the
6154 * fileserver SYNC service is established
6156 * @see VChildProcReconnectFS_r
6158 * @see VDisconnectFS
6161 VChildProcReconnectFS(void)
6165 ret = VChildProcReconnectFS_r();
6169 #endif /* FSSYNC_BUILD_CLIENT */
6172 /***************************************************/
6173 /* volume bitmap routines */
6174 /***************************************************/
6177 * Grow the bitmap by the defined increment
6180 VGrowBitmap(struct vnodeIndex *index)
6184 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6185 osi_Assert(bp != NULL);
6187 bp += index->bitmapSize;
6188 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6189 index->bitmapOffset = index->bitmapSize;
6190 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6196 * allocate a vnode bitmap number for the vnode
6198 * @param[out] ec error code
6199 * @param[in] vp volume object pointer
6200 * @param[in] index vnode index number for the vnode
6201 * @param[in] flags flag values described in note
6203 * @note for DAFS, flags parameter controls locking behavior.
6204 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6205 * will create a reservation and block on any other exclusive
6206 * operations. Otherwise, this function assumes the caller
6207 * already has exclusive access to vp, and we just change the
6210 * @pre VOL_LOCK held
6212 * @return bit number allocated
6218 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6219 struct vnodeIndex *index, int flags)
6223 #ifdef AFS_DEMAND_ATTACH_FS
6224 VolState state_save;
6225 #endif /* AFS_DEMAND_ATTACH_FS */
6229 /* This test is probably redundant */
6230 if (!VolumeWriteable(vp)) {
6231 *ec = (bit32) VREADONLY;
6235 #ifdef AFS_DEMAND_ATTACH_FS
6236 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6237 VCreateReservation_r(vp);
6238 VWaitExclusiveState_r(vp);
6240 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6241 #endif /* AFS_DEMAND_ATTACH_FS */
6244 if ((programType == fileServer) && !index->bitmap) {
6246 #ifndef AFS_DEMAND_ATTACH_FS
6247 /* demand attach fs uses the volume state to avoid races.
6248 * specialStatus field is not used at all */
6250 if (vp->specialStatus == VBUSY) {
6251 if (vp->goingOffline) { /* vos dump waiting for the volume to
6252 * go offline. We probably come here
6253 * from AddNewReadableResidency */
6256 while (vp->specialStatus == VBUSY) {
6257 #ifdef AFS_PTHREAD_ENV
6261 #else /* !AFS_PTHREAD_ENV */
6263 #endif /* !AFS_PTHREAD_ENV */
6267 #endif /* !AFS_DEMAND_ATTACH_FS */
6269 if (!index->bitmap) {
6270 #ifndef AFS_DEMAND_ATTACH_FS
6271 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6272 #endif /* AFS_DEMAND_ATTACH_FS */
6273 for (i = 0; i < nVNODECLASSES; i++) {
6274 VGetBitmap_r(ec, vp, i);
6276 #ifdef AFS_DEMAND_ATTACH_FS
6277 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6278 #else /* AFS_DEMAND_ATTACH_FS */
6279 DeleteVolumeFromHashTable(vp);
6280 vp->shuttingDown = 1; /* Let who has it free it. */
6281 vp->specialStatus = 0;
6282 #endif /* AFS_DEMAND_ATTACH_FS */
6286 #ifndef AFS_DEMAND_ATTACH_FS
6288 vp->specialStatus = 0; /* Allow others to have access. */
6289 #endif /* AFS_DEMAND_ATTACH_FS */
6292 #endif /* BITMAP_LATER */
6294 #ifdef AFS_DEMAND_ATTACH_FS
6296 #endif /* AFS_DEMAND_ATTACH_FS */
6297 bp = index->bitmap + index->bitmapOffset;
6298 ep = index->bitmap + index->bitmapSize;
6300 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6302 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6305 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6307 ret = ((bp - index->bitmap) * 8 + o);
6308 #ifdef AFS_DEMAND_ATTACH_FS
6310 #endif /* AFS_DEMAND_ATTACH_FS */
6313 bp += sizeof(bit32) /* i.e. 4 */ ;
6315 /* No bit map entry--must grow bitmap */
6319 ret = index->bitmapOffset * 8;
6320 #ifdef AFS_DEMAND_ATTACH_FS
6322 #endif /* AFS_DEMAND_ATTACH_FS */
6325 #ifdef AFS_DEMAND_ATTACH_FS
6326 VChangeState_r(vp, state_save);
6327 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6328 VCancelReservation_r(vp);
6330 #endif /* AFS_DEMAND_ATTACH_FS */
6335 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6339 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6345 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6346 unsigned bitNumber, int flags)
6348 unsigned int offset;
6352 #ifdef AFS_DEMAND_ATTACH_FS
6353 if (flags & VOL_FREE_BITMAP_WAIT) {
6354 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6355 * state, so ensure we're not in an exclusive volume state when we update
6357 VCreateReservation_r(vp);
6358 VWaitExclusiveState_r(vp);
6365 #endif /* BITMAP_LATER */
6367 offset = bitNumber >> 3;
6368 if (offset >= index->bitmapSize) {
6372 if (offset < index->bitmapOffset)
6373 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6374 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6377 #ifdef AFS_DEMAND_ATTACH_FS
6378 VCancelReservation_r(vp);
6380 return; /* make the compiler happy for non-DAFS */
6384 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6388 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6392 /* this function will drop the glock internally.
6393 * for old pthread fileservers, this is safe thanks to vbusy.
6395 * for demand attach fs, caller must have already called
6396 * VCreateReservation_r and VWaitExclusiveState_r */
6398 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6400 StreamHandle_t *file;
6401 afs_sfsize_t nVnodes, size;
6402 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6403 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6404 struct VnodeDiskObject *vnode;
6405 unsigned int unique = 0;
6409 #endif /* BITMAP_LATER */
6410 #ifdef AFS_DEMAND_ATTACH_FS
6411 VolState state_save;
6412 #endif /* AFS_DEMAND_ATTACH_FS */
6416 #ifdef AFS_DEMAND_ATTACH_FS
6417 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6418 #endif /* AFS_DEMAND_ATTACH_FS */
6421 fdP = IH_OPEN(vip->handle);
6422 osi_Assert(fdP != NULL);
6423 file = FDH_FDOPEN(fdP, "r");
6424 osi_Assert(file != NULL);
6425 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6426 osi_Assert(vnode != NULL);
6427 size = OS_SIZE(fdP->fd_fd);
6428 osi_Assert(size != -1);
6429 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6431 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6432 * a few files can be created in this volume,
6433 * the whole thing is rounded up to nearest 4
6434 * bytes, because the bit map allocator likes
6437 BitMap = (byte *) calloc(1, vip->bitmapSize);
6438 osi_Assert(BitMap != NULL);
6439 #else /* BITMAP_LATER */
6440 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6441 osi_Assert(vip->bitmap != NULL);
6442 vip->bitmapOffset = 0;
6443 #endif /* BITMAP_LATER */
6444 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6446 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6447 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6449 if (vnode->type != vNull) {
6450 if (vnode->vnodeMagic != vcp->magic) {
6451 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6456 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6457 #else /* BITMAP_LATER */
6458 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6459 #endif /* BITMAP_LATER */
6460 if (unique <= vnode->uniquifier)
6461 unique = vnode->uniquifier + 1;
6463 #ifndef AFS_PTHREAD_ENV
6464 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6467 #endif /* !AFS_PTHREAD_ENV */
6470 if (vp->nextVnodeUnique < unique) {
6471 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6474 /* Paranoia, partly justified--I think fclose after fdopen
6475 * doesn't seem to close fd. In any event, the documentation
6476 * doesn't specify, so it's safer to close it twice.
6484 /* There may have been a racing condition with some other thread, both
6485 * creating the bitmaps for this volume. If the other thread was faster
6486 * the pointer to bitmap should already be filled and we can free ours.
6488 if (vip->bitmap == NULL) {
6489 vip->bitmap = BitMap;
6490 vip->bitmapOffset = 0;
6493 #endif /* BITMAP_LATER */
6494 #ifdef AFS_DEMAND_ATTACH_FS
6495 VChangeState_r(vp, state_save);
6496 #endif /* AFS_DEMAND_ATTACH_FS */
6500 /***************************************************/
6501 /* Volume Path and Volume Number utility routines */
6502 /***************************************************/
6505 * find the first occurrence of a volume header file and return the path.
6507 * @param[out] ec outbound error code
6508 * @param[in] volumeId volume id to find
6509 * @param[out] partitionp pointer to disk partition path string
6510 * @param[out] namep pointer to volume header file name string
6512 * @post path to first occurrence of volume header is returned in partitionp
6513 * and namep, or ec is set accordingly.
6515 * @warning this function is NOT re-entrant -- partitionp and namep point to
6516 * static data segments
6518 * @note if a volume utility inadvertently leaves behind a stale volume header
6519 * on a vice partition, it is possible for callers to get the wrong one,
6520 * depending on the order of the disk partition linked list.
6524 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6526 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6527 char path[VMAXPATHLEN];
6529 struct DiskPartition64 *dp;
6532 name[0] = OS_DIRSEPC;
6533 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6534 afs_printable_uint32_lu(volumeId));
6535 for (dp = DiskPartitionList; dp; dp = dp->next) {
6536 struct afs_stat_st status;
6537 strcpy(path, VPartitionPath(dp));
6539 if (afs_stat(path, &status) == 0) {
6540 strcpy(partition, dp->name);
6547 *partitionp = *namep = NULL;
6549 *partitionp = partition;
6555 * extract a volume number from a volume header filename string.
6557 * @param[in] name volume header filename string
6559 * @return volume number
6561 * @note the string must be of the form VFORMAT. the only permissible
6562 * deviation is a leading OS_DIRSEPC character.
6567 VolumeNumber(char *name)
6569 if (*name == OS_DIRSEPC)
6571 return strtoul(name + 1, NULL, 10);
6575 * compute the volume header filename.
6577 * @param[in] volumeId
6579 * @return volume header filename
6581 * @post volume header filename string is constructed
6583 * @warning this function is NOT re-entrant -- the returned string is
6584 * stored in a static char array. see VolumeExternalName_r
6585 * for a re-entrant equivalent.
6587 * @see VolumeExternalName_r
6589 * @deprecated due to the above re-entrancy warning, this interface should
6590 * be considered deprecated. Please use VolumeExternalName_r
6594 VolumeExternalName(VolumeId volumeId)
6596 static char name[VMAXPATHLEN];
6597 snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6602 * compute the volume header filename.
6604 * @param[in] volumeId
6605 * @param[inout] name array in which to store filename
6606 * @param[in] len length of name array
6608 * @return result code from afs_snprintf
6610 * @see VolumeExternalName
6613 * @note re-entrant equivalent of VolumeExternalName
6616 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6618 return snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6622 /***************************************************/
6623 /* Volume Usage Statistics routines */
6624 /***************************************************/
6626 #define OneDay (86400) /* 24 hours' worth of seconds */
6629 Midnight(time_t t) {
6630 struct tm local, *l;
6633 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6634 l = localtime_r(&t, &local);
6640 /* the following is strictly speaking problematic on the
6641 switching day to daylight saving time, after the switch,
6642 as tm_isdst does not match. Similarly, on the looong day when
6643 switching back the OneDay check will not do what naively expected!
6644 The effects are minor, though, and more a matter of interpreting
6646 #ifndef AFS_PTHREAD_ENV
6649 local.tm_hour = local.tm_min=local.tm_sec = 0;
6650 midnight = mktime(&local);
6651 if (midnight != (time_t) -1) return(midnight);
6653 return( (t/OneDay)*OneDay );
6657 /*------------------------------------------------------------------------
6658 * [export] VAdjustVolumeStatistics
6661 * If we've passed midnight, we need to update all the day use
6662 * statistics as well as zeroing the detailed volume statistics
6663 * (if we are implementing them).
6666 * vp : Pointer to the volume structure describing the lucky
6667 * volume being considered for update.
6673 * Nothing interesting.
6677 *------------------------------------------------------------------------*/
6680 VAdjustVolumeStatistics_r(Volume * vp)
6682 unsigned int now = FT_ApproxTime();
6684 if (now - V_dayUseDate(vp) > OneDay) {
6687 ndays = (now - V_dayUseDate(vp)) / OneDay;
6688 for (i = 6; i > ndays - 1; i--)
6689 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6690 for (i = 0; i < ndays - 1 && i < 7; i++)
6691 V_weekUse(vp)[i] = 0;
6693 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6695 V_dayUseDate(vp) = Midnight(now);
6698 * All we need to do is bzero the entire VOL_STATS_BYTES of
6699 * the detailed volume statistics area.
6701 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6704 /*It's been more than a day of collection */
6706 * Always return happily.
6709 } /*VAdjustVolumeStatistics */
6712 VAdjustVolumeStatistics(Volume * vp)
6716 retVal = VAdjustVolumeStatistics_r(vp);
6722 VBumpVolumeUsage_r(Volume * vp)
6724 unsigned int now = FT_ApproxTime();
6725 V_accessDate(vp) = now;
6726 if (now - V_dayUseDate(vp) > OneDay)
6727 VAdjustVolumeStatistics_r(vp);
6729 * Save the volume header image to disk after a threshold of bumps to dayUse,
6730 * at most every usage_rate_limit seconds.
6733 vp->usage_bumps_outstanding++;
6734 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6735 && vp->usage_bumps_next_write <= now) {
6737 vp->usage_bumps_outstanding = 0;
6738 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6739 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6744 VBumpVolumeUsage(Volume * vp)
6747 VBumpVolumeUsage_r(vp);
6752 VSetDiskUsage_r(void)
6754 #ifndef AFS_DEMAND_ATTACH_FS
6755 static int FifteenMinuteCounter = 0;
6759 /* NOTE: Don't attempt to access the partitions list until the
6760 * initialization level indicates that all volumes are attached,
6761 * which implies that all partitions are initialized. */
6762 #ifdef AFS_PTHREAD_ENV
6763 VOL_CV_WAIT(&vol_vinit_cond);
6764 #else /* AFS_PTHREAD_ENV */
6766 #endif /* AFS_PTHREAD_ENV */
6769 VResetDiskUsage_r();
6771 #ifndef AFS_DEMAND_ATTACH_FS
6772 if (++FifteenMinuteCounter == 3) {
6773 FifteenMinuteCounter = 0;
6776 #endif /* !AFS_DEMAND_ATTACH_FS */
6788 /***************************************************/
6789 /* Volume Update List routines */
6790 /***************************************************/
6792 /* The number of minutes that a volume hasn't been updated before the
6793 * "Dont salvage" flag in the volume header will be turned on */
6794 #define SALVAGE_INTERVAL (10*60)
6799 * volume update list functionality has been moved into the VLRU
6800 * the DONT_SALVAGE flag is now set during VLRU demotion
6803 #ifndef AFS_DEMAND_ATTACH_FS
6804 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6805 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6806 static int updateSize = 0; /* number of entries possible */
6807 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6808 #endif /* !AFS_DEMAND_ATTACH_FS */
6811 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6814 vp->updateTime = FT_ApproxTime();
6815 if (V_dontSalvage(vp) == 0)
6817 V_dontSalvage(vp) = 0;
6818 VSyncVolume_r(ec, vp, 0);
6819 #ifdef AFS_DEMAND_ATTACH_FS
6820 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6821 #else /* !AFS_DEMAND_ATTACH_FS */
6824 if (UpdateList == NULL) {
6825 updateSize = UPDATE_LIST_SIZE;
6826 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6828 if (nUpdatedVolumes == updateSize) {
6830 if (updateSize > 524288) {
6831 Log("warning: there is likely a bug in the volume update scanner\n");
6835 (VolumeId *) realloc(UpdateList,
6836 sizeof(VolumeId) * updateSize);
6839 osi_Assert(UpdateList != NULL);
6840 UpdateList[nUpdatedVolumes++] = V_id(vp);
6841 #endif /* !AFS_DEMAND_ATTACH_FS */
6844 #ifndef AFS_DEMAND_ATTACH_FS
6846 VScanUpdateList(void)
6851 afs_uint32 now = FT_ApproxTime();
6852 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6853 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6855 UpdateList[i - gap] = UpdateList[i];
6857 /* XXX this routine needlessly messes up the Volume LRU by
6858 * breaking the LRU temporal-locality assumptions.....
6859 * we should use a special volume header allocator here */
6860 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6863 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6864 V_dontSalvage(vp) = DONT_SALVAGE;
6865 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6873 #ifndef AFS_PTHREAD_ENV
6875 #endif /* !AFS_PTHREAD_ENV */
6877 nUpdatedVolumes -= gap;
6879 #endif /* !AFS_DEMAND_ATTACH_FS */
6882 /***************************************************/
6883 /* Volume LRU routines */
6884 /***************************************************/
6889 * with demand attach fs, we attempt to soft detach(1)
6890 * volumes which have not been accessed in a long time
6891 * in order to speed up fileserver shutdown
6893 * (1) by soft detach we mean a process very similar
6894 * to VOffline, except the final state of the
6895 * Volume will be VOL_STATE_PREATTACHED, instead
6896 * of the usual VOL_STATE_UNATTACHED
6898 #ifdef AFS_DEMAND_ATTACH_FS
6900 /* implementation is reminiscent of a generational GC
6902 * queue 0 is newly attached volumes. this queue is
6903 * sorted by attach timestamp
6905 * queue 1 is volumes that have been around a bit
6906 * longer than queue 0. this queue is sorted by
6909 * queue 2 is volumes tha have been around the longest.
6910 * this queue is unsorted
6912 * queue 3 is volumes that have been marked as
6913 * candidates for soft detachment. this queue is
6916 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6917 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6920 * definition of a VLRU queue.
6923 volatile struct rx_queue q;
6930 * main VLRU data structure.
6933 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6936 /** time interval (in seconds) between promotion passes for
6937 * each young generation queue. */
6938 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6940 /** time interval (in seconds) between soft detach candidate
6941 * scans for each generation queue.
6943 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6944 * we perform a soft detach pass. */
6945 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6947 /* scheduler state */
6948 int next_idx; /**< next queue to receive attention */
6949 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6950 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6952 int scanner_state; /**< state of scanner thread */
6953 pthread_cond_t cv; /**< state transition CV */
6956 /** global VLRU state */
6957 static struct VLRU volume_LRU;
6960 * defined states for VLRU scanner thread.
6963 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6964 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6965 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6966 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6967 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6968 } vlru_thread_state_t;
6970 /* vlru disk data header stuff */
6971 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6972 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6974 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6975 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6978 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6979 * soft detachment. */
6980 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6982 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6983 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6985 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6986 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6988 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6989 static afs_uint32 VLRU_enabled = 1;
6991 /* queue synchronization routines */
6992 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6993 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6994 static void VLRU_Wait_r(struct VLRU_q * q);
6997 * set VLRU subsystem tunable parameters.
6999 * @param[in] option tunable option to modify
7000 * @param[in] val new value for tunable parameter
7002 * @pre @c VInitVolumePackage2 has not yet been called.
7004 * @post tunable parameter is modified
7008 * @note valid option parameters are:
7009 * @arg @c VLRU_SET_THRESH
7010 * set the period of inactivity after which
7011 * volumes are eligible for soft detachment
7012 * @arg @c VLRU_SET_INTERVAL
7013 * set the time interval between calls
7014 * to the volume LRU "garbage collector"
7015 * @arg @c VLRU_SET_MAX
7016 * set the max number of volumes to deallocate
7020 VLRU_SetOptions(int option, afs_uint32 val)
7022 if (option == VLRU_SET_THRESH) {
7023 VLRU_offline_thresh = val;
7024 } else if (option == VLRU_SET_INTERVAL) {
7025 VLRU_offline_interval = val;
7026 } else if (option == VLRU_SET_MAX) {
7027 VLRU_offline_max = val;
7028 } else if (option == VLRU_SET_ENABLED) {
7031 VLRU_ComputeConstants();
7035 * compute VLRU internal timing parameters.
7037 * @post VLRU scanner thread internal timing parameters are computed
7039 * @note computes internal timing parameters based upon user-modifiable
7040 * tunable parameters.
7044 * @internal volume package internal use only.
7047 VLRU_ComputeConstants(void)
7049 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7051 /* compute the candidate scan interval */
7052 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7054 /* compute the promotion intervals */
7055 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7056 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7059 /* compute the gen 0 scan interval */
7060 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7062 /* compute the gen 0 scan interval */
7063 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7068 * initialize VLRU subsystem.
7070 * @pre this function has not yet been called
7072 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7076 * @internal volume package internal use only.
7082 pthread_attr_t attrs;
7085 if (!VLRU_enabled) {
7086 Log("VLRU: disabled\n");
7090 /* initialize each of the VLRU queues */
7091 for (i = 0; i < VLRU_QUEUES; i++) {
7092 queue_Init(&volume_LRU.q[i]);
7093 volume_LRU.q[i].len = 0;
7094 volume_LRU.q[i].busy = 0;
7095 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7098 /* setup the timing constants */
7099 VLRU_ComputeConstants();
7101 /* XXX put inside LogLevel check? */
7102 Log("VLRU: starting scanner with the following configuration parameters:\n");
7103 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7104 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7105 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7106 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7107 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7108 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7110 /* start up the VLRU scanner */
7111 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7112 if (programType == fileServer) {
7113 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7114 osi_Assert(pthread_attr_init(&attrs) == 0);
7115 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7116 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7121 * initialize the VLRU-related fields of a newly allocated volume object.
7123 * @param[in] vp pointer to volume object
7126 * @arg @c VOL_LOCK is held.
7127 * @arg volume object is not on a VLRU queue.
7129 * @post VLRU fields are initialized to indicate that volume object is not
7130 * currently registered with the VLRU subsystem
7134 * @internal volume package interal use only.
7137 VLRU_Init_Node_r(Volume * vp)
7142 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7143 vp->vlru.idx = VLRU_QUEUE_INVALID;
7147 * add a volume object to a VLRU queue.
7149 * @param[in] vp pointer to volume object
7152 * @arg @c VOL_LOCK is held.
7153 * @arg caller MUST hold a lightweight ref on @p vp.
7154 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7156 * @post the volume object is added to the appropriate VLRU queue
7158 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7159 * then the volume is added to that queue. Otherwise, the value
7160 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7161 * volume is added to the NEW generation queue.
7163 * @note @c VOL_LOCK may be dropped internally
7165 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7166 * during the add operation, and is restored to the previous
7167 * state prior to return.
7171 * @internal volume package internal use only.
7174 VLRU_Add_r(Volume * vp)
7177 VolState state_save;
7182 if (queue_IsOnQueue(&vp->vlru))
7185 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7188 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7189 idx = VLRU_QUEUE_NEW;
7192 VLRU_Wait_r(&volume_LRU.q[idx]);
7194 /* repeat check since VLRU_Wait_r may have dropped
7196 if (queue_IsNotOnQueue(&vp->vlru)) {
7198 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7199 volume_LRU.q[idx].len++;
7200 V_attachFlags(vp) |= VOL_ON_VLRU;
7201 vp->stats.last_promote = FT_ApproxTime();
7204 VChangeState_r(vp, state_save);
7208 * delete a volume object from a VLRU queue.
7210 * @param[in] vp pointer to volume object
7213 * @arg @c VOL_LOCK is held.
7214 * @arg caller MUST hold a lightweight ref on @p vp.
7215 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7217 * @post volume object is removed from the VLRU queue
7219 * @note @c VOL_LOCK may be dropped internally
7223 * @todo We should probably set volume state to something exlcusive
7224 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7226 * @internal volume package internal use only.
7229 VLRU_Delete_r(Volume * vp)
7236 if (queue_IsNotOnQueue(&vp->vlru))
7242 if (idx == VLRU_QUEUE_INVALID)
7244 VLRU_Wait_r(&volume_LRU.q[idx]);
7245 } while (idx != vp->vlru.idx);
7247 /* now remove from the VLRU and update
7248 * the appropriate counter */
7249 queue_Remove(&vp->vlru);
7250 volume_LRU.q[idx].len--;
7251 vp->vlru.idx = VLRU_QUEUE_INVALID;
7252 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7256 * tell the VLRU subsystem that a volume was just accessed.
7258 * @param[in] vp pointer to volume object
7261 * @arg @c VOL_LOCK is held
7262 * @arg caller MUST hold a lightweight ref on @p vp
7263 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7265 * @post volume VLRU access statistics are updated. If the volume was on
7266 * the VLRU soft detach candidate queue, it is moved to the NEW
7269 * @note @c VOL_LOCK may be dropped internally
7273 * @internal volume package internal use only.
7276 VLRU_UpdateAccess_r(Volume * vp)
7278 Volume * rvp = NULL;
7283 if (queue_IsNotOnQueue(&vp->vlru))
7286 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7288 /* update the access timestamp */
7289 vp->stats.last_get = FT_ApproxTime();
7292 * if the volume is on the soft detach candidate
7293 * list, we need to safely move it back to a
7294 * regular generation. this has to be done
7295 * carefully so we don't race against the scanner
7299 /* if this volume is on the soft detach candidate queue,
7300 * then grab exclusive access to the necessary queues */
7301 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7303 VCreateReservation_r(rvp);
7305 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7306 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7307 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7308 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7311 /* make sure multiple threads don't race to update */
7312 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7313 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7317 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7318 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7319 VCancelReservation_r(rvp);
7324 * switch a volume between two VLRU queues.
7326 * @param[in] vp pointer to volume object
7327 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7328 * @param[in] append controls whether the volume will be appended or
7329 * prepended to the queue. A nonzero value means it will
7330 * be appended; zero means it will be prepended.
7332 * @pre The new (and old, if applicable) queue(s) must either be owned
7333 * exclusively by the calling thread for asynchronous manipulation,
7334 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7335 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7336 * for further details of the queue asynchronous processing mechanism.
7338 * @post If the volume object was already on a VLRU queue, it is
7339 * removed from the queue. Depending on the value of the append
7340 * parameter, the volume object is either appended or prepended
7341 * to the VLRU queue referenced by the new_idx parameter.
7345 * @see VLRU_BeginExclusive_r
7346 * @see VLRU_EndExclusive_r
7349 * @internal volume package internal use only.
7352 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7354 if (queue_IsNotOnQueue(&vp->vlru))
7357 queue_Remove(&vp->vlru);
7358 volume_LRU.q[vp->vlru.idx].len--;
7360 /* put the volume back on the correct generational queue */
7362 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7364 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7367 volume_LRU.q[new_idx].len++;
7368 vp->vlru.idx = new_idx;
7372 * VLRU background thread.
7374 * The VLRU Scanner Thread is responsible for periodically scanning through
7375 * each VLRU queue looking for volumes which should be moved to another
7376 * queue, or soft detached.
7378 * @param[in] args unused thread arguments parameter
7380 * @return unused thread return value
7381 * @retval NULL always
7383 * @internal volume package internal use only.
7386 VLRU_ScannerThread(void * args)
7388 afs_uint32 now, min_delay, delay;
7389 int i, min_idx, min_op, overdue, state;
7391 /* set t=0 for promotion cycle to be
7392 * fileserver startup */
7393 now = FT_ApproxTime();
7394 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7395 volume_LRU.last_promotion[i] = now;
7398 /* don't start the scanner until VLRU_offline_thresh
7399 * plus a small delay for VInitVolumePackage2 to finish
7402 sleep(VLRU_offline_thresh + 60);
7404 /* set t=0 for scan cycle to be now */
7405 now = FT_ApproxTime();
7406 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7407 volume_LRU.last_scan[i] = now;
7411 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7412 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7415 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7416 /* check to see if we've been asked to pause */
7417 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7418 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7419 CV_BROADCAST(&volume_LRU.cv);
7421 VOL_CV_WAIT(&volume_LRU.cv);
7422 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7425 /* scheduling can happen outside the glock */
7428 /* figure out what is next on the schedule */
7430 /* figure out a potential schedule for the new generation first */
7432 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7435 if (min_delay > volume_LRU.scan_interval[0]) {
7436 /* unsigned overflow -- we're overdue to run this scan */
7441 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7443 i = VLRU_QUEUE_CANDIDATE;
7444 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7445 if (delay < min_delay) {
7449 if (delay > volume_LRU.scan_interval[i]) {
7450 /* unsigned overflow -- we're overdue to run this scan */
7457 /* if we're still not overdue for something, figure out schedules for promotions */
7458 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7459 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7460 if (delay < min_delay) {
7465 if (delay > volume_LRU.promotion_interval[i]) {
7466 /* unsigned overflow -- we're overdue to run this promotion */
7475 /* sleep as needed */
7480 /* do whatever is next */
7483 VLRU_Promote_r(min_idx);
7484 VLRU_Demote_r(min_idx+1);
7486 VLRU_Scan_r(min_idx);
7488 now = FT_ApproxTime();
7491 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7493 /* signal that scanner is down */
7494 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7495 CV_BROADCAST(&volume_LRU.cv);
7501 * promote volumes from one VLRU generation to the next.
7503 * This routine scans a VLRU generation looking for volumes which are
7504 * eligible to be promoted to the next generation. All volumes which
7505 * meet the eligibility requirement are promoted.
7507 * Promotion eligibility is based upon meeting both of the following
7510 * @arg The volume has been accessed since the last promotion:
7511 * @c (vp->stats.last_get >= vp->stats.last_promote)
7512 * @arg The last promotion occurred at least
7513 * @c volume_LRU.promotion_interval[idx] seconds ago
7515 * As a performance optimization, promotions are "globbed". In other
7516 * words, we promote arbitrarily large contiguous sublists of elements
7519 * @param[in] idx VLRU queue index to scan
7523 * @internal VLRU internal use only.
7526 VLRU_Promote_r(int idx)
7528 int len, chaining, promote;
7529 afs_uint32 now, thresh;
7530 struct rx_queue *qp, *nqp;
7531 Volume * vp, *start = NULL, *end = NULL;
7533 /* get exclusive access to two chains, and drop the glock */
7534 VLRU_Wait_r(&volume_LRU.q[idx]);
7535 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7536 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7537 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7540 thresh = volume_LRU.promotion_interval[idx];
7541 now = FT_ApproxTime();
7544 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7545 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7546 promote = (((vp->stats.last_promote + thresh) <= now) &&
7547 (vp->stats.last_get >= vp->stats.last_promote));
7555 /* promote and prepend chain */
7556 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7570 /* promote and prepend */
7571 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7575 volume_LRU.q[idx].len -= len;
7576 volume_LRU.q[idx+1].len += len;
7579 /* release exclusive access to the two chains */
7581 volume_LRU.last_promotion[idx] = now;
7582 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7583 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7586 /* run the demotions */
7588 VLRU_Demote_r(int idx)
7591 int len, chaining, demote;
7592 afs_uint32 now, thresh;
7593 struct rx_queue *qp, *nqp;
7594 Volume * vp, *start = NULL, *end = NULL;
7595 Volume ** salv_flag_vec = NULL;
7596 int salv_vec_offset = 0;
7598 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7600 /* get exclusive access to two chains, and drop the glock */
7601 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7602 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7603 VLRU_Wait_r(&volume_LRU.q[idx]);
7604 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7607 /* no big deal if this allocation fails */
7608 if (volume_LRU.q[idx].len) {
7609 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7612 now = FT_ApproxTime();
7613 thresh = volume_LRU.promotion_interval[idx-1];
7616 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7617 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7618 demote = (((vp->stats.last_promote + thresh) <= now) &&
7619 (vp->stats.last_get < (now - thresh)));
7621 /* we now do volume update list DONT_SALVAGE flag setting during
7622 * demotion passes */
7623 if (salv_flag_vec &&
7624 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7626 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7627 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7628 salv_flag_vec[salv_vec_offset++] = vp;
7629 VCreateReservation_r(vp);
7638 /* demote and append chain */
7639 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7653 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7657 volume_LRU.q[idx].len -= len;
7658 volume_LRU.q[idx-1].len += len;
7661 /* release exclusive access to the two chains */
7663 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7664 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7666 /* now go back and set the DONT_SALVAGE flags as appropriate */
7667 if (salv_flag_vec) {
7669 for (i = 0; i < salv_vec_offset; i++) {
7670 vp = salv_flag_vec[i];
7671 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7672 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7673 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7676 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7677 V_dontSalvage(vp) = DONT_SALVAGE;
7678 VUpdateVolume_r(&ec, vp, 0);
7682 VCancelReservation_r(vp);
7684 free(salv_flag_vec);
7688 /* run a pass of the VLRU GC scanner */
7690 VLRU_Scan_r(int idx)
7692 afs_uint32 now, thresh;
7693 struct rx_queue *qp, *nqp;
7697 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7699 /* gain exclusive access to the idx VLRU */
7700 VLRU_Wait_r(&volume_LRU.q[idx]);
7701 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7703 if (idx != VLRU_QUEUE_CANDIDATE) {
7704 /* gain exclusive access to the candidate VLRU */
7705 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7706 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7709 now = FT_ApproxTime();
7710 thresh = now - VLRU_offline_thresh;
7712 /* perform candidate selection and soft detaching */
7713 if (idx == VLRU_QUEUE_CANDIDATE) {
7714 /* soft detach some volumes from the candidate pool */
7718 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7719 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7720 if (i >= VLRU_offline_max) {
7723 /* check timestamp to see if it's a candidate for soft detaching */
7724 if (vp->stats.last_get <= thresh) {
7726 if (VCheckSoftDetach(vp, thresh))
7732 /* scan for volumes to become soft detach candidates */
7733 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7734 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7736 /* check timestamp to see if it's a candidate for soft detaching */
7737 if (vp->stats.last_get <= thresh) {
7738 VCheckSoftDetachCandidate(vp, thresh);
7741 if (!(i&0x7f)) { /* lock coarsening optimization */
7749 /* relinquish exclusive access to the VLRU chains */
7753 volume_LRU.last_scan[idx] = now;
7754 if (idx != VLRU_QUEUE_CANDIDATE) {
7755 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7757 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7760 /* check whether volume is safe to soft detach
7761 * caller MUST NOT hold a ref count on vp */
7763 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7767 if (vp->nUsers || vp->nWaiters)
7770 if (vp->stats.last_get <= thresh) {
7771 ret = VSoftDetachVolume_r(vp, thresh);
7777 /* check whether volume should be made a
7778 * soft detach candidate */
7780 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7783 if (vp->nUsers || vp->nWaiters)
7788 osi_Assert(idx == VLRU_QUEUE_NEW);
7790 if (vp->stats.last_get <= thresh) {
7791 /* move to candidate pool */
7792 queue_Remove(&vp->vlru);
7793 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7794 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7795 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7796 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7804 /* begin exclusive access on VLRU */
7806 VLRU_BeginExclusive_r(struct VLRU_q * q)
7808 osi_Assert(q->busy == 0);
7812 /* end exclusive access on VLRU */
7814 VLRU_EndExclusive_r(struct VLRU_q * q)
7816 osi_Assert(q->busy);
7818 CV_BROADCAST(&q->cv);
7821 /* wait for another thread to end exclusive access on VLRU */
7823 VLRU_Wait_r(struct VLRU_q * q)
7826 VOL_CV_WAIT(&q->cv);
7831 * volume soft detach
7833 * caller MUST NOT hold a ref count on vp */
7835 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7840 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7842 ts_save = vp->stats.last_get;
7843 if (ts_save > thresh)
7846 if (vp->nUsers || vp->nWaiters)
7849 if (VIsExclusiveState(V_attachState(vp))) {
7853 switch (V_attachState(vp)) {
7854 case VOL_STATE_UNATTACHED:
7855 case VOL_STATE_PREATTACHED:
7856 case VOL_STATE_ERROR:
7857 case VOL_STATE_GOING_OFFLINE:
7858 case VOL_STATE_SHUTTING_DOWN:
7859 case VOL_STATE_SALVAGING:
7860 case VOL_STATE_DELETED:
7861 volume_LRU.q[vp->vlru.idx].len--;
7863 /* create and cancel a reservation to
7864 * give the volume an opportunity to
7866 VCreateReservation_r(vp);
7867 queue_Remove(&vp->vlru);
7868 vp->vlru.idx = VLRU_QUEUE_INVALID;
7869 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7870 VCancelReservation_r(vp);
7876 /* hold the volume and take it offline.
7877 * no need for reservations, as VHold_r
7878 * takes care of that internally. */
7879 if (VHold_r(vp) == 0) {
7880 /* vhold drops the glock, so now we should
7881 * check to make sure we aren't racing against
7882 * other threads. if we are racing, offlining vp
7883 * would be wasteful, and block the scanner for a while
7887 (vp->shuttingDown) ||
7888 (vp->goingOffline) ||
7889 (vp->stats.last_get != ts_save)) {
7890 /* looks like we're racing someone else. bail */
7894 /* pull it off the VLRU */
7895 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7896 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7897 queue_Remove(&vp->vlru);
7898 vp->vlru.idx = VLRU_QUEUE_INVALID;
7899 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7901 /* take if offline */
7902 VOffline_r(vp, "volume has been soft detached");
7904 /* invalidate the volume header cache */
7905 FreeVolumeHeader(vp);
7908 IncUInt64(&VStats.soft_detaches);
7909 vp->stats.soft_detaches++;
7911 /* put in pre-attached state so demand
7912 * attacher can work on it */
7913 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7919 #endif /* AFS_DEMAND_ATTACH_FS */
7922 /***************************************************/
7923 /* Volume Header Cache routines */
7924 /***************************************************/
7927 * volume header cache.
7929 struct volume_hdr_LRU_t volume_hdr_LRU;
7932 * initialize the volume header cache.
7934 * @param[in] howMany number of header cache entries to preallocate
7936 * @pre VOL_LOCK held. Function has never been called before.
7938 * @post howMany cache entries are allocated, initialized, and added
7939 * to the LRU list. Header cache statistics are initialized.
7941 * @note only applicable to fileServer program type. Should only be
7942 * called once during volume package initialization.
7944 * @internal volume package internal use only.
7947 VInitVolumeHeaderCache(afs_uint32 howMany)
7949 struct volHeader *hp;
7950 if (programType != fileServer)
7952 queue_Init(&volume_hdr_LRU);
7953 volume_hdr_LRU.stats.free = 0;
7954 volume_hdr_LRU.stats.used = howMany;
7955 volume_hdr_LRU.stats.attached = 0;
7956 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7957 osi_Assert(hp != NULL);
7960 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7961 * to ensure they have the right values
7963 ReleaseVolumeHeader(hp++);
7966 /* get a volume header off of the volume header LRU.
7968 * @return volume header
7969 * @retval NULL no usable volume header is available on the LRU
7971 * @pre VOL_LOCK held
7973 * @post for DAFS, if the returned header is associated with a volume, that
7974 * volume is NOT in an exclusive state
7976 * @internal volume package internal use only.
7978 #ifdef AFS_DEMAND_ATTACH_FS
7979 static struct volHeader*
7980 GetVolHeaderFromLRU(void)
7982 struct volHeader *hd = NULL, *qh, *nqh;
7983 /* Usually, a volume in an exclusive state will not have its header on
7984 * the LRU. However, it is possible for this to occur when a salvage
7985 * request is received over FSSYNC, and possibly in other corner cases.
7986 * So just skip over headers whose volumes are in an exclusive state. We
7987 * could VWaitExclusiveState_r instead, but not waiting is faster and
7989 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
7990 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
7998 #else /* AFS_DEMAND_ATTACH_FS */
7999 static struct volHeader*
8000 GetVolHeaderFromLRU(void)
8002 struct volHeader *hd = NULL;
8003 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8004 hd = queue_First(&volume_hdr_LRU, volHeader);
8009 #endif /* !AFS_DEMAND_ATTACH_FS */
8012 * get a volume header and attach it to the volume object.
8014 * @param[in] vp pointer to volume object
8016 * @return cache entry status
8017 * @retval 0 volume header was newly attached; cache data is invalid
8018 * @retval 1 volume header was previously attached; cache data is valid
8020 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8022 * @post volume header attached to volume object. if necessary, header cache
8023 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8025 * @note VOL_LOCK may be dropped
8027 * @warning this interface does not load header data from disk. it merely
8028 * attaches a header object to the volume object, and may sync the old
8029 * header cache data out to disk in the process.
8031 * @internal volume package internal use only.
8034 GetVolumeHeader(Volume * vp)
8037 struct volHeader *hd;
8039 static int everLogged = 0;
8041 #ifdef AFS_DEMAND_ATTACH_FS
8042 VolState vp_save = 0, back_save = 0;
8044 /* XXX debug 9/19/05 we've apparently got
8045 * a ref counting bug somewhere that's
8046 * breaking the nUsers == 0 => header on LRU
8048 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8049 Log("nUsers == 0, but header not on LRU\n");
8054 old = (vp->header != NULL); /* old == volume already has a header */
8056 if (programType != fileServer) {
8057 /* for volume utilities, we allocate volHeaders as needed */
8059 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
8060 osi_Assert(hd != NULL);
8063 #ifdef AFS_DEMAND_ATTACH_FS
8064 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8068 /* for the fileserver, we keep a volume header cache */
8070 /* the header we previously dropped in the lru is
8071 * still available. pull it off the lru and return */
8074 osi_Assert(hd->back == vp);
8075 #ifdef AFS_DEMAND_ATTACH_FS
8076 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8079 hd = GetVolHeaderFromLRU();
8081 /* LRU is empty, so allocate a new volHeader
8082 * this is probably indicative of a leak, so let the user know */
8083 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
8084 osi_Assert(hd != NULL);
8086 Log("****Allocated more volume headers, probably leak****\n");
8089 volume_hdr_LRU.stats.free++;
8092 /* this header used to belong to someone else.
8093 * we'll need to check if the header needs to
8094 * be sync'd out to disk */
8096 #ifdef AFS_DEMAND_ATTACH_FS
8097 /* GetVolHeaderFromLRU had better not give us back a header
8098 * with a volume in exclusive state... */
8099 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8102 if (hd->diskstuff.inUse) {
8103 /* volume was in use, so we'll need to sync
8104 * its header to disk */
8106 #ifdef AFS_DEMAND_ATTACH_FS
8107 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8108 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8109 VCreateReservation_r(hd->back);
8113 WriteVolumeHeader_r(&error, hd->back);
8114 /* Ignore errors; catch them later */
8116 #ifdef AFS_DEMAND_ATTACH_FS
8121 hd->back->header = NULL;
8122 #ifdef AFS_DEMAND_ATTACH_FS
8123 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8125 if (hd->diskstuff.inUse) {
8126 VChangeState_r(hd->back, back_save);
8127 VCancelReservation_r(hd->back);
8128 VChangeState_r(vp, vp_save);
8132 volume_hdr_LRU.stats.attached++;
8136 #ifdef AFS_DEMAND_ATTACH_FS
8137 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8140 volume_hdr_LRU.stats.free--;
8141 volume_hdr_LRU.stats.used++;
8143 IncUInt64(&VStats.hdr_gets);
8144 #ifdef AFS_DEMAND_ATTACH_FS
8145 IncUInt64(&vp->stats.hdr_gets);
8146 vp->stats.last_hdr_get = FT_ApproxTime();
8153 * make sure volume header is attached and contains valid cache data.
8155 * @param[out] ec outbound error code
8156 * @param[in] vp pointer to volume object
8158 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8160 * @post header cache entry attached, and loaded with valid data, or
8161 * *ec is nonzero, and the header is released back into the LRU.
8163 * @internal volume package internal use only.
8166 LoadVolumeHeader(Error * ec, Volume * vp)
8168 #ifdef AFS_DEMAND_ATTACH_FS
8169 VolState state_save;
8173 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8174 IncUInt64(&VStats.hdr_loads);
8175 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8178 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8179 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8181 IncUInt64(&vp->stats.hdr_loads);
8182 now = FT_ApproxTime();
8186 V_attachFlags(vp) |= VOL_HDR_LOADED;
8187 vp->stats.last_hdr_load = now;
8189 VChangeState_r(vp, state_save);
8191 #else /* AFS_DEMAND_ATTACH_FS */
8193 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8194 IncUInt64(&VStats.hdr_loads);
8196 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8197 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8200 #endif /* AFS_DEMAND_ATTACH_FS */
8202 /* maintain (nUsers==0) => header in LRU invariant */
8203 FreeVolumeHeader(vp);
8208 * release a header cache entry back into the LRU list.
8210 * @param[in] hd pointer to volume header cache object
8212 * @pre VOL_LOCK held.
8214 * @post header cache object appended onto end of LRU list.
8216 * @note only applicable to fileServer program type.
8218 * @note used to place a header cache entry back into the
8219 * LRU pool without invalidating it as a cache entry.
8221 * @internal volume package internal use only.
8224 ReleaseVolumeHeader(struct volHeader *hd)
8226 if (programType != fileServer)
8228 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8230 queue_Append(&volume_hdr_LRU, hd);
8231 #ifdef AFS_DEMAND_ATTACH_FS
8233 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8236 volume_hdr_LRU.stats.free++;
8237 volume_hdr_LRU.stats.used--;
8241 * free/invalidate a volume header cache entry.
8243 * @param[in] vp pointer to volume object
8245 * @pre VOL_LOCK is held.
8247 * @post For fileserver, header cache entry is returned to LRU, and it is
8248 * invalidated as a cache entry. For volume utilities, the header
8249 * cache entry is freed.
8251 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8252 * whenever it is necessary to invalidate the header cache entry.
8254 * @see ReleaseVolumeHeader
8256 * @internal volume package internal use only.
8259 FreeVolumeHeader(Volume * vp)
8261 struct volHeader *hd = vp->header;
8264 if (programType == fileServer) {
8265 ReleaseVolumeHeader(hd);
8270 #ifdef AFS_DEMAND_ATTACH_FS
8271 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8273 volume_hdr_LRU.stats.attached--;
8278 /***************************************************/
8279 /* Volume Hash Table routines */
8280 /***************************************************/
8283 * set size of volume object hash table.
8285 * @param[in] logsize log(2) of desired hash table size
8287 * @return operation status
8289 * @retval -1 failure
8291 * @pre MUST be called prior to VInitVolumePackage2
8293 * @post Volume Hash Table will have 2^logsize buckets
8296 VSetVolHashSize(int logsize)
8298 /* 64 to 268435456 hash buckets seems like a reasonable range */
8299 if ((logsize < 6 ) || (logsize > 28)) {
8304 VolumeHashTable.Size = 1 << logsize;
8305 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8307 /* we can't yet support runtime modification of this
8308 * parameter. we'll need a configuration rwlock to
8309 * make runtime modification feasible.... */
8316 * initialize dynamic data structures for volume hash table.
8318 * @post hash table is allocated, and fields are initialized.
8320 * @internal volume package internal use only.
8323 VInitVolumeHash(void)
8327 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8328 sizeof(VolumeHashChainHead));
8329 osi_Assert(VolumeHashTable.Table != NULL);
8331 for (i=0; i < VolumeHashTable.Size; i++) {
8332 queue_Init(&VolumeHashTable.Table[i]);
8333 #ifdef AFS_DEMAND_ATTACH_FS
8334 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8335 #endif /* AFS_DEMAND_ATTACH_FS */
8340 * add a volume object to the hash table.
8342 * @param[in] vp pointer to volume object
8343 * @param[in] hashid hash of volume id
8345 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8348 * @post volume is added to hash chain.
8350 * @internal volume package internal use only.
8352 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8353 * asynchronous hash chain reordering to finish.
8356 AddVolumeToHashTable(Volume * vp, int hashid)
8358 VolumeHashChainHead * head;
8360 if (queue_IsOnQueue(vp))
8363 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8365 #ifdef AFS_DEMAND_ATTACH_FS
8366 /* wait for the hash chain to become available */
8369 V_attachFlags(vp) |= VOL_IN_HASH;
8370 vp->chainCacheCheck = ++head->cacheCheck;
8371 #endif /* AFS_DEMAND_ATTACH_FS */
8374 vp->hashid = hashid;
8375 queue_Append(head, vp);
8376 vp->vnodeHashOffset = VolumeHashOffset_r();
8380 * delete a volume object from the hash table.
8382 * @param[in] vp pointer to volume object
8384 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8387 * @post volume is removed from hash chain.
8389 * @internal volume package internal use only.
8391 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8392 * asynchronous hash chain reordering to finish.
8395 DeleteVolumeFromHashTable(Volume * vp)
8397 VolumeHashChainHead * head;
8399 if (!queue_IsOnQueue(vp))
8402 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8404 #ifdef AFS_DEMAND_ATTACH_FS
8405 /* wait for the hash chain to become available */
8408 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8410 #endif /* AFS_DEMAND_ATTACH_FS */
8414 /* do NOT reset hashid to zero, as the online
8415 * salvager package may need to know the volume id
8416 * after the volume is removed from the hash */
8420 * lookup a volume object in the hash table given a volume id.
8422 * @param[out] ec error code return
8423 * @param[in] volumeId volume id
8424 * @param[in] hint volume object which we believe could be the correct
8427 * @return volume object pointer
8428 * @retval NULL no such volume id is registered with the hash table.
8430 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8433 * @post volume object with the given id is returned. volume object and
8434 * hash chain access statistics are updated. hash chain may have
8437 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8438 * asynchronous hash chain reordering operation to finish, or
8439 * in order for us to perform an asynchronous chain reordering.
8441 * @note Hash chain reorderings occur when the access count for the
8442 * volume object being looked up exceeds the sum of the previous
8443 * node's (the node ahead of it in the hash chain linked list)
8444 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8446 * @note For DAFS, the hint parameter allows us to short-circuit if the
8447 * cacheCheck fields match between the hash chain head and the
8448 * hint volume object.
8451 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8455 #ifdef AFS_DEMAND_ATTACH_FS
8458 VolumeHashChainHead * head;
8461 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8463 #ifdef AFS_DEMAND_ATTACH_FS
8464 /* wait for the hash chain to become available */
8467 /* check to see if we can short circuit without walking the hash chain */
8468 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8469 IncUInt64(&hint->stats.hash_short_circuits);
8472 #endif /* AFS_DEMAND_ATTACH_FS */
8474 /* someday we need to either do per-chain locks, RWlocks,
8475 * or both for volhash access.
8476 * (and move to a data structure with better cache locality) */
8478 /* search the chain for this volume id */
8479 for(queue_Scan(head, vp, np, Volume)) {
8481 if (vp->hashid == volumeId) {
8486 if (queue_IsEnd(head, vp)) {
8490 #ifdef AFS_DEMAND_ATTACH_FS
8491 /* update hash chain statistics */
8494 FillInt64(lks, 0, looks);
8495 AddUInt64(head->looks, lks, &head->looks);
8496 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8497 IncUInt64(&head->gets);
8502 IncUInt64(&vp->stats.hash_lookups);
8504 /* for demand attach fileserver, we permit occasional hash chain reordering
8505 * so that frequently looked up volumes move towards the head of the chain */
8506 pp = queue_Prev(vp, Volume);
8507 if (!queue_IsEnd(head, pp)) {
8508 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8509 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8510 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8511 VReorderHash_r(head, pp, vp);
8515 /* update the short-circuit cache check */
8516 vp->chainCacheCheck = head->cacheCheck;
8518 #endif /* AFS_DEMAND_ATTACH_FS */
8523 #ifdef AFS_DEMAND_ATTACH_FS
8524 /* perform volume hash chain reordering.
8526 * advance a subchain beginning at vp ahead of
8527 * the adjacent subchain ending at pp */
8529 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8531 Volume *tp, *np, *lp;
8532 afs_uint64 move_thresh;
8534 /* this should never be called if the chain is already busy, so
8535 * no need to wait for other exclusive chain ops to finish */
8537 /* this is a rather heavy set of operations,
8538 * so let's set the chain busy flag and drop
8540 VHashBeginExclusive_r(head);
8543 /* scan forward in the chain from vp looking for the last element
8544 * in the chain we want to advance */
8545 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8546 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8547 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8548 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8552 lp = queue_Prev(tp, Volume);
8554 /* scan backwards from pp to determine where to splice and
8555 * insert the subchain we're advancing */
8556 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8557 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8561 tp = queue_Next(tp, Volume);
8563 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8564 queue_MoveChainBefore(tp,vp,lp);
8567 IncUInt64(&VStats.hash_reorders);
8569 IncUInt64(&head->reorders);
8571 /* wake up any threads waiting for the hash chain */
8572 VHashEndExclusive_r(head);
8576 /* demand-attach fs volume hash
8577 * asynchronous exclusive operations */
8580 * begin an asynchronous exclusive operation on a volume hash chain.
8582 * @param[in] head pointer to volume hash chain head object
8584 * @pre VOL_LOCK held. hash chain is quiescent.
8586 * @post hash chain marked busy.
8588 * @note this interface is used in conjunction with VHashEndExclusive_r and
8589 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8590 * volume hash chain. Its main use case is hash chain reordering, which
8591 * has the potential to be a highly latent operation.
8593 * @see VHashEndExclusive_r
8598 * @internal volume package internal use only.
8601 VHashBeginExclusive_r(VolumeHashChainHead * head)
8603 osi_Assert(head->busy == 0);
8608 * relinquish exclusive ownership of a volume hash chain.
8610 * @param[in] head pointer to volume hash chain head object
8612 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8614 * @post hash chain is marked quiescent. threads awaiting use of
8615 * chain are awakened.
8617 * @see VHashBeginExclusive_r
8622 * @internal volume package internal use only.
8625 VHashEndExclusive_r(VolumeHashChainHead * head)
8627 osi_Assert(head->busy);
8629 CV_BROADCAST(&head->chain_busy_cv);
8633 * wait for all asynchronous operations on a hash chain to complete.
8635 * @param[in] head pointer to volume hash chain head object
8637 * @pre VOL_LOCK held.
8639 * @post hash chain object is quiescent.
8641 * @see VHashBeginExclusive_r
8642 * @see VHashEndExclusive_r
8646 * @note This interface should be called before any attempt to
8647 * traverse the hash chain. It is permissible for a thread
8648 * to gain exclusive access to the chain, and then perform
8649 * latent operations on the chain asynchronously wrt the
8652 * @warning if waiting is necessary, VOL_LOCK is dropped
8654 * @internal volume package internal use only.
8657 VHashWait_r(VolumeHashChainHead * head)
8659 while (head->busy) {
8660 VOL_CV_WAIT(&head->chain_busy_cv);
8663 #endif /* AFS_DEMAND_ATTACH_FS */
8666 /***************************************************/
8667 /* Volume by Partition List routines */
8668 /***************************************************/
8671 * demand attach fileserver adds a
8672 * linked list of volumes to each
8673 * partition object, thus allowing
8674 * for quick enumeration of all
8675 * volumes on a partition
8678 #ifdef AFS_DEMAND_ATTACH_FS
8680 * add a volume to its disk partition VByPList.
8682 * @param[in] vp pointer to volume object
8684 * @pre either the disk partition VByPList is owned exclusively
8685 * by the calling thread, or the list is quiescent and
8688 * @post volume is added to disk partition VByPList
8692 * @warning it is the caller's responsibility to ensure list
8695 * @see VVByPListWait_r
8696 * @see VVByPListBeginExclusive_r
8697 * @see VVByPListEndExclusive_r
8699 * @internal volume package internal use only.
8702 AddVolumeToVByPList_r(Volume * vp)
8704 if (queue_IsNotOnQueue(&vp->vol_list)) {
8705 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8706 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8707 vp->partition->vol_list.len++;
8712 * delete a volume from its disk partition VByPList.
8714 * @param[in] vp pointer to volume object
8716 * @pre either the disk partition VByPList is owned exclusively
8717 * by the calling thread, or the list is quiescent and
8720 * @post volume is removed from the disk partition VByPList
8724 * @warning it is the caller's responsibility to ensure list
8727 * @see VVByPListWait_r
8728 * @see VVByPListBeginExclusive_r
8729 * @see VVByPListEndExclusive_r
8731 * @internal volume package internal use only.
8734 DeleteVolumeFromVByPList_r(Volume * vp)
8736 if (queue_IsOnQueue(&vp->vol_list)) {
8737 queue_Remove(&vp->vol_list);
8738 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8739 vp->partition->vol_list.len--;
8744 * begin an asynchronous exclusive operation on a VByPList.
8746 * @param[in] dp pointer to disk partition object
8748 * @pre VOL_LOCK held. VByPList is quiescent.
8750 * @post VByPList marked busy.
8752 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8753 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8756 * @see VVByPListEndExclusive_r
8757 * @see VVByPListWait_r
8761 * @internal volume package internal use only.
8763 /* take exclusive control over the list */
8765 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8767 osi_Assert(dp->vol_list.busy == 0);
8768 dp->vol_list.busy = 1;
8772 * relinquish exclusive ownership of a VByPList.
8774 * @param[in] dp pointer to disk partition object
8776 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8778 * @post VByPList is marked quiescent. threads awaiting use of
8779 * the list are awakened.
8781 * @see VVByPListBeginExclusive_r
8782 * @see VVByPListWait_r
8786 * @internal volume package internal use only.
8789 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8791 osi_Assert(dp->vol_list.busy);
8792 dp->vol_list.busy = 0;
8793 CV_BROADCAST(&dp->vol_list.cv);
8797 * wait for all asynchronous operations on a VByPList to complete.
8799 * @param[in] dp pointer to disk partition object
8801 * @pre VOL_LOCK is held.
8803 * @post disk partition's VByP list is quiescent
8807 * @note This interface should be called before any attempt to
8808 * traverse the VByPList. It is permissible for a thread
8809 * to gain exclusive access to the list, and then perform
8810 * latent operations on the list asynchronously wrt the
8813 * @warning if waiting is necessary, VOL_LOCK is dropped
8815 * @see VVByPListEndExclusive_r
8816 * @see VVByPListBeginExclusive_r
8818 * @internal volume package internal use only.
8821 VVByPListWait_r(struct DiskPartition64 * dp)
8823 while (dp->vol_list.busy) {
8824 VOL_CV_WAIT(&dp->vol_list.cv);
8827 #endif /* AFS_DEMAND_ATTACH_FS */
8829 /***************************************************/
8830 /* Volume Cache Statistics routines */
8831 /***************************************************/
8834 VPrintCacheStats_r(void)
8836 struct VnodeClassInfo *vcp;
8837 vcp = &VnodeClassInfo[vLarge];
8838 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);
8839 vcp = &VnodeClassInfo[vSmall];
8840 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);
8841 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8842 "%"AFS_INT64_FMT" replacements\n",
8843 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8847 VPrintCacheStats(void)
8850 VPrintCacheStats_r();
8854 #ifdef AFS_DEMAND_ATTACH_FS
8856 UInt64ToDouble(afs_uint64 * x)
8858 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8860 SplitInt64(*x, h, l);
8861 return (((double)h) * c32) + ((double) l);
8865 DoubleToPrintable(double x, char * buf, int len)
8867 static double billion = 1000000000.0;
8870 y[0] = (afs_uint32) (x / (billion * billion));
8871 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8872 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8875 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8877 snprintf(buf, len, "%d%09d", y[1], y[2]);
8879 snprintf(buf, len, "%d", y[2]);
8885 struct VLRUExtStatsEntry {
8889 struct VLRUExtStats {
8895 } queue_info[VLRU_QUEUE_INVALID];
8896 struct VLRUExtStatsEntry * vec;
8900 * add a 256-entry fudge factor onto the vector in case state changes
8901 * out from under us.
8903 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8906 * collect extended statistics for the VLRU subsystem.
8908 * @param[out] stats pointer to stats structure to be populated
8909 * @param[in] nvols number of volumes currently known to exist
8911 * @pre VOL_LOCK held
8913 * @post stats->vec allocated and populated
8915 * @return operation status
8920 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8922 afs_uint32 cur, idx, len;
8923 struct rx_queue * qp, * nqp;
8925 struct VLRUExtStatsEntry * vec;
8927 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8928 vec = stats->vec = calloc(len,
8929 sizeof(struct VLRUExtStatsEntry));
8935 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8936 VLRU_Wait_r(&volume_LRU.q[idx]);
8937 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8940 stats->queue_info[idx].start = cur;
8942 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8944 /* out of space in vec */
8947 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8948 vec[cur].volid = vp->hashid;
8952 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8955 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8963 #define ENUMTOSTRING(en) #en
8964 #define ENUMCASE(en) \
8965 case en: return ENUMTOSTRING(en)
8968 vlru_idx_to_string(int idx)
8971 ENUMCASE(VLRU_QUEUE_NEW);
8972 ENUMCASE(VLRU_QUEUE_MID);
8973 ENUMCASE(VLRU_QUEUE_OLD);
8974 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8975 ENUMCASE(VLRU_QUEUE_HELD);
8976 ENUMCASE(VLRU_QUEUE_INVALID);
8978 return "**UNKNOWN**";
8983 VPrintExtendedCacheStats_r(int flags)
8986 afs_uint32 vol_sum = 0;
8993 struct stats looks, gets, reorders, len;
8994 struct stats ch_looks, ch_gets, ch_reorders;
8996 VolumeHashChainHead *head;
8998 struct VLRUExtStats vlru_stats;
9000 /* zero out stats */
9001 memset(&looks, 0, sizeof(struct stats));
9002 memset(&gets, 0, sizeof(struct stats));
9003 memset(&reorders, 0, sizeof(struct stats));
9004 memset(&len, 0, sizeof(struct stats));
9005 memset(&ch_looks, 0, sizeof(struct stats));
9006 memset(&ch_gets, 0, sizeof(struct stats));
9007 memset(&ch_reorders, 0, sizeof(struct stats));
9009 for (i = 0; i < VolumeHashTable.Size; i++) {
9010 head = &VolumeHashTable.Table[i];
9013 VHashBeginExclusive_r(head);
9016 ch_looks.sum = UInt64ToDouble(&head->looks);
9017 ch_gets.sum = UInt64ToDouble(&head->gets);
9018 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9020 /* update global statistics */
9022 looks.sum += ch_looks.sum;
9023 gets.sum += ch_gets.sum;
9024 reorders.sum += ch_reorders.sum;
9025 len.sum += (double)head->len;
9026 vol_sum += head->len;
9029 len.min = (double) head->len;
9030 len.max = (double) head->len;
9031 looks.min = ch_looks.sum;
9032 looks.max = ch_looks.sum;
9033 gets.min = ch_gets.sum;
9034 gets.max = ch_gets.sum;
9035 reorders.min = ch_reorders.sum;
9036 reorders.max = ch_reorders.sum;
9038 if (((double)head->len) < len.min)
9039 len.min = (double) head->len;
9040 if (((double)head->len) > len.max)
9041 len.max = (double) head->len;
9042 if (ch_looks.sum < looks.min)
9043 looks.min = ch_looks.sum;
9044 else if (ch_looks.sum > looks.max)
9045 looks.max = ch_looks.sum;
9046 if (ch_gets.sum < gets.min)
9047 gets.min = ch_gets.sum;
9048 else if (ch_gets.sum > gets.max)
9049 gets.max = ch_gets.sum;
9050 if (ch_reorders.sum < reorders.min)
9051 reorders.min = ch_reorders.sum;
9052 else if (ch_reorders.sum > reorders.max)
9053 reorders.max = ch_reorders.sum;
9057 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9058 /* compute detailed per-chain stats */
9059 struct stats hdr_loads, hdr_gets;
9060 double v_looks, v_loads, v_gets;
9062 /* initialize stats with data from first element in chain */
9063 vp = queue_First(head, Volume);
9064 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9065 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9066 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9067 ch_gets.min = ch_gets.max = v_looks;
9068 hdr_loads.min = hdr_loads.max = v_loads;
9069 hdr_gets.min = hdr_gets.max = v_gets;
9070 hdr_loads.sum = hdr_gets.sum = 0;
9072 vp = queue_Next(vp, Volume);
9074 /* pull in stats from remaining elements in chain */
9075 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9076 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9077 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9078 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9080 hdr_loads.sum += v_loads;
9081 hdr_gets.sum += v_gets;
9083 if (v_looks < ch_gets.min)
9084 ch_gets.min = v_looks;
9085 else if (v_looks > ch_gets.max)
9086 ch_gets.max = v_looks;
9088 if (v_loads < hdr_loads.min)
9089 hdr_loads.min = v_loads;
9090 else if (v_loads > hdr_loads.max)
9091 hdr_loads.max = v_loads;
9093 if (v_gets < hdr_gets.min)
9094 hdr_gets.min = v_gets;
9095 else if (v_gets > hdr_gets.max)
9096 hdr_gets.max = v_gets;
9099 /* compute per-chain averages */
9100 ch_gets.avg = ch_gets.sum / ((double)head->len);
9101 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9102 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9104 /* dump per-chain stats */
9105 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9107 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9108 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9109 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9110 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9111 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9112 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9113 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9114 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9115 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9116 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9117 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9118 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9119 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9120 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9121 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9122 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9123 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9124 } else if (flags & VOL_STATS_PER_CHAIN) {
9125 /* dump simple per-chain stats */
9126 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9128 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9129 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9130 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9134 VHashEndExclusive_r(head);
9139 /* compute global averages */
9140 len.avg = len.sum / ((double)VolumeHashTable.Size);
9141 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9142 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9143 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9145 /* dump global stats */
9146 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9147 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9148 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9149 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9150 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9151 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9152 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9153 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9154 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9155 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9156 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9157 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9158 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9159 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9160 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9161 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9162 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9163 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9164 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9165 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9166 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9168 /* print extended disk related statistics */
9170 struct DiskPartition64 * diskP;
9171 afs_uint32 vol_count[VOLMAXPARTS+1];
9172 byte part_exists[VOLMAXPARTS+1];
9176 memset(vol_count, 0, sizeof(vol_count));
9177 memset(part_exists, 0, sizeof(part_exists));
9181 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9183 vol_count[id] = diskP->vol_list.len;
9184 part_exists[id] = 1;
9188 for (i = 0; i <= VOLMAXPARTS; i++) {
9189 if (part_exists[i]) {
9190 /* XXX while this is currently safe, it is a violation
9191 * of the VGetPartitionById_r interface contract. */
9192 diskP = VGetPartitionById_r(i, 0);
9194 Log("Partition %s has %d online volumes\n",
9195 VPartitionPath(diskP), diskP->vol_list.len);
9202 /* print extended VLRU statistics */
9203 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9204 afs_uint32 idx, cur, lpos;
9209 Log("VLRU State Dump:\n\n");
9211 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9212 Log("\t%s:\n", vlru_idx_to_string(idx));
9215 for (cur = vlru_stats.queue_info[idx].start;
9216 cur < vlru_stats.queue_info[idx].len;
9218 line[lpos++] = vlru_stats.vec[cur].volid;
9220 Log("\t\t%u, %u, %u, %u, %u,\n",
9221 line[0], line[1], line[2], line[3], line[4]);
9230 Log("\t\t%u, %u, %u, %u, %u\n",
9231 line[0], line[1], line[2], line[3], line[4]);
9236 free(vlru_stats.vec);
9243 VPrintExtendedCacheStats(int flags)
9246 VPrintExtendedCacheStats_r(flags);
9249 #endif /* AFS_DEMAND_ATTACH_FS */
9252 VCanScheduleSalvage(void)
9254 return vol_opts.canScheduleSalvage;
9260 return vol_opts.canUseFSSYNC;
9264 VCanUseSALVSYNC(void)
9266 return vol_opts.canUseSALVSYNC;
9270 VCanUnsafeAttach(void)
9272 return vol_opts.unsafe_attach;