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 = calloc(1, sizeof(Volume));
930 vp->device = partition->device;
931 vp->partition = partition;
933 queue_Init(&vp->vnode_list);
934 queue_Init(&vp->rx_call_list);
935 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
937 vb->batch[vb->size++] = vp;
938 if (vb->size == VINIT_BATCH_MAX_SIZE) {
939 MUTEX_ENTER(&vq->mutex);
940 queue_Append(vq, vb);
941 CV_BROADCAST(&vq->cv);
942 MUTEX_EXIT(&vq->mutex);
944 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
946 vb->thread = params->thread;
955 MUTEX_ENTER(&vq->mutex);
956 queue_Append(vq, vb);
957 CV_BROADCAST(&vq->cv);
958 MUTEX_EXIT(&vq->mutex);
960 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
966 * Read next element from the pre-populated partition list.
968 static struct DiskPartition64*
969 VInitNextPartition(struct partition_queue *pq)
971 struct DiskPartition64 *partition;
972 struct diskpartition_queue_t *dp; /* queue element */
974 if (vinit_attach_abort) {
975 Log("Aborting volume preattach thread.\n");
979 /* get next partition to scan */
980 MUTEX_ENTER(&pq->mutex);
981 if (queue_IsEmpty(pq)) {
982 MUTEX_EXIT(&pq->mutex);
985 dp = queue_First(pq, diskpartition_queue_t);
987 MUTEX_EXIT(&pq->mutex);
990 osi_Assert(dp->diskP);
992 partition = dp->diskP;
998 * Find next volume id on the partition.
1001 VInitNextVolumeId(DIR *dirp)
1007 while((d = readdir(dirp))) {
1008 if (vinit_attach_abort) {
1009 Log("Aborting volume preattach thread.\n");
1012 ext = strrchr(d->d_name, '.');
1013 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1014 vid = VolumeNumber(d->d_name);
1018 Log("Warning: bogus volume header file: %s\n", d->d_name);
1025 * Preattach volumes in batches to avoid lock contention.
1028 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1030 struct volume_init_batch *vb;
1034 /* dequeue next volume */
1035 MUTEX_ENTER(&vq->mutex);
1036 if (queue_IsEmpty(vq)) {
1037 CV_WAIT(&vq->cv, &vq->mutex);
1039 vb = queue_First(vq, volume_init_batch);
1041 MUTEX_EXIT(&vq->mutex);
1045 for (i = 0; i<vb->size; i++) {
1051 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1053 Log("Error looking up volume, code=%d\n", ec);
1056 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1059 /* put pre-attached volume onto the hash table
1060 * and bring it up to the pre-attached state */
1061 AddVolumeToHashTable(vp, vp->hashid);
1062 AddVolumeToVByPList_r(vp);
1063 VLRU_Init_Node_r(vp);
1064 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1077 #endif /* AFS_DEMAND_ATTACH_FS */
1079 #if !defined(AFS_DEMAND_ATTACH_FS)
1081 * attach all volumes on a given disk partition
1084 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1090 Log("Partition %s: attaching volumes\n", diskP->name);
1091 dirp = opendir(VPartitionPath(diskP));
1093 Log("opendir on Partition %s failed!\n", diskP->name);
1097 while ((dp = readdir(dirp))) {
1099 p = strrchr(dp->d_name, '.');
1101 if (vinit_attach_abort) {
1102 Log("Partition %s: abort attach volumes\n", diskP->name);
1106 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1109 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1111 (*(vp ? nAttached : nUnattached))++;
1112 if (error == VOFFLINE)
1113 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1114 else if (LogLevel >= 5) {
1115 Log("Partition %s: attached volume %d (%s)\n",
1116 diskP->name, VolumeNumber(dp->d_name),
1125 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1130 #endif /* !AFS_DEMAND_ATTACH_FS */
1132 /***************************************************/
1133 /* Shutdown routines */
1134 /***************************************************/
1138 * highly multithreaded volume package shutdown
1140 * with the demand attach fileserver extensions,
1141 * VShutdown has been modified to be multithreaded.
1142 * In order to achieve optimal use of many threads,
1143 * the shutdown code involves one control thread and
1144 * n shutdown worker threads. The control thread
1145 * periodically examines the number of volumes available
1146 * for shutdown on each partition, and produces a worker
1147 * thread allocation schedule. The idea is to eliminate
1148 * redundant scheduling computation on the workers by
1149 * having a single master scheduler.
1151 * The scheduler's objectives are:
1153 * each partition with volumes remaining gets allocated
1154 * at least 1 thread (assuming sufficient threads)
1156 * threads are allocated proportional to the number of
1157 * volumes remaining to be offlined. This ensures that
1158 * the OS I/O scheduler has many requests to elevator
1159 * seek on partitions that will (presumably) take the
1160 * longest amount of time (from now) to finish shutdown
1161 * (3) keep threads busy
1162 * when there are extra threads, they are assigned to
1163 * partitions using a simple round-robin algorithm
1165 * In the future, we may wish to add the ability to adapt
1166 * to the relative performance patterns of each disk
1171 * multi-step shutdown process
1173 * demand attach shutdown is a four-step process. Each
1174 * shutdown "pass" shuts down increasingly more difficult
1175 * volumes. The main purpose is to achieve better cache
1176 * utilization during shutdown.
1179 * shutdown volumes in the unattached, pre-attached
1182 * shutdown attached volumes with cached volume headers
1184 * shutdown all volumes in non-exclusive states
1186 * shutdown all remaining volumes
1189 #ifdef AFS_DEMAND_ATTACH_FS
1195 struct DiskPartition64 * diskP;
1196 struct diskpartition_queue_t * dpq;
1197 vshutdown_thread_t params;
1199 pthread_attr_t attrs;
1201 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1204 Log("VShutdown: aborting attach volumes\n");
1205 vinit_attach_abort = 1;
1206 VOL_CV_WAIT(&vol_init_attach_cond);
1209 for (params.n_parts=0, diskP = DiskPartitionList;
1210 diskP; diskP = diskP->next, params.n_parts++);
1212 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1213 params.n_parts, params.n_parts > 1 ? "s" : "");
1215 vol_shutting_down = 1;
1217 if (vol_attach_threads > 1) {
1218 /* prepare for parallel shutdown */
1219 params.n_threads = vol_attach_threads;
1220 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1221 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1222 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1223 osi_Assert(pthread_attr_init(&attrs) == 0);
1224 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1225 queue_Init(¶ms);
1227 /* setup the basic partition information structures for
1228 * parallel shutdown */
1229 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1231 struct rx_queue * qp, * nqp;
1235 VVByPListWait_r(diskP);
1236 VVByPListBeginExclusive_r(diskP);
1239 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1240 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1244 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1245 VPartitionPath(diskP), count);
1248 /* build up the pass 0 shutdown work queue */
1249 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1250 osi_Assert(dpq != NULL);
1252 queue_Prepend(¶ms, dpq);
1254 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1257 Log("VShutdown: beginning parallel fileserver shutdown\n");
1258 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1259 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1261 /* do pass 0 shutdown */
1262 MUTEX_ENTER(¶ms.lock);
1263 for (i=0; i < params.n_threads; i++) {
1264 osi_Assert(pthread_create
1265 (&tid, &attrs, &VShutdownThread,
1269 /* wait for all the pass 0 shutdowns to complete */
1270 while (params.n_threads_complete < params.n_threads) {
1271 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1273 params.n_threads_complete = 0;
1275 CV_BROADCAST(¶ms.cv);
1276 MUTEX_EXIT(¶ms.lock);
1278 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1279 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1281 /* run the parallel shutdown scheduler. it will drop the glock internally */
1282 ShutdownController(¶ms);
1284 /* wait for all the workers to finish pass 3 and terminate */
1285 while (params.pass < 4) {
1286 VOL_CV_WAIT(¶ms.cv);
1289 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1290 CV_DESTROY(¶ms.cv);
1291 CV_DESTROY(¶ms.master_cv);
1292 MUTEX_DESTROY(¶ms.lock);
1294 /* drop the VByPList exclusive reservations */
1295 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1296 VVByPListEndExclusive_r(diskP);
1297 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1298 VPartitionPath(diskP),
1299 params.stats[0][diskP->index],
1300 params.stats[1][diskP->index],
1301 params.stats[2][diskP->index],
1302 params.stats[3][diskP->index]);
1305 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1307 /* if we're only going to run one shutdown thread, don't bother creating
1309 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1311 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1312 VShutdownByPartition_r(diskP);
1316 Log("VShutdown: complete.\n");
1319 #else /* AFS_DEMAND_ATTACH_FS */
1329 Log("VShutdown: aborting attach volumes\n");
1330 vinit_attach_abort = 1;
1331 #ifdef AFS_PTHREAD_ENV
1332 VOL_CV_WAIT(&vol_init_attach_cond);
1334 LWP_WaitProcess(VInitAttachVolumes);
1335 #endif /* AFS_PTHREAD_ENV */
1338 Log("VShutdown: shutting down on-line volumes...\n");
1339 vol_shutting_down = 1;
1340 for (i = 0; i < VolumeHashTable.Size; i++) {
1341 /* try to hold first volume in the hash table */
1342 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1346 Log("VShutdown: Attempting to take volume %u offline.\n",
1349 /* next, take the volume offline (drops reference count) */
1350 VOffline_r(vp, "File server was shut down");
1354 Log("VShutdown: complete.\n");
1356 #endif /* AFS_DEMAND_ATTACH_FS */
1362 osi_Assert(VInit>0);
1369 * stop new activity (e.g. SALVSYNC) from occurring
1371 * Use this to make the volume package less busy; for example, during
1372 * shutdown. This doesn't actually shutdown/detach anything in the
1373 * volume package, but prevents certain processes from ocurring. For
1374 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1375 * could also use this to prevent new volume attachment, or prevent
1376 * other programs from checking out volumes, etc.
1381 #ifdef AFS_DEMAND_ATTACH_FS
1382 /* make sure we don't try to contact the salvageserver, since it may
1383 * not be around anymore */
1384 vol_disallow_salvsync = 1;
1388 #ifdef AFS_DEMAND_ATTACH_FS
1391 * shutdown control thread
1394 ShutdownController(vshutdown_thread_t * params)
1397 struct DiskPartition64 * diskP;
1399 vshutdown_thread_t shadow;
1401 ShutdownCreateSchedule(params);
1403 while ((params->pass < 4) &&
1404 (params->n_threads_complete < params->n_threads)) {
1405 /* recompute schedule once per second */
1407 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1411 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1412 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1413 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1414 shadow.n_threads_complete, shadow.n_parts_done_pass);
1415 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1417 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1419 diskP->vol_list.len,
1420 shadow.part_thread_target[id],
1421 shadow.part_done_pass[id],
1422 shadow.part_pass_head[id]);
1428 ShutdownCreateSchedule(params);
1432 /* create the shutdown thread work schedule.
1433 * this scheduler tries to implement fairness
1434 * by allocating at least 1 thread to each
1435 * partition with volumes to be shutdown,
1436 * and then it attempts to allocate remaining
1437 * threads based upon the amount of work left
1440 ShutdownCreateSchedule(vshutdown_thread_t * params)
1442 struct DiskPartition64 * diskP;
1443 int sum, thr_workload, thr_left;
1444 int part_residue[VOLMAXPARTS+1];
1447 /* compute the total number of outstanding volumes */
1449 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1450 sum += diskP->vol_list.len;
1453 params->schedule_version++;
1454 params->vol_remaining = sum;
1459 /* compute average per-thread workload */
1460 thr_workload = sum / params->n_threads;
1461 if (sum % params->n_threads)
1464 thr_left = params->n_threads;
1465 memset(&part_residue, 0, sizeof(part_residue));
1467 /* for fairness, give every partition with volumes remaining
1468 * at least one thread */
1469 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1471 if (diskP->vol_list.len) {
1472 params->part_thread_target[id] = 1;
1475 params->part_thread_target[id] = 0;
1479 if (thr_left && thr_workload) {
1480 /* compute length-weighted workloads */
1483 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1485 delta = (diskP->vol_list.len / thr_workload) -
1486 params->part_thread_target[id];
1490 if (delta < thr_left) {
1491 params->part_thread_target[id] += delta;
1494 params->part_thread_target[id] += thr_left;
1502 /* try to assign any leftover threads to partitions that
1503 * had volume lengths closer to needing thread_target+1 */
1504 int max_residue, max_id = 0;
1506 /* compute the residues */
1507 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1509 part_residue[id] = diskP->vol_list.len -
1510 (params->part_thread_target[id] * thr_workload);
1513 /* now try to allocate remaining threads to partitions with the
1514 * highest residues */
1517 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1519 if (part_residue[id] > max_residue) {
1520 max_residue = part_residue[id];
1529 params->part_thread_target[max_id]++;
1531 part_residue[max_id] = 0;
1536 /* punt and give any remaining threads equally to each partition */
1538 if (thr_left >= params->n_parts) {
1539 alloc = thr_left / params->n_parts;
1540 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1542 params->part_thread_target[id] += alloc;
1547 /* finish off the last of the threads */
1548 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1550 params->part_thread_target[id]++;
1556 /* worker thread for parallel shutdown */
1558 VShutdownThread(void * args)
1560 vshutdown_thread_t * params;
1561 int found, pass, schedule_version_save, count;
1562 struct DiskPartition64 *diskP;
1563 struct diskpartition_queue_t * dpq;
1566 params = (vshutdown_thread_t *) args;
1568 /* acquire the shutdown pass 0 lock */
1569 MUTEX_ENTER(¶ms->lock);
1571 /* if there's still pass 0 work to be done,
1572 * get a work entry, and do a pass 0 shutdown */
1573 if (queue_IsNotEmpty(params)) {
1574 dpq = queue_First(params, diskpartition_queue_t);
1576 MUTEX_EXIT(¶ms->lock);
1582 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1584 params->stats[0][diskP->index] = count;
1585 MUTEX_ENTER(¶ms->lock);
1588 params->n_threads_complete++;
1589 if (params->n_threads_complete == params->n_threads) {
1590 /* notify control thread that all workers have completed pass 0 */
1591 CV_SIGNAL(¶ms->master_cv);
1593 while (params->pass == 0) {
1594 CV_WAIT(¶ms->cv, ¶ms->lock);
1598 MUTEX_EXIT(¶ms->lock);
1601 pass = params->pass;
1602 osi_Assert(pass > 0);
1604 /* now escalate through the more complicated shutdowns */
1606 schedule_version_save = params->schedule_version;
1608 /* find a disk partition to work on */
1609 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1611 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1612 params->part_thread_target[id]--;
1619 /* hmm. for some reason the controller thread couldn't find anything for
1620 * us to do. let's see if there's anything we can do */
1621 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1623 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1626 } else if (!params->part_done_pass[id]) {
1627 params->part_done_pass[id] = 1;
1628 params->n_parts_done_pass++;
1630 Log("VShutdown: done shutting down volumes on partition %s.\n",
1631 VPartitionPath(diskP));
1637 /* do work on this partition until either the controller
1638 * creates a new schedule, or we run out of things to do
1639 * on this partition */
1642 while (!params->part_done_pass[id] &&
1643 (schedule_version_save == params->schedule_version)) {
1644 /* ShutdownVolumeWalk_r will drop the glock internally */
1645 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1646 if (!params->part_done_pass[id]) {
1647 params->part_done_pass[id] = 1;
1648 params->n_parts_done_pass++;
1650 Log("VShutdown: done shutting down volumes on partition %s.\n",
1651 VPartitionPath(diskP));
1659 params->stats[pass][id] += count;
1661 /* ok, everyone is done this pass, proceed */
1664 params->n_threads_complete++;
1665 while (params->pass == pass) {
1666 if (params->n_threads_complete == params->n_threads) {
1667 /* we are the last thread to complete, so we will
1668 * reinitialize worker pool state for the next pass */
1669 params->n_threads_complete = 0;
1670 params->n_parts_done_pass = 0;
1672 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1674 params->part_done_pass[id] = 0;
1675 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1678 /* compute a new thread schedule before releasing all the workers */
1679 ShutdownCreateSchedule(params);
1681 /* wake up all the workers */
1682 CV_BROADCAST(¶ms->cv);
1685 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1686 pass, params->n_threads, params->n_parts);
1689 VOL_CV_WAIT(¶ms->cv);
1692 pass = params->pass;
1706 /* shut down all volumes on a given disk partition
1708 * note that this function will not allow mp-fast
1709 * shutdown of a partition */
1711 VShutdownByPartition_r(struct DiskPartition64 * dp)
1717 /* wait for other exclusive ops to finish */
1718 VVByPListWait_r(dp);
1720 /* begin exclusive access */
1721 VVByPListBeginExclusive_r(dp);
1723 /* pick the low-hanging fruit first,
1724 * then do the complicated ones last
1725 * (has the advantage of keeping
1726 * in-use volumes up until the bitter end) */
1727 for (pass = 0, total=0; pass < 4; pass++) {
1728 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1729 total += pass_stats[pass];
1732 /* end exclusive access */
1733 VVByPListEndExclusive_r(dp);
1735 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1736 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1741 /* internal shutdown functionality
1743 * for multi-pass shutdown:
1744 * 0 to only "shutdown" {pre,un}attached and error state volumes
1745 * 1 to also shutdown attached volumes w/ volume header loaded
1746 * 2 to also shutdown attached volumes w/o volume header loaded
1747 * 3 to also shutdown exclusive state volumes
1749 * caller MUST hold exclusive access on the hash chain
1750 * because we drop vol_glock_mutex internally
1752 * this function is reentrant for passes 1--3
1753 * (e.g. multiple threads can cooperate to
1754 * shutdown a partition mp-fast)
1756 * pass 0 is not scaleable because the volume state data is
1757 * synchronized by vol_glock mutex, and the locking overhead
1758 * is too high to drop the lock long enough to do linked list
1762 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1764 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1767 while (ShutdownVolumeWalk_r(dp, pass, &q))
1773 /* conditionally shutdown one volume on partition dp
1774 * returns 1 if a volume was shutdown in this pass,
1777 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1778 struct rx_queue ** idx)
1780 struct rx_queue *qp, *nqp;
1785 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1786 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1790 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1791 (V_attachState(vp) != VOL_STATE_ERROR) &&
1792 (V_attachState(vp) != VOL_STATE_DELETED) &&
1793 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1797 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1798 (vp->header == NULL)) {
1802 if (VIsExclusiveState(V_attachState(vp))) {
1807 DeleteVolumeFromVByPList_r(vp);
1808 VShutdownVolume_r(vp);
1818 * shutdown a specific volume
1820 /* caller MUST NOT hold a heavyweight ref on vp */
1822 VShutdownVolume_r(Volume * vp)
1826 VCreateReservation_r(vp);
1828 if (LogLevel >= 5) {
1829 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1830 vp->hashid, vp->partition->device, V_attachState(vp));
1833 /* wait for other blocking ops to finish */
1834 VWaitExclusiveState_r(vp);
1836 osi_Assert(VIsValidState(V_attachState(vp)));
1838 switch(V_attachState(vp)) {
1839 case VOL_STATE_SALVAGING:
1840 /* Leave salvaging volumes alone. Any in-progress salvages will
1841 * continue working after viced shuts down. This is intentional.
1844 case VOL_STATE_PREATTACHED:
1845 case VOL_STATE_ERROR:
1846 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1847 case VOL_STATE_UNATTACHED:
1848 case VOL_STATE_DELETED:
1850 case VOL_STATE_GOING_OFFLINE:
1851 case VOL_STATE_SHUTTING_DOWN:
1852 case VOL_STATE_ATTACHED:
1856 Log("VShutdown: Attempting to take volume %u offline.\n",
1859 /* take the volume offline (drops reference count) */
1860 VOffline_r(vp, "File server was shut down");
1867 VCancelReservation_r(vp);
1871 #endif /* AFS_DEMAND_ATTACH_FS */
1874 /***************************************************/
1875 /* Header I/O routines */
1876 /***************************************************/
1879 HeaderName(bit32 magic)
1882 case VOLUMEINFOMAGIC:
1883 return "volume info";
1884 case SMALLINDEXMAGIC:
1885 return "small index";
1886 case LARGEINDEXMAGIC:
1887 return "large index";
1888 case LINKTABLEMAGIC:
1889 return "link table";
1894 /* open a descriptor for the inode (h),
1895 * read in an on-disk structure into buffer (to) of size (size),
1896 * verify versionstamp in structure has magic (magic) and
1897 * optionally verify version (version) if (version) is nonzero
1900 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1903 struct versionStamp *vsn;
1905 afs_sfsize_t nbytes;
1910 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1918 Log("ReadHeader: Failed to open %s header file "
1919 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1920 PrintInode(stmp, h->ih_ino), errno);
1925 vsn = (struct versionStamp *)to;
1926 nbytes = FDH_PREAD(fdP, to, size, 0);
1928 Log("ReadHeader: Failed to read %s header file "
1929 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1930 PrintInode(stmp, h->ih_ino), errno);
1932 FDH_REALLYCLOSE(fdP);
1935 if (nbytes != size) {
1936 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1937 "(volume=%u, inode=%s); expected=%d, read=%d\n",
1938 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), size,
1941 FDH_REALLYCLOSE(fdP);
1944 if (vsn->magic != magic) {
1945 Log("ReadHeader: Incorrect magic for %s header file "
1946 "(volume=%u, inode=%s); expected=0x%x, read=0x%x\n",
1947 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), magic,
1950 FDH_REALLYCLOSE(fdP);
1956 /* Check is conditional, in case caller wants to inspect version himself */
1957 if (version && vsn->version != version) {
1958 Log("ReadHeader: Incorrect version for %s header file "
1959 "(volume=%u, inode=%s); expected=%x, read=%x\n",
1960 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino),
1961 version, vsn->version);
1967 WriteVolumeHeader_r(Error * ec, Volume * vp)
1969 IHandle_t *h = V_diskDataHandle(vp);
1979 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1980 != sizeof(V_disk(vp))) {
1982 FDH_REALLYCLOSE(fdP);
1988 /* VolumeHeaderToDisk
1989 * Allows for storing 64 bit inode numbers in on-disk volume header
1992 /* convert in-memory representation of a volume header to the
1993 * on-disk representation of a volume header */
1995 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1998 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1999 dh->stamp = h->stamp;
2001 dh->parent = h->parent;
2003 #ifdef AFS_64BIT_IOPS_ENV
2004 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2005 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2006 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2007 dh->smallVnodeIndex_hi =
2008 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2009 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2010 dh->largeVnodeIndex_hi =
2011 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2012 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2013 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2015 dh->volumeInfo_lo = h->volumeInfo;
2016 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2017 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2018 dh->linkTable_lo = h->linkTable;
2022 /* DiskToVolumeHeader
2023 * Converts an on-disk representation of a volume header to
2024 * the in-memory representation of a volume header.
2026 * Makes the assumption that AFS has *always*
2027 * zero'd the volume header file so that high parts of inode
2028 * numbers are 0 in older (SGI EFS) volume header files.
2031 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2033 memset(h, 0, sizeof(VolumeHeader_t));
2034 h->stamp = dh->stamp;
2036 h->parent = dh->parent;
2038 #ifdef AFS_64BIT_IOPS_ENV
2040 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2042 h->smallVnodeIndex =
2043 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2044 smallVnodeIndex_hi << 32);
2046 h->largeVnodeIndex =
2047 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2048 largeVnodeIndex_hi << 32);
2050 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2052 h->volumeInfo = dh->volumeInfo_lo;
2053 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2054 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2055 h->linkTable = dh->linkTable_lo;
2060 /***************************************************/
2061 /* Volume Attachment routines */
2062 /***************************************************/
2064 #ifdef AFS_DEMAND_ATTACH_FS
2066 * pre-attach a volume given its path.
2068 * @param[out] ec outbound error code
2069 * @param[in] partition partition path string
2070 * @param[in] name volume id string
2072 * @return volume object pointer
2074 * @note A pre-attached volume will only have its partition
2075 * and hashid fields initialized. At first call to
2076 * VGetVolume, the volume will be fully attached.
2080 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2084 vp = VPreAttachVolumeByName_r(ec, partition, name);
2090 * pre-attach a volume given its path.
2092 * @param[out] ec outbound error code
2093 * @param[in] partition path to vice partition
2094 * @param[in] name volume id string
2096 * @return volume object pointer
2098 * @pre VOL_LOCK held
2100 * @internal volume package internal use only.
2103 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2105 return VPreAttachVolumeById_r(ec,
2107 VolumeNumber(name));
2111 * pre-attach a volume given its path and numeric volume id.
2113 * @param[out] ec error code return
2114 * @param[in] partition path to vice partition
2115 * @param[in] volumeId numeric volume id
2117 * @return volume object pointer
2119 * @pre VOL_LOCK held
2121 * @internal volume package internal use only.
2124 VPreAttachVolumeById_r(Error * ec,
2129 struct DiskPartition64 *partp;
2133 osi_Assert(programType == fileServer);
2135 if (!(partp = VGetPartition_r(partition, 0))) {
2137 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2141 vp = VLookupVolume_r(ec, volumeId, NULL);
2146 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2150 * preattach a volume.
2152 * @param[out] ec outbound error code
2153 * @param[in] partp pointer to partition object
2154 * @param[in] vp pointer to volume object
2155 * @param[in] vid volume id
2157 * @return volume object pointer
2159 * @pre VOL_LOCK is held.
2161 * @warning Returned volume object pointer does not have to
2162 * equal the pointer passed in as argument vp. There
2163 * are potential race conditions which can result in
2164 * the pointers having different values. It is up to
2165 * the caller to make sure that references are handled
2166 * properly in this case.
2168 * @note If there is already a volume object registered with
2169 * the same volume id, its pointer MUST be passed as
2170 * argument vp. Failure to do so will result in a silent
2171 * failure to preattach.
2173 * @internal volume package internal use only.
2176 VPreAttachVolumeByVp_r(Error * ec,
2177 struct DiskPartition64 * partp,
2185 /* check to see if pre-attach already happened */
2187 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2188 (V_attachState(vp) != VOL_STATE_DELETED) &&
2189 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2190 !VIsErrorState(V_attachState(vp))) {
2192 * pre-attach is a no-op in all but the following cases:
2194 * - volume is unattached
2195 * - volume is in an error state
2196 * - volume is pre-attached
2198 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state (state %u flags 0x%x)\n",
2199 vid, V_attachState(vp), V_attachFlags(vp));
2202 /* we're re-attaching a volume; clear out some old state */
2203 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2205 if (V_partition(vp) != partp) {
2206 /* XXX potential race */
2207 DeleteVolumeFromVByPList_r(vp);
2210 /* if we need to allocate a new Volume struct,
2211 * go ahead and drop the vol glock, otherwise
2212 * do the basic setup synchronised, as it's
2213 * probably not worth dropping the lock */
2216 /* allocate the volume structure */
2217 vp = nvp = calloc(1, sizeof(Volume));
2218 osi_Assert(vp != NULL);
2219 queue_Init(&vp->vnode_list);
2220 queue_Init(&vp->rx_call_list);
2221 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2224 /* link the volume with its associated vice partition */
2225 vp->device = partp->device;
2226 vp->partition = partp;
2229 vp->specialStatus = 0;
2231 /* if we dropped the lock, reacquire the lock,
2232 * check for pre-attach races, and then add
2233 * the volume to the hash table */
2236 nvp = VLookupVolume_r(ec, vid, NULL);
2241 } else if (nvp) { /* race detected */
2246 /* hack to make up for VChangeState_r() decrementing
2247 * the old state counter */
2248 VStats.state_levels[0]++;
2252 /* put pre-attached volume onto the hash table
2253 * and bring it up to the pre-attached state */
2254 AddVolumeToHashTable(vp, vp->hashid);
2255 AddVolumeToVByPList_r(vp);
2256 VLRU_Init_Node_r(vp);
2257 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2260 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2268 #endif /* AFS_DEMAND_ATTACH_FS */
2270 /* Attach an existing volume, given its pathname, and return a
2271 pointer to the volume header information. The volume also
2272 normally goes online at this time. An offline volume
2273 must be reattached to make it go online */
2275 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2279 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2285 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2288 struct DiskPartition64 *partp;
2293 #ifdef AFS_DEMAND_ATTACH_FS
2294 VolumeStats stats_save;
2296 #endif /* AFS_DEMAND_ATTACH_FS */
2300 volumeId = VolumeNumber(name);
2302 if (!(partp = VGetPartition_r(partition, 0))) {
2304 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2308 if (VRequiresPartLock()) {
2309 osi_Assert(VInit == 3);
2310 VLockPartition_r(partition);
2311 } else if (programType == fileServer) {
2312 #ifdef AFS_DEMAND_ATTACH_FS
2313 /* lookup the volume in the hash table */
2314 vp = VLookupVolume_r(ec, volumeId, NULL);
2320 /* save any counters that are supposed to
2321 * be monotonically increasing over the
2322 * lifetime of the fileserver */
2323 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2325 memset(&stats_save, 0, sizeof(VolumeStats));
2328 /* if there's something in the hash table, and it's not
2329 * in the pre-attach state, then we may need to detach
2330 * it before proceeding */
2331 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2332 VCreateReservation_r(vp);
2333 VWaitExclusiveState_r(vp);
2335 /* at this point state must be one of:
2345 if (vp->specialStatus == VBUSY)
2348 /* if it's already attached, see if we can return it */
2349 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2350 VGetVolumeByVp_r(ec, vp);
2351 if (V_inUse(vp) == fileServer) {
2352 VCancelReservation_r(vp);
2356 /* otherwise, we need to detach, and attempt to re-attach */
2357 VDetachVolume_r(ec, vp);
2359 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2362 /* if it isn't fully attached, delete from the hash tables,
2363 and let the refcounter handle the rest */
2364 DeleteVolumeFromHashTable(vp);
2365 DeleteVolumeFromVByPList_r(vp);
2368 VCancelReservation_r(vp);
2372 /* pre-attach volume if it hasn't been done yet */
2374 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2375 (V_attachState(vp) == VOL_STATE_DELETED) ||
2376 (V_attachState(vp) == VOL_STATE_ERROR)) {
2378 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2384 osi_Assert(vp != NULL);
2386 /* handle pre-attach races
2388 * multiple threads can race to pre-attach a volume,
2389 * but we can't let them race beyond that
2391 * our solution is to let the first thread to bring
2392 * the volume into an exclusive state win; the other
2393 * threads just wait until it finishes bringing the
2394 * volume online, and then they do a vgetvolumebyvp
2396 if (svp && (svp != vp)) {
2397 /* wait for other exclusive ops to finish */
2398 VCreateReservation_r(vp);
2399 VWaitExclusiveState_r(vp);
2401 /* get a heavyweight ref, kill the lightweight ref, and return */
2402 VGetVolumeByVp_r(ec, vp);
2403 VCancelReservation_r(vp);
2407 /* at this point, we are chosen as the thread to do
2408 * demand attachment for this volume. all other threads
2409 * doing a getvolume on vp->hashid will block until we finish */
2411 /* make sure any old header cache entries are invalidated
2412 * before proceeding */
2413 FreeVolumeHeader(vp);
2415 VChangeState_r(vp, VOL_STATE_ATTACHING);
2417 /* restore any saved counters */
2418 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2419 #else /* AFS_DEMAND_ATTACH_FS */
2420 vp = VGetVolume_r(ec, volumeId);
2422 if (V_inUse(vp) == fileServer)
2424 if (vp->specialStatus == VBUSY)
2426 VDetachVolume_r(ec, vp);
2428 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2432 #endif /* AFS_DEMAND_ATTACH_FS */
2436 strcpy(path, VPartitionPath(partp));
2440 strcat(path, OS_DIRSEP);
2444 vp = (Volume *) calloc(1, sizeof(Volume));
2445 osi_Assert(vp != NULL);
2446 vp->hashid = volumeId;
2447 vp->device = partp->device;
2448 vp->partition = partp;
2449 queue_Init(&vp->vnode_list);
2450 queue_Init(&vp->rx_call_list);
2451 #ifdef AFS_DEMAND_ATTACH_FS
2452 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2453 #endif /* AFS_DEMAND_ATTACH_FS */
2456 /* attach2 is entered without any locks, and returns
2457 * with vol_glock_mutex held */
2458 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2460 if (VCanUseFSSYNC() && vp) {
2461 #ifdef AFS_DEMAND_ATTACH_FS
2462 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2463 /* mark volume header as in use so that volser crashes lead to a
2464 * salvage attempt */
2465 VUpdateVolume_r(ec, vp, 0);
2467 /* for dafs, we should tell the fileserver, except for V_PEEK
2468 * where we know it is not necessary */
2469 if (mode == V_PEEK) {
2470 vp->needsPutBack = 0;
2472 vp->needsPutBack = VOL_PUTBACK;
2474 #else /* !AFS_DEMAND_ATTACH_FS */
2475 /* duplicate computation in fssync.c about whether the server
2476 * takes the volume offline or not. If the volume isn't
2477 * offline, we must not return it when we detach the volume,
2478 * or the server will abort */
2479 if (mode == V_READONLY || mode == V_PEEK
2480 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2481 vp->needsPutBack = 0;
2483 vp->needsPutBack = VOL_PUTBACK;
2484 #endif /* !AFS_DEMAND_ATTACH_FS */
2486 #ifdef FSSYNC_BUILD_CLIENT
2487 /* Only give back the vol to the fileserver if we checked it out; attach2
2488 * will set checkedOut only if we successfully checked it out from the
2490 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2492 #ifdef AFS_DEMAND_ATTACH_FS
2493 /* If we couldn't attach but we scheduled a salvage, we already
2494 * notified the fileserver; don't online it now */
2495 if (*ec != VSALVAGING)
2496 #endif /* AFS_DEMAND_ATTACH_FS */
2497 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2500 if (programType == fileServer && vp) {
2501 #ifdef AFS_DEMAND_ATTACH_FS
2503 * we can get here in cases where we don't "own"
2504 * the volume (e.g. volume owned by a utility).
2505 * short circuit around potential disk header races.
2507 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2511 VUpdateVolume_r(ec, vp, 0);
2513 Log("VAttachVolume: Error updating volume\n");
2518 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2519 #ifndef AFS_DEMAND_ATTACH_FS
2520 /* This is a hack: by temporarily setting the incore
2521 * dontSalvage flag ON, the volume will be put back on the
2522 * Update list (with dontSalvage OFF again). It will then
2523 * come back in N minutes with DONT_SALVAGE eventually
2524 * set. This is the way that volumes that have never had
2525 * it set get it set; or that volumes that have been
2526 * offline without DONT SALVAGE having been set also
2527 * eventually get it set */
2528 V_dontSalvage(vp) = DONT_SALVAGE;
2529 #endif /* !AFS_DEMAND_ATTACH_FS */
2530 VAddToVolumeUpdateList_r(ec, vp);
2532 Log("VAttachVolume: Error adding volume to update list\n");
2539 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2544 if (VRequiresPartLock()) {
2545 VUnlockPartition_r(partition);
2548 #ifdef AFS_DEMAND_ATTACH_FS
2549 /* attach failed; make sure we're in error state */
2550 if (vp && !VIsErrorState(V_attachState(vp))) {
2551 VChangeState_r(vp, VOL_STATE_ERROR);
2553 #endif /* AFS_DEMAND_ATTACH_FS */
2560 #ifdef AFS_DEMAND_ATTACH_FS
2561 /* VAttachVolumeByVp_r
2563 * finish attaching a volume that is
2564 * in a less than fully attached state
2566 /* caller MUST hold a ref count on vp */
2568 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2570 char name[VMAXPATHLEN];
2572 struct DiskPartition64 *partp;
2576 Volume * nvp = NULL;
2577 VolumeStats stats_save;
2581 /* volume utility should never call AttachByVp */
2582 osi_Assert(programType == fileServer);
2584 volumeId = vp->hashid;
2585 partp = vp->partition;
2586 VolumeExternalName_r(volumeId, name, sizeof(name));
2589 /* if another thread is performing a blocking op, wait */
2590 VWaitExclusiveState_r(vp);
2592 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2594 /* if it's already attached, see if we can return it */
2595 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2596 VGetVolumeByVp_r(ec, vp);
2597 if (V_inUse(vp) == fileServer) {
2600 if (vp->specialStatus == VBUSY)
2602 VDetachVolume_r(ec, vp);
2604 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2610 /* pre-attach volume if it hasn't been done yet */
2612 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2613 (V_attachState(vp) == VOL_STATE_DELETED) ||
2614 (V_attachState(vp) == VOL_STATE_ERROR)) {
2615 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2621 VCreateReservation_r(nvp);
2626 osi_Assert(vp != NULL);
2627 VChangeState_r(vp, VOL_STATE_ATTACHING);
2629 /* restore monotonically increasing stats */
2630 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2634 /* compute path to disk header */
2635 strcpy(path, VPartitionPath(partp));
2639 strcat(path, OS_DIRSEP);
2644 * NOTE: attach2 is entered without any locks, and returns
2645 * with vol_glock_mutex held */
2646 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2649 * the event that an error was encountered, or
2650 * the volume was not brought to an attached state
2651 * for any reason, skip to the end. We cannot
2652 * safely call VUpdateVolume unless we "own" it.
2656 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2660 VUpdateVolume_r(ec, vp, 0);
2662 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2666 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2667 #ifndef AFS_DEMAND_ATTACH_FS
2668 /* This is a hack: by temporarily setting the incore
2669 * dontSalvage flag ON, the volume will be put back on the
2670 * Update list (with dontSalvage OFF again). It will then
2671 * come back in N minutes with DONT_SALVAGE eventually
2672 * set. This is the way that volumes that have never had
2673 * it set get it set; or that volumes that have been
2674 * offline without DONT SALVAGE having been set also
2675 * eventually get it set */
2676 V_dontSalvage(vp) = DONT_SALVAGE;
2677 #endif /* !AFS_DEMAND_ATTACH_FS */
2678 VAddToVolumeUpdateList_r(ec, vp);
2680 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2687 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2691 VCancelReservation_r(nvp);
2694 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2695 if (vp && !VIsErrorState(V_attachState(vp))) {
2696 VChangeState_r(vp, VOL_STATE_ERROR);
2705 * lock a volume on disk (non-blocking).
2707 * @param[in] vp The volume to lock
2708 * @param[in] locktype READ_LOCK or WRITE_LOCK
2710 * @return operation status
2711 * @retval 0 success, lock was obtained
2712 * @retval EBUSY a conflicting lock was held by another process
2713 * @retval EIO error acquiring lock
2715 * @pre If we're in the fileserver, vp is in an exclusive state
2717 * @pre vp is not already locked
2720 VLockVolumeNB(Volume *vp, int locktype)
2724 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2725 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2727 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2729 V_attachFlags(vp) |= VOL_LOCKED;
2736 * unlock a volume on disk that was locked with VLockVolumeNB.
2738 * @param[in] vp volume to unlock
2740 * @pre If we're in the fileserver, vp is in an exclusive state
2742 * @pre vp has already been locked
2745 VUnlockVolume(Volume *vp)
2747 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2748 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2750 VUnlockVolumeById(vp->hashid, vp->partition);
2752 V_attachFlags(vp) &= ~VOL_LOCKED;
2754 #endif /* AFS_DEMAND_ATTACH_FS */
2757 * read in a vol header, possibly lock the vol header, and possibly check out
2758 * the vol header from the fileserver, as part of volume attachment.
2760 * @param[out] ec error code
2761 * @param[in] vp volume pointer object
2762 * @param[in] partp disk partition object of the attaching partition
2763 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2765 * @param[in] peek 1 to just try to read in the volume header and make sure
2766 * we don't try to lock the vol, or check it out from
2767 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2769 * @param[out] acheckedOut If we successfully checked-out the volume from
2770 * the fileserver (if we needed to), this is set
2771 * to 1, otherwise it is untouched.
2773 * @note As part of DAFS volume attachment, the volume header may be either
2774 * read- or write-locked to ensure mutual exclusion of certain volume
2775 * operations. In some cases in order to determine whether we need to
2776 * read- or write-lock the header, we need to read in the header to see
2777 * if the volume is RW or not. So, if we read in the header under a
2778 * read-lock and determine that we actually need a write-lock on the
2779 * volume header, this function will drop the read lock, acquire a write
2780 * lock, and read the header in again.
2783 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2784 int mode, int peek, int *acheckedOut)
2786 struct VolumeDiskHeader diskHeader;
2787 struct VolumeHeader header;
2790 int lock_tries = 0, checkout_tries = 0;
2792 VolumeId volid = vp->hashid;
2793 #ifdef FSSYNC_BUILD_CLIENT
2794 int checkout, done_checkout = 0;
2795 #endif /* FSSYNC_BUILD_CLIENT */
2796 #ifdef AFS_DEMAND_ATTACH_FS
2797 int locktype = 0, use_locktype = -1;
2798 #endif /* AFS_DEMAND_ATTACH_FS */
2804 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2805 Log("VAttachVolume: retried too many times trying to lock header for "
2806 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2807 VPartitionPath(partp));
2811 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2812 Log("VAttachVolume: retried too many times trying to checkout "
2813 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2814 VPartitionPath(partp));
2819 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2820 /* short-circuit the 'volume does not exist' case */
2825 #ifdef FSSYNC_BUILD_CLIENT
2826 checkout = !done_checkout;
2828 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2830 memset(&res, 0, sizeof(res));
2832 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2835 if (res.hdr.reason == FSYNC_SALVAGE) {
2836 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2837 afs_printable_uint32_lu(volid));
2840 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2841 afs_printable_uint32_lu(volid));
2842 *ec = VNOVOL; /* XXXX */
2850 #ifdef AFS_DEMAND_ATTACH_FS
2851 if (use_locktype < 0) {
2852 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2853 * if it turns out to be RW */
2854 locktype = VVolLockType(mode, 0);
2857 /* a previous try says we should use use_locktype to lock the volume,
2859 locktype = use_locktype;
2862 if (!peek && locktype) {
2863 code = VLockVolumeNB(vp, locktype);
2865 if (code == EBUSY) {
2866 Log("VAttachVolume: another program has vol %lu locked\n",
2867 afs_printable_uint32_lu(volid));
2869 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2870 code, afs_printable_uint32_lu(volid));
2877 #endif /* AFS_DEMAND_ATTACH_FS */
2879 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2889 DiskToVolumeHeader(&header, &diskHeader);
2891 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2892 header.largeVnodeIndex);
2893 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2894 header.smallVnodeIndex);
2895 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2897 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2900 /* only need to do this once */
2902 GetVolumeHeader(vp);
2906 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2907 /* demand attach changes the V_PEEK mechanism
2909 * we can now suck the current disk data structure over
2910 * the fssync interface without going to disk
2912 * (technically, we don't need to restrict this feature
2913 * to demand attach fileservers. However, I'm trying
2914 * to limit the number of common code changes)
2916 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2918 res.payload.len = sizeof(VolumeDiskData);
2919 res.payload.buf = &vp->header->diskstuff;
2921 if (FSYNC_VolOp(vp->hashid,
2923 FSYNC_VOL_QUERY_HDR,
2926 goto disk_header_loaded;
2929 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2930 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2931 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2933 #ifdef AFS_DEMAND_ATTACH_FS
2936 IncUInt64(&VStats.hdr_loads);
2937 IncUInt64(&vp->stats.hdr_loads);
2939 #endif /* AFS_DEMAND_ATTACH_FS */
2942 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2943 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2947 #ifdef AFS_DEMAND_ATTACH_FS
2948 # ifdef FSSYNC_BUILD_CLIENT
2950 # endif /* FSSYNC_BUILD_CLIENT */
2952 /* if the lock type we actually used to lock the volume is different than
2953 * the lock type we should have used, retry with the lock type we should
2955 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2956 if (locktype != use_locktype) {
2960 #endif /* AFS_DEMAND_ATTACH_FS */
2965 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2966 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2968 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2970 if (code == SYNC_DENIED) {
2971 /* must retry checkout; fileserver no longer thinks we have
2977 } else if (code != SYNC_OK) {
2981 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2984 /* either we are going to be called again for a second pass, or we
2985 * encountered an error; clean up in either case */
2987 #ifdef AFS_DEMAND_ATTACH_FS
2988 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2991 #endif /* AFS_DEMAND_ATTACH_FS */
2992 if (vp->linkHandle) {
2993 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2994 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2995 IH_RELEASE(vp->diskDataHandle);
2996 IH_RELEASE(vp->linkHandle);
3002 FreeVolumeHeader(vp);
3012 #ifdef AFS_DEMAND_ATTACH_FS
3014 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3015 Volume *vp, int *acheckedOut)
3019 if (vp->pending_vol_op) {
3023 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3025 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3027 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3028 } else if (code == 0) {
3029 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3032 /* we need the vol header to determine if the volume can be
3033 * left online for the vop, so... get the header */
3037 /* attach header with peek=1 to avoid checking out the volume
3038 * or locking it; we just want the header info, we're not
3039 * messing with the volume itself at all */
3040 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3047 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3048 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3050 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3053 /* make sure we grab a new vol header and re-open stuff on
3054 * actual attachment; we can't keep the data we grabbed, since
3055 * it was not done under a lock and thus not safe */
3056 FreeVolumeHeader(vp);
3057 VReleaseVolumeHandles_r(vp);
3060 /* see if the pending volume op requires exclusive access */
3061 switch (vp->pending_vol_op->vol_op_state) {
3062 case FSSYNC_VolOpPending:
3063 /* this should never happen */
3064 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3067 case FSSYNC_VolOpRunningUnknown:
3068 /* this should never happen; we resolved 'unknown' above */
3069 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3072 case FSSYNC_VolOpRunningOffline:
3073 /* mark the volume down */
3075 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3077 /* do not set V_offlineMessage here; we don't have ownership of
3078 * the volume (and probably do not have the header loaded), so we
3079 * can't alter the disk header */
3081 /* check to see if we should set the specialStatus flag */
3082 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3083 /* don't overwrite specialStatus if it was already set to
3084 * something else (e.g. VMOVED) */
3085 if (!vp->specialStatus) {
3086 vp->specialStatus = VBUSY;
3098 #endif /* AFS_DEMAND_ATTACH_FS */
3101 * volume attachment helper function.
3103 * @param[out] ec error code
3104 * @param[in] volumeId volume ID of the attaching volume
3105 * @param[in] path full path to the volume header .vol file
3106 * @param[in] partp disk partition object for the attaching partition
3107 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3108 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3109 * DAFS) should already be initialized
3110 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3111 * if there is a volume operation running for this volume
3112 * that should set the volume to VBUSY during its run. 0
3113 * otherwise. (see VVolOpSetVBusy_r)
3114 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3116 * @param[out] acheckedOut If we successfully checked-out the volume from
3117 * the fileserver (if we needed to), this is set
3118 * to 1, otherwise it is 0.
3120 * @return pointer to the semi-attached volume pointer
3121 * @retval NULL an error occurred (check value of *ec)
3122 * @retval vp volume successfully attaching
3124 * @pre no locks held
3126 * @post VOL_LOCK held
3129 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3130 Volume * vp, int isbusy, int mode, int *acheckedOut)
3132 /* have we read in the header successfully? */
3133 int read_header = 0;
3135 #ifdef AFS_DEMAND_ATTACH_FS
3136 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3140 /* in the case of an error, to what state should the volume be
3142 VolState error_state = VOL_STATE_ERROR;
3143 #endif /* AFS_DEMAND_ATTACH_FS */
3147 vp->vnodeIndex[vLarge].handle = NULL;
3148 vp->vnodeIndex[vSmall].handle = NULL;
3149 vp->diskDataHandle = NULL;
3150 vp->linkHandle = NULL;
3154 #ifdef AFS_DEMAND_ATTACH_FS
3155 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3157 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3160 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3161 #endif /* !AFS_DEMAND_ATTACH_FS */
3163 if (*ec == VNOVOL) {
3164 /* if the volume doesn't exist, skip straight to 'error' so we don't
3165 * request a salvage */
3167 goto error_notbroken;
3173 /* ensure that we don't override specialStatus if it was set to
3174 * something else (e.g. VMOVED) */
3175 if (isbusy && !vp->specialStatus) {
3176 vp->specialStatus = VBUSY;
3178 vp->shuttingDown = 0;
3179 vp->goingOffline = 0;
3181 #ifdef AFS_DEMAND_ATTACH_FS
3182 vp->stats.last_attach = FT_ApproxTime();
3183 vp->stats.attaches++;
3187 IncUInt64(&VStats.attaches);
3188 vp->cacheCheck = ++VolumeCacheCheck;
3189 /* just in case this ever rolls over */
3190 if (!vp->cacheCheck)
3191 vp->cacheCheck = ++VolumeCacheCheck;
3194 #ifdef AFS_DEMAND_ATTACH_FS
3195 V_attachFlags(vp) |= VOL_HDR_LOADED;
3196 vp->stats.last_hdr_load = vp->stats.last_attach;
3197 #endif /* AFS_DEMAND_ATTACH_FS */
3201 struct IndexFileHeader iHead;
3204 * We just read in the diskstuff part of the header. If the detailed
3205 * volume stats area has not yet been initialized, we should bzero the
3206 * area and mark it as initialized.
3208 if (!(V_stat_initialized(vp))) {
3209 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3210 V_stat_initialized(vp) = 1;
3213 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3214 (char *)&iHead, sizeof(iHead),
3215 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3218 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3223 struct IndexFileHeader iHead;
3225 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3226 (char *)&iHead, sizeof(iHead),
3227 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3230 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3234 #ifdef AFS_NAMEI_ENV
3236 struct versionStamp stamp;
3238 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3239 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3242 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3245 #endif /* AFS_NAMEI_ENV */
3247 #if defined(AFS_DEMAND_ATTACH_FS)
3248 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3250 if (!VCanScheduleSalvage()) {
3251 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3253 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3258 /* volume operation in progress */
3260 goto error_notbroken;
3262 #else /* AFS_DEMAND_ATTACH_FS */
3264 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3265 goto unlocked_error;
3267 #endif /* AFS_DEMAND_ATTACH_FS */
3269 if (V_needsSalvaged(vp)) {
3270 if (vp->specialStatus)
3271 vp->specialStatus = 0;
3273 #if defined(AFS_DEMAND_ATTACH_FS)
3274 if (!VCanScheduleSalvage()) {
3275 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3277 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3280 #else /* AFS_DEMAND_ATTACH_FS */
3282 #endif /* AFS_DEMAND_ATTACH_FS */
3288 vp->nextVnodeUnique = V_uniquifier(vp);
3290 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3291 if (!V_needsSalvaged(vp)) {
3292 V_needsSalvaged(vp) = 1;
3293 VUpdateVolume_r(ec, vp, 0);
3295 #if defined(AFS_DEMAND_ATTACH_FS)
3296 if (!VCanScheduleSalvage()) {
3297 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3299 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3302 #else /* AFS_DEMAND_ATTACH_FS */
3303 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3305 #endif /* AFS_DEMAND_ATTACH_FS */
3310 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3311 /* Only check destroyMe if we are the fileserver, since the
3312 * volserver et al sometimes need to work with volumes with
3313 * destroyMe set. Examples are 'temporary' volumes the
3314 * volserver creates, and when we create a volume (destroyMe
3315 * is set on creation; sometimes a separate volserver
3316 * transaction is created to clear destroyMe).
3319 #if defined(AFS_DEMAND_ATTACH_FS)
3320 /* schedule a salvage so the volume goes away on disk */
3321 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3322 VChangeState_r(vp, VOL_STATE_ERROR);
3325 #endif /* AFS_DEMAND_ATTACH_FS */
3326 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3331 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3332 #ifndef BITMAP_LATER
3333 if (programType == fileServer && VolumeWriteable(vp)) {
3335 for (i = 0; i < nVNODECLASSES; i++) {
3336 VGetBitmap_r(ec, vp, i);
3338 #ifdef AFS_DEMAND_ATTACH_FS
3339 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3341 #endif /* AFS_DEMAND_ATTACH_FS */
3342 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3348 #endif /* BITMAP_LATER */
3350 if (VInit >= 2 && V_needsCallback(vp)) {
3351 if (V_BreakVolumeCallbacks) {
3352 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3353 afs_printable_uint32_lu(V_id(vp)));
3354 V_needsCallback(vp) = 0;
3356 (*V_BreakVolumeCallbacks) (V_id(vp));
3359 VUpdateVolume_r(ec, vp, 0);
3361 #ifdef FSSYNC_BUILD_CLIENT
3362 else if (VCanUseFSSYNC()) {
3363 afs_int32 fsync_code;
3365 V_needsCallback(vp) = 0;
3367 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3371 V_needsCallback(vp) = 1;
3372 Log("Error trying to tell the fileserver to break callbacks for "
3373 "changed volume %lu; error code %ld\n",
3374 afs_printable_uint32_lu(V_id(vp)),
3375 afs_printable_int32_ld(fsync_code));
3377 VUpdateVolume_r(ec, vp, 0);
3380 #endif /* FSSYNC_BUILD_CLIENT */
3383 Log("VAttachVolume: error %d clearing needsCallback on volume "
3384 "%lu; needs salvage\n", (int)*ec,
3385 afs_printable_uint32_lu(V_id(vp)));
3386 #ifdef AFS_DEMAND_ATTACH_FS
3387 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3389 #else /* !AFS_DEMAND_ATTACH_FS */
3391 #endif /* !AFS_DEMAND_ATTACh_FS */
3396 if (programType == fileServer) {
3397 if (vp->specialStatus)
3398 vp->specialStatus = 0;
3399 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3400 V_inUse(vp) = fileServer;
3401 V_offlineMessage(vp)[0] = '\0';
3405 #ifdef AFS_DEMAND_ATTACH_FS
3406 /* Put the vol into PREATTACHED state, so if someone tries to
3407 * access it again, we try to attach, see that we're not blessed,
3408 * and give a VNOVOL error again. Putting it into UNATTACHED state
3409 * would result in a VOFFLINE error instead. */
3410 error_state = VOL_STATE_PREATTACHED;
3411 #endif /* AFS_DEMAND_ATTACH_FS */
3413 /* mimic e.g. GetVolume errors */
3414 if (!V_blessed(vp)) {
3415 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3416 FreeVolumeHeader(vp);
3417 } else if (!V_inService(vp)) {
3418 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3419 FreeVolumeHeader(vp);
3421 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3423 #ifdef AFS_DEMAND_ATTACH_FS
3424 error_state = VOL_STATE_ERROR;
3425 /* see if we can recover */
3426 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0 /*flags*/);
3429 #ifdef AFS_DEMAND_ATTACH_FS
3435 #ifdef AFS_DEMAND_ATTACH_FS
3436 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3437 V_inUse(vp) = programType;
3438 #endif /* AFS_DEMAND_ATTACH_FS */
3439 V_checkoutMode(vp) = mode;
3442 AddVolumeToHashTable(vp, V_id(vp));
3443 #ifdef AFS_DEMAND_ATTACH_FS
3444 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3447 if ((programType != fileServer) ||
3448 (V_inUse(vp) == fileServer)) {
3449 AddVolumeToVByPList_r(vp);
3451 VChangeState_r(vp, VOL_STATE_ATTACHED);
3453 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3459 #ifndef AFS_DEMAND_ATTACH_FS
3465 #ifdef AFS_DEMAND_ATTACH_FS
3466 if (!VIsErrorState(V_attachState(vp))) {
3467 if (VIsErrorState(error_state)) {
3468 Log("attach2: forcing vol %u to error state (state %u flags 0x%x ec %d)\n",
3469 vp->hashid, V_attachState(vp), V_attachFlags(vp), *ec);
3471 VChangeState_r(vp, error_state);
3473 #endif /* AFS_DEMAND_ATTACH_FS */
3476 VReleaseVolumeHandles_r(vp);
3480 #ifdef AFS_DEMAND_ATTACH_FS
3487 #else /* !AFS_DEMAND_ATTACH_FS */
3489 #endif /* !AFS_DEMAND_ATTACH_FS */
3493 /* Attach an existing volume.
3494 The volume also normally goes online at this time.
3495 An offline volume must be reattached to make it go online.
3499 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3503 retVal = VAttachVolume_r(ec, volumeId, mode);
3509 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3512 VGetVolumePath(ec, volumeId, &part, &name);
3516 vp = VGetVolume_r(&error, volumeId);
3518 osi_Assert(V_inUse(vp) == 0);
3519 VDetachVolume_r(ec, vp);
3523 return VAttachVolumeByName_r(ec, part, name, mode);
3526 /* Increment a reference count to a volume, sans context swaps. Requires
3527 * possibly reading the volume header in from the disk, since there's
3528 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3530 * N.B. This call can fail if we can't read in the header!! In this case
3531 * we still guarantee we won't context swap, but the ref count won't be
3532 * incremented (otherwise we'd violate the invariant).
3534 /* NOTE: with the demand attach fileserver extensions, the global lock
3535 * is dropped within VHold */
3536 #ifdef AFS_DEMAND_ATTACH_FS
3538 VHold_r(Volume * vp)
3542 VCreateReservation_r(vp);
3543 VWaitExclusiveState_r(vp);
3545 LoadVolumeHeader(&error, vp);
3547 VCancelReservation_r(vp);
3551 VCancelReservation_r(vp);
3554 #else /* AFS_DEMAND_ATTACH_FS */
3556 VHold_r(Volume * vp)
3560 LoadVolumeHeader(&error, vp);
3566 #endif /* AFS_DEMAND_ATTACH_FS */
3568 /**** volume timeout-related stuff ****/
3570 #ifdef AFS_PTHREAD_ENV
3572 static struct timespec *shutdown_timeout;
3573 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3576 VTimedOut(const struct timespec *ts)
3581 if (ts->tv_sec == 0) {
3582 /* short-circuit; this will have always timed out */
3586 code = gettimeofday(&tv, NULL);
3588 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3589 /* assume no timeout; failure mode is we just wait longer than normal
3590 * instead of returning errors when we shouldn't */
3594 if (tv.tv_sec < ts->tv_sec ||
3595 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3604 * Calculate an absolute timeout.
3606 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3607 * NULL, the memory is not touched
3608 * @param[in] timeout How long the timeout should be from now
3610 * @return timeout to use
3611 * @retval NULL no timeout; wait forever
3612 * @retval non-NULL the given value for "ts"
3616 static struct timespec *
3617 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3627 ts->tv_sec = ts->tv_nsec = 0;
3631 code = gettimeofday(&now, NULL);
3633 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3637 ts->tv_sec = now.tv_sec + timeout;
3638 ts->tv_nsec = now.tv_usec * 1000;
3644 * Initialize the shutdown_timeout global.
3647 VShutdownTimeoutInit(void)
3649 struct timespec *ts;
3651 ts = malloc(sizeof(*ts));
3653 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3655 if (!shutdown_timeout) {
3661 * Figure out the timeout that should be used for waiting for offline volumes.
3663 * @param[out] ats Storage space for a local timeout value if needed
3665 * @return The timeout value that should be used
3666 * @retval NULL No timeout; wait forever for offlining volumes
3667 * @retval non-NULL A pointer to the absolute time that should be used as
3668 * the deadline for waiting for offlining volumes.
3670 * @note If we return non-NULL, the pointer we return may or may not be the
3673 static const struct timespec *
3674 VOfflineTimeout(struct timespec *ats)
3676 if (vol_shutting_down) {
3677 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3678 return shutdown_timeout;
3680 return VCalcTimeout(ats, vol_opts.offline_timeout);
3684 #else /* AFS_PTHREAD_ENV */
3686 /* Waiting a certain amount of time for offlining volumes is not supported
3687 * for LWP due to a lack of primitives. So, we never time out */
3688 # define VTimedOut(x) (0)
3689 # define VOfflineTimeout(x) (NULL)
3691 #endif /* !AFS_PTHREAD_ENV */
3699 retVal = VHold_r(vp);
3706 VIsGoingOffline_r(struct Volume *vp)
3710 if (vp->goingOffline) {
3711 if (vp->specialStatus) {
3712 code = vp->specialStatus;
3713 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3724 * Tell the caller if a volume is waiting to go offline.
3726 * @param[in] vp The volume we want to know about
3728 * @return volume status
3729 * @retval 0 volume is not waiting to go offline, go ahead and use it
3730 * @retval nonzero volume is waiting to offline, and give the returned code
3731 * as an error to anyone accessing the volume
3733 * @pre VOL_LOCK is NOT held
3734 * @pre caller holds a heavyweight reference on vp
3737 VIsGoingOffline(struct Volume *vp)
3742 code = VIsGoingOffline_r(vp);
3749 * Register an RX call with a volume.
3751 * @param[inout] ec Error code; if unset when passed in, may be set if
3752 * the volume starts going offline
3753 * @param[out] client_ec @see GetVolume
3754 * @param[in] vp Volume struct
3755 * @param[in] cbv VCallByVol struct containing the RX call to register
3757 * @pre VOL_LOCK held
3758 * @pre caller holds heavy ref on vp
3763 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3766 #ifdef AFS_DEMAND_ATTACH_FS
3768 /* just in case the volume started going offline after we got the
3769 * reference to it... otherwise, if the volume started going
3770 * offline right at the end of GetVolume(), we might race with the
3771 * RX call scanner, and return success and add our cbv to the
3772 * rx_call_list _after_ the scanner has scanned the list. */
3773 *ec = VIsGoingOffline_r(vp);
3779 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3780 VWaitStateChange_r(vp);
3782 #endif /* AFS_DEMAND_ATTACH_FS */
3784 queue_Prepend(&vp->rx_call_list, cbv);
3789 * Deregister an RX call with a volume.
3791 * @param[in] vp Volume struct
3792 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3794 * @pre VOL_LOCK held
3795 * @pre caller holds heavy ref on vp
3800 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3802 if (cbv && queue_IsOnQueue(cbv)) {
3803 #ifdef AFS_DEMAND_ATTACH_FS
3804 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3805 VWaitStateChange_r(vp);
3807 #endif /* AFS_DEMAND_ATTACH_FS */
3813 /***************************************************/
3814 /* get and put volume routines */
3815 /***************************************************/
3818 * put back a heavyweight reference to a volume object.
3820 * @param[in] vp volume object pointer
3822 * @pre VOL_LOCK held
3824 * @post heavyweight volume reference put back.
3825 * depending on state, volume may have been taken offline,
3826 * detached, salvaged, freed, etc.
3828 * @internal volume package internal use only
3831 VPutVolume_r(Volume * vp)
3833 osi_Assert(--vp->nUsers >= 0);
3834 if (vp->nUsers == 0) {
3836 ReleaseVolumeHeader(vp->header);
3837 #ifdef AFS_DEMAND_ATTACH_FS
3838 if (!VCheckDetach(vp)) {
3842 #else /* AFS_DEMAND_ATTACH_FS */
3844 #endif /* AFS_DEMAND_ATTACH_FS */
3849 VPutVolume(Volume * vp)
3857 * Puts a volume reference obtained with VGetVolumeWithCall.
3859 * @param[in] vp Volume struct
3860 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3862 * @pre VOL_LOCK is NOT held
3865 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3868 VDeregisterCall_r(vp, cbv);
3873 /* Get a pointer to an attached volume. The pointer is returned regardless
3874 of whether or not the volume is in service or on/off line. An error
3875 code, however, is returned with an indication of the volume's status */
3877 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3881 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3887 * Get a volume reference associated with an RX call.
3889 * @param[out] ec @see GetVolume
3890 * @param[out] client_ec @see GetVolume
3891 * @param[in] volumeId @see GetVolume
3892 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3893 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3894 * with an error if the volume is going offline.
3895 * @param[in] cbv Contains an RX call to be associated with this volume
3896 * reference. This call may be interrupted if the volume is
3897 * requested to go offline while we hold a ref on it. Give NULL
3898 * to not associate an RX call with this reference.
3900 * @return @see GetVolume
3902 * @note for LWP builds, ts must be NULL
3904 * @note A reference obtained with this function MUST be put back with
3905 * VPutVolumeWithCall
3908 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3909 const struct timespec *ts, struct VCallByVol *cbv)
3913 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3914 VRegisterCall_r(ec, client_ec, retVal, cbv);
3920 VGetVolume_r(Error * ec, VolId volumeId)
3922 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3925 /* try to get a volume we've previously looked up */
3926 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3928 VGetVolumeByVp_r(Error * ec, Volume * vp)
3930 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3934 * private interface for getting a volume handle
3936 * @param[out] ec error code (0 if no error)
3937 * @param[out] client_ec wire error code to be given to clients
3938 * @param[in] volumeId ID of the volume we want
3939 * @param[in] hint optional hint for hash lookups, or NULL
3940 * @param[in] timeout absolute deadline for waiting for the volume to go
3941 * offline, if it is going offline. NULL to wait forever.
3943 * @return a volume handle for the specified volume
3944 * @retval NULL an error occurred, or the volume is in such a state that
3945 * we cannot load a header or return any volume struct
3947 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3949 * @note 'timeout' is only checked if the volume is actually going offline; so
3950 * if you pass timeout->tv_sec = 0, this will exhibit typical
3951 * nonblocking behavior.
3953 * @note for LWP builds, 'timeout' must be NULL
3956 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3957 const struct timespec *timeout)
3960 /* pull this profiling/debugging code out of regular builds */
3962 #define VGET_CTR_INC(x) x++
3963 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3964 0, V7 = 0, V8 = 0, V9 = 0;
3965 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3967 #define VGET_CTR_INC(x)
3969 #ifdef AFS_DEMAND_ATTACH_FS
3970 Volume *avp, * rvp = hint;
3974 * if VInit is zero, the volume package dynamic
3975 * data structures have not been initialized yet,
3976 * and we must immediately return an error
3982 *client_ec = VOFFLINE;
3987 #ifdef AFS_DEMAND_ATTACH_FS
3989 VCreateReservation_r(rvp);
3991 #endif /* AFS_DEMAND_ATTACH_FS */
3999 vp = VLookupVolume_r(ec, volumeId, vp);
4005 #ifdef AFS_DEMAND_ATTACH_FS
4006 if (rvp && (rvp != vp)) {
4007 /* break reservation on old vp */
4008 VCancelReservation_r(rvp);
4011 #endif /* AFS_DEMAND_ATTACH_FS */
4017 /* Until we have reached an initialization level of 2
4018 * we don't know whether this volume exists or not.
4019 * We can't sleep and retry later because before a volume
4020 * is attached, the caller tries to get it first. Just
4021 * return VOFFLINE and the caller can choose whether to
4022 * retry the command or not. */
4032 IncUInt64(&VStats.hdr_gets);
4034 #ifdef AFS_DEMAND_ATTACH_FS
4035 /* block if someone else is performing an exclusive op on this volume */
4038 VCreateReservation_r(rvp);
4040 VWaitExclusiveState_r(vp);
4042 /* short circuit with VNOVOL in the following circumstances:
4045 * - VOL_STATE_SHUTTING_DOWN
4047 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4048 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4055 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4056 * VNOVOL for VOL_STATE_DELETED
4058 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4059 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4060 (V_attachState(vp) == VOL_STATE_DELETED)) {
4061 if (vp->specialStatus) {
4062 *ec = vp->specialStatus;
4063 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4072 /* allowable states:
4079 if (vp->salvage.requested) {
4080 VUpdateSalvagePriority_r(vp);
4083 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4084 if (vp->specialStatus) {
4085 *ec = vp->specialStatus;
4089 avp = VAttachVolumeByVp_r(ec, vp, 0);
4092 /* VAttachVolumeByVp_r can return a pointer
4093 * != the vp passed to it under certain
4094 * conditions; make sure we don't leak
4095 * reservations if that happens */
4097 VCancelReservation_r(rvp);
4099 VCreateReservation_r(rvp);
4110 if (vp->specialStatus) {
4111 *ec = vp->specialStatus;
4116 if (vp->specialStatus) {
4117 *ec = vp->specialStatus;
4130 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4132 /* see CheckVnode() in afsfileprocs.c for an explanation
4133 * of this error code logic */
4134 afs_uint32 now = FT_ApproxTime();
4135 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4138 *client_ec = VRESTARTING;
4146 if (VIsErrorState(V_attachState(vp))) {
4147 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4148 * it, or transition it out of that state */
4157 * this test MUST happen after VAttachVolymeByVp, so we have no
4158 * conflicting vol op. (attach2 would have errored out if we had one;
4159 * specifically attach_check_vop must have detected a conflicting vop)
4161 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4163 #endif /* AFS_DEMAND_ATTACH_FS */
4165 LoadVolumeHeader(ec, vp);
4168 /* Only log the error if it was a totally unexpected error. Simply
4169 * a missing inode is likely to be caused by the volume being deleted */
4170 if (errno != ENXIO || LogLevel)
4171 Log("Volume %u: couldn't reread volume header\n",
4173 #ifdef AFS_DEMAND_ATTACH_FS
4174 if (VCanScheduleSalvage()) {
4175 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4180 #else /* AFS_DEMAND_ATTACH_FS */
4183 #endif /* AFS_DEMAND_ATTACH_FS */
4188 if (vp->shuttingDown) {
4195 if (programType == fileServer) {
4197 if (vp->goingOffline) {
4198 if (timeout && VTimedOut(timeout)) {
4199 /* we've timed out; don't wait for the vol */
4202 #ifdef AFS_DEMAND_ATTACH_FS
4203 /* wait for the volume to go offline */
4204 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4205 VTimedWaitStateChange_r(vp, timeout, NULL);
4207 #elif defined(AFS_PTHREAD_ENV)
4208 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4209 #else /* AFS_PTHREAD_ENV */
4210 /* LWP has no timed wait, so the caller better not be
4212 osi_Assert(!timeout);
4213 LWP_WaitProcess(VPutVolume);
4214 #endif /* AFS_PTHREAD_ENV */
4218 if (vp->specialStatus) {
4220 *ec = vp->specialStatus;
4221 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4224 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4235 #ifdef AFS_DEMAND_ATTACH_FS
4236 /* if no error, bump nUsers */
4239 VLRU_UpdateAccess_r(vp);
4242 VCancelReservation_r(rvp);
4245 if (client_ec && !*client_ec) {
4248 #else /* AFS_DEMAND_ATTACH_FS */
4249 /* if no error, bump nUsers */
4256 #endif /* AFS_DEMAND_ATTACH_FS */
4259 osi_Assert(vp || *ec);
4264 /***************************************************/
4265 /* Volume offline/detach routines */
4266 /***************************************************/
4268 /* caller MUST hold a heavyweight ref on vp */
4269 #ifdef AFS_DEMAND_ATTACH_FS
4271 VTakeOffline_r(Volume * vp)
4275 osi_Assert(vp->nUsers > 0);
4276 osi_Assert(programType == fileServer);
4278 VCreateReservation_r(vp);
4279 VWaitExclusiveState_r(vp);
4281 vp->goingOffline = 1;
4282 V_needsSalvaged(vp) = 1;
4284 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4285 VCancelReservation_r(vp);
4287 #else /* AFS_DEMAND_ATTACH_FS */
4289 VTakeOffline_r(Volume * vp)
4291 osi_Assert(vp->nUsers > 0);
4292 osi_Assert(programType == fileServer);
4294 vp->goingOffline = 1;
4295 V_needsSalvaged(vp) = 1;
4297 #endif /* AFS_DEMAND_ATTACH_FS */
4300 VTakeOffline(Volume * vp)
4308 * force a volume offline.
4310 * @param[in] vp volume object pointer
4311 * @param[in] flags flags (see note below)
4313 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4314 * used when VUpdateVolume_r needs to call VForceOffline_r
4315 * (which in turn would normally call VUpdateVolume_r)
4317 * @see VUpdateVolume_r
4319 * @pre VOL_LOCK must be held.
4320 * for DAFS, caller must hold ref.
4322 * @note for DAFS, it _is safe_ to call this function from an
4325 * @post needsSalvaged flag is set.
4326 * for DAFS, salvage is requested.
4327 * no further references to the volume through the volume
4328 * package will be honored.
4329 * all file descriptor and vnode caches are invalidated.
4331 * @warning this is a heavy-handed interface. it results in
4332 * a volume going offline regardless of the current
4333 * reference count state.
4335 * @internal volume package internal use only
4338 VForceOffline_r(Volume * vp, int flags)
4342 #ifdef AFS_DEMAND_ATTACH_FS
4343 VChangeState_r(vp, VOL_STATE_ERROR);
4348 strcpy(V_offlineMessage(vp),
4349 "Forced offline due to internal error: volume needs to be salvaged");
4350 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4353 vp->goingOffline = 0;
4354 V_needsSalvaged(vp) = 1;
4355 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4356 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4359 #ifdef AFS_DEMAND_ATTACH_FS
4360 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4361 #endif /* AFS_DEMAND_ATTACH_FS */
4363 #ifdef AFS_PTHREAD_ENV
4364 CV_BROADCAST(&vol_put_volume_cond);
4365 #else /* AFS_PTHREAD_ENV */
4366 LWP_NoYieldSignal(VPutVolume);
4367 #endif /* AFS_PTHREAD_ENV */
4369 VReleaseVolumeHandles_r(vp);
4373 * force a volume offline.
4375 * @param[in] vp volume object pointer
4377 * @see VForceOffline_r
4380 VForceOffline(Volume * vp)
4383 VForceOffline_r(vp, 0);
4388 * Iterate over the RX calls associated with a volume, and interrupt them.
4390 * @param[in] vp The volume whose RX calls we want to scan
4392 * @pre VOL_LOCK held
4395 VScanCalls_r(struct Volume *vp)
4397 struct VCallByVol *cbv, *ncbv;
4399 #ifdef AFS_DEMAND_ATTACH_FS
4400 VolState state_save;
4403 if (queue_IsEmpty(&vp->rx_call_list))
4404 return; /* no calls to interrupt */
4405 if (!vol_opts.interrupt_rxcall)
4406 return; /* we have no function with which to interrupt calls */
4407 err = VIsGoingOffline_r(vp);
4409 return; /* we're not going offline anymore */
4411 #ifdef AFS_DEMAND_ATTACH_FS
4412 VWaitExclusiveState_r(vp);
4413 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4415 #endif /* AFS_DEMAND_ATTACH_FS */
4417 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4419 struct rx_peer *peer;
4421 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4423 Log("Offlining volume %lu while client %s:%u is trying to read "
4424 "from it; kicking client off with error %ld\n",
4425 (long unsigned) vp->hashid,
4426 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4427 (unsigned) ntohs(rx_PortOf(peer)),
4430 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4433 #ifdef AFS_DEMAND_ATTACH_FS
4435 VChangeState_r(vp, state_save);
4436 #endif /* AFS_DEMAND_ATTACH_FS */
4439 #ifdef AFS_DEMAND_ATTACH_FS
4441 * Wait for a vp to go offline.
4443 * @param[out] ec 1 if a salvage on the volume has been requested and
4444 * salvok == 0, 0 otherwise
4445 * @param[in] vp The volume to wait for
4446 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4447 * has been requested to salvage. Otherwise we keep waiting
4448 * until the volume has gone offline.
4450 * @pre VOL_LOCK held
4451 * @pre caller holds a lightweight ref on vp
4456 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4458 struct timespec timeout_ts;
4459 const struct timespec *ts;
4462 ts = VOfflineTimeout(&timeout_ts);
4466 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4467 if (!salvok && vp->salvage.requested) {
4471 VTimedWaitStateChange_r(vp, ts, &timedout);
4474 /* we didn't time out, so the volume must be offline, so we're done */
4478 /* If we got here, we timed out waiting for the volume to go offline.
4479 * Kick off the accessing RX calls and wait again */
4483 while (!VIsOfflineState(V_attachState(vp))) {
4484 if (!salvok && vp->salvage.requested) {
4489 VWaitStateChange_r(vp);
4493 #else /* AFS_DEMAND_ATTACH_FS */
4496 * Wait for a volume to go offline.
4498 * @pre VOL_LOCK held
4500 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4503 VWaitForOffline_r(Error *ec, VolumeId volid)
4506 const struct timespec *ts;
4507 #ifdef AFS_PTHREAD_ENV
4508 struct timespec timeout_ts;
4511 ts = VOfflineTimeout(&timeout_ts);
4513 vp = GetVolume(ec, NULL, volid, NULL, ts);
4515 /* error occurred so bad that we can't even get a vp; we have no
4516 * information on the vol so we don't know whether to wait, so just
4520 if (!VIsGoingOffline_r(vp)) {
4521 /* volume is no longer going offline, so we're done */
4526 /* If we got here, we timed out waiting for the volume to go offline.
4527 * Kick off the accessing RX calls and wait again */
4533 vp = VGetVolume_r(ec, volid);
4535 /* In case it was reattached... */
4539 #endif /* !AFS_DEMAND_ATTACH_FS */
4541 /* The opposite of VAttachVolume. The volume header is written to disk, with
4542 the inUse bit turned off. A copy of the header is maintained in memory,
4543 however (which is why this is VOffline, not VDetach).
4546 VOffline_r(Volume * vp, char *message)
4549 #ifndef AFS_DEMAND_ATTACH_FS
4550 VolumeId vid = V_id(vp);
4553 osi_Assert(programType != volumeUtility && programType != volumeServer);
4558 if (V_offlineMessage(vp)[0] == '\0')
4559 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4560 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4562 vp->goingOffline = 1;
4563 #ifdef AFS_DEMAND_ATTACH_FS
4564 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4565 VCreateReservation_r(vp);
4567 VWaitForOfflineByVp_r(&error, vp, 1);
4568 VCancelReservation_r(vp);
4569 #else /* AFS_DEMAND_ATTACH_FS */
4571 VWaitForOffline_r(&error, vid);
4572 #endif /* AFS_DEMAND_ATTACH_FS */
4575 #ifdef AFS_DEMAND_ATTACH_FS
4577 * Take a volume offline in order to perform a volume operation.
4579 * @param[inout] ec address in which to store error code
4580 * @param[in] vp volume object pointer
4581 * @param[in] message volume offline status message
4584 * - VOL_LOCK is held
4585 * - caller MUST hold a heavyweight ref on vp
4588 * - volume is taken offline
4589 * - if possible, volume operation is promoted to running state
4590 * - on failure, *ec is set to nonzero
4592 * @note Although this function does not return any value, it may
4593 * still fail to promote our pending volume operation to
4594 * a running state. Any caller MUST check the value of *ec,
4595 * and MUST NOT blindly assume success.
4597 * @warning if the caller does not hold a lightweight ref on vp,
4598 * then it MUST NOT reference vp after this function
4599 * returns to the caller.
4601 * @internal volume package internal use only
4604 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4607 osi_Assert(vp->pending_vol_op);
4613 if (V_offlineMessage(vp)[0] == '\0')
4614 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4615 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4617 vp->goingOffline = 1;
4618 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4619 VCreateReservation_r(vp);
4622 if (vp->pending_vol_op->com.programType != salvageServer) {
4623 /* do not give corrupted volumes to the volserver */
4628 VWaitForOfflineByVp_r(ec, vp, salvok);
4630 VCancelReservation_r(vp);
4632 #endif /* AFS_DEMAND_ATTACH_FS */
4635 VOffline(Volume * vp, char *message)
4638 VOffline_r(vp, message);
4642 /* This gets used for the most part by utility routines that don't want
4643 * to keep all the volume headers around. Generally, the file server won't
4644 * call this routine, because then the offline message in the volume header
4645 * (or other information) won't be available to clients. For NAMEI, also
4646 * close the file handles. However, the fileserver does call this during
4647 * an attach following a volume operation.
4650 VDetachVolume_r(Error * ec, Volume * vp)
4652 #ifdef FSSYNC_BUILD_CLIENT
4654 struct DiskPartition64 *tpartp;
4655 int notifyServer = 0;
4656 int useDone = FSYNC_VOL_ON;
4658 if (VCanUseFSSYNC()) {
4659 notifyServer = vp->needsPutBack;
4660 if (V_destroyMe(vp) == DESTROY_ME)
4661 useDone = FSYNC_VOL_LEAVE_OFF;
4662 # ifdef AFS_DEMAND_ATTACH_FS
4663 else if (!V_blessed(vp) || !V_inService(vp))
4664 useDone = FSYNC_VOL_LEAVE_OFF;
4667 # ifdef AFS_DEMAND_ATTACH_FS
4668 if (V_needsSalvaged(vp)) {
4670 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4673 tpartp = vp->partition;
4675 #endif /* FSSYNC_BUILD_CLIENT */
4677 *ec = 0; /* always "succeeds" */
4678 DeleteVolumeFromHashTable(vp);
4679 vp->shuttingDown = 1;
4680 #ifdef AFS_DEMAND_ATTACH_FS
4681 DeleteVolumeFromVByPList_r(vp);
4683 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4685 if (programType != fileServer)
4687 #endif /* AFS_DEMAND_ATTACH_FS */
4689 /* Will be detached sometime in the future--this is OK since volume is offline */
4691 /* XXX the following code should really be moved to VCheckDetach() since the volume
4692 * is not technically detached until the refcounts reach zero
4694 #ifdef FSSYNC_BUILD_CLIENT
4695 if (VCanUseFSSYNC() && notifyServer) {
4696 if (notifyServer == VOL_PUTBACK_DELETE) {
4697 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4698 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4699 * to signify a deleted volume. */
4700 useDone = FSYNC_VOL_DONE;
4703 * Note: The server is not notified in the case of a bogus volume
4704 * explicitly to make it possible to create a volume, do a partial
4705 * restore, then abort the operation without ever putting the volume
4706 * online. This is essential in the case of a volume move operation
4707 * between two partitions on the same server. In that case, there
4708 * would be two instances of the same volume, one of them bogus,
4709 * which the file server would attempt to put on line
4711 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4712 /* XXX this code path is only hit by volume utilities, thus
4713 * V_BreakVolumeCallbacks will always be NULL. if we really
4714 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4716 /* Dettaching it so break all callbacks on it */
4717 if (V_BreakVolumeCallbacks) {
4718 Log("volume %u detached; breaking all call backs\n", volume);
4719 (*V_BreakVolumeCallbacks) (volume);
4723 #endif /* FSSYNC_BUILD_CLIENT */
4727 VDetachVolume(Error * ec, Volume * vp)
4730 VDetachVolume_r(ec, vp);
4735 /***************************************************/
4736 /* Volume fd/inode handle closing routines */
4737 /***************************************************/
4739 /* For VDetachVolume, we close all cached file descriptors, but keep
4740 * the Inode handles in case we need to read from a busy volume.
4742 /* for demand attach, caller MUST hold ref count on vp */
4744 VCloseVolumeHandles_r(Volume * vp)
4746 #ifdef AFS_DEMAND_ATTACH_FS
4747 VolState state_save;
4749 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4754 DFlushVolume(vp->hashid);
4756 #ifdef AFS_DEMAND_ATTACH_FS
4760 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4761 VCloseVnodeFiles_r(vp);
4763 #ifdef AFS_DEMAND_ATTACH_FS
4767 /* Too time consuming and unnecessary for the volserver */
4768 if (programType == fileServer) {
4769 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4770 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4771 IH_CONDSYNC(vp->diskDataHandle);
4773 IH_CONDSYNC(vp->linkHandle);
4774 #endif /* AFS_NT40_ENV */
4777 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4778 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4779 IH_REALLYCLOSE(vp->diskDataHandle);
4780 IH_REALLYCLOSE(vp->linkHandle);
4782 #ifdef AFS_DEMAND_ATTACH_FS
4783 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4788 VChangeState_r(vp, state_save);
4792 /* For both VForceOffline and VOffline, we close all relevant handles.
4793 * For VOffline, if we re-attach the volume, the files may possible be
4794 * different than before.
4796 /* for demand attach, caller MUST hold a ref count on vp */
4798 VReleaseVolumeHandles_r(Volume * vp)
4800 #ifdef AFS_DEMAND_ATTACH_FS
4801 VolState state_save;
4803 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4808 DFlushVolume(vp->hashid);
4810 #ifdef AFS_DEMAND_ATTACH_FS
4814 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4816 #ifdef AFS_DEMAND_ATTACH_FS
4820 /* Too time consuming and unnecessary for the volserver */
4821 if (programType == fileServer) {
4822 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4823 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4824 IH_CONDSYNC(vp->diskDataHandle);
4826 IH_CONDSYNC(vp->linkHandle);
4827 #endif /* AFS_NT40_ENV */
4830 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4831 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4832 IH_RELEASE(vp->diskDataHandle);
4833 IH_RELEASE(vp->linkHandle);
4835 #ifdef AFS_DEMAND_ATTACH_FS
4836 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4841 VChangeState_r(vp, state_save);
4846 /***************************************************/
4847 /* Volume write and fsync routines */
4848 /***************************************************/
4851 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4853 #ifdef AFS_DEMAND_ATTACH_FS
4854 VolState state_save;
4856 if (flags & VOL_UPDATE_WAIT) {
4857 VCreateReservation_r(vp);
4858 VWaitExclusiveState_r(vp);
4863 if (programType == fileServer)
4865 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4866 200 : V_nextVnodeUnique(vp));
4868 #ifdef AFS_DEMAND_ATTACH_FS
4869 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4873 WriteVolumeHeader_r(ec, vp);
4875 #ifdef AFS_DEMAND_ATTACH_FS
4877 VChangeState_r(vp, state_save);
4878 if (flags & VOL_UPDATE_WAIT) {
4879 VCancelReservation_r(vp);
4884 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4885 V_id(vp), V_name(vp));
4886 /* try to update on-disk header,
4887 * while preventing infinite recursion */
4888 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4889 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4895 VUpdateVolume(Error * ec, Volume * vp)
4898 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4903 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4907 #ifdef AFS_DEMAND_ATTACH_FS
4908 VolState state_save;
4911 if (flags & VOL_SYNC_WAIT) {
4912 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4914 VUpdateVolume_r(ec, vp, 0);
4917 #ifdef AFS_DEMAND_ATTACH_FS
4918 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4921 fdP = IH_OPEN(V_diskDataHandle(vp));
4922 osi_Assert(fdP != NULL);
4923 code = FDH_SYNC(fdP);
4924 osi_Assert(code == 0);
4926 #ifdef AFS_DEMAND_ATTACH_FS
4928 VChangeState_r(vp, state_save);
4934 VSyncVolume(Error * ec, Volume * vp)
4937 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4942 /***************************************************/
4943 /* Volume dealloaction routines */
4944 /***************************************************/
4946 #ifdef AFS_DEMAND_ATTACH_FS
4948 FreeVolume(Volume * vp)
4950 /* free the heap space, iff it's safe.
4951 * otherwise, pull it out of the hash table, so it
4952 * will get deallocated when all refs to it go away */
4953 if (!VCheckFree(vp)) {
4954 DeleteVolumeFromHashTable(vp);
4955 DeleteVolumeFromVByPList_r(vp);
4957 /* make sure we invalidate the header cache entry */
4958 FreeVolumeHeader(vp);
4961 #endif /* AFS_DEMAND_ATTACH_FS */
4964 ReallyFreeVolume(Volume * vp)
4969 #ifdef AFS_DEMAND_ATTACH_FS
4971 VChangeState_r(vp, VOL_STATE_FREED);
4972 if (vp->pending_vol_op)
4973 free(vp->pending_vol_op);
4974 #endif /* AFS_DEMAND_ATTACH_FS */
4975 for (i = 0; i < nVNODECLASSES; i++)
4976 if (vp->vnodeIndex[i].bitmap)
4977 free(vp->vnodeIndex[i].bitmap);
4978 FreeVolumeHeader(vp);
4979 #ifndef AFS_DEMAND_ATTACH_FS
4980 DeleteVolumeFromHashTable(vp);
4981 #endif /* AFS_DEMAND_ATTACH_FS */
4985 /* check to see if we should shutdown this volume
4986 * returns 1 if volume was freed, 0 otherwise */
4987 #ifdef AFS_DEMAND_ATTACH_FS
4989 VCheckDetach(Volume * vp)
4994 if (vp->nUsers || vp->nWaiters)
4997 if (vp->shuttingDown) {
4999 if ((programType != fileServer) &&
5000 (V_inUse(vp) == programType) &&
5001 ((V_checkoutMode(vp) == V_VOLUPD) ||
5002 (V_checkoutMode(vp) == V_SECRETLY) ||
5003 ((V_checkoutMode(vp) == V_CLONE) &&
5004 (VolumeWriteable(vp))))) {
5006 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5008 Log("VCheckDetach: volume header update for volume %u "
5009 "failed with errno %d\n", vp->hashid, errno);
5012 VReleaseVolumeHandles_r(vp);
5014 ReallyFreeVolume(vp);
5015 if (programType == fileServer) {
5016 CV_BROADCAST(&vol_put_volume_cond);
5021 #else /* AFS_DEMAND_ATTACH_FS */
5023 VCheckDetach(Volume * vp)
5031 if (vp->shuttingDown) {
5033 if ((programType != fileServer) &&
5034 (V_inUse(vp) == programType) &&
5035 ((V_checkoutMode(vp) == V_VOLUPD) ||
5036 (V_checkoutMode(vp) == V_SECRETLY) ||
5037 ((V_checkoutMode(vp) == V_CLONE) &&
5038 (VolumeWriteable(vp))))) {
5040 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5042 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5046 VReleaseVolumeHandles_r(vp);
5047 ReallyFreeVolume(vp);
5048 if (programType == fileServer) {
5049 #if defined(AFS_PTHREAD_ENV)
5050 CV_BROADCAST(&vol_put_volume_cond);
5051 #else /* AFS_PTHREAD_ENV */
5052 LWP_NoYieldSignal(VPutVolume);
5053 #endif /* AFS_PTHREAD_ENV */
5058 #endif /* AFS_DEMAND_ATTACH_FS */
5060 /* check to see if we should offline this volume
5061 * return 1 if volume went offline, 0 otherwise */
5062 #ifdef AFS_DEMAND_ATTACH_FS
5064 VCheckOffline(Volume * vp)
5068 if (vp->goingOffline && !vp->nUsers) {
5070 osi_Assert(programType == fileServer);
5071 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5072 (V_attachState(vp) != VOL_STATE_FREED) &&
5073 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5074 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5075 (V_attachState(vp) != VOL_STATE_DELETED));
5079 * VOL_STATE_GOING_OFFLINE
5080 * VOL_STATE_SHUTTING_DOWN
5081 * VIsErrorState(V_attachState(vp))
5082 * VIsExclusiveState(V_attachState(vp))
5085 VCreateReservation_r(vp);
5086 VChangeState_r(vp, VOL_STATE_OFFLINING);
5089 /* must clear the goingOffline flag before we drop the glock */
5090 vp->goingOffline = 0;
5095 /* perform async operations */
5096 VUpdateVolume_r(&error, vp, 0);
5097 VCloseVolumeHandles_r(vp);
5100 if (V_offlineMessage(vp)[0]) {
5101 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5102 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5103 V_offlineMessage(vp));
5105 Log("VOffline: Volume %lu (%s) is now offline\n",
5106 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5110 /* invalidate the volume header cache entry */
5111 FreeVolumeHeader(vp);
5113 /* if nothing changed state to error or salvaging,
5114 * drop state to unattached */
5115 if (!VIsErrorState(V_attachState(vp))) {
5116 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5118 VCancelReservation_r(vp);
5119 /* no usage of vp is safe beyond this point */
5123 #else /* AFS_DEMAND_ATTACH_FS */
5125 VCheckOffline(Volume * vp)
5129 if (vp->goingOffline && !vp->nUsers) {
5131 osi_Assert(programType == fileServer);
5134 vp->goingOffline = 0;
5136 VUpdateVolume_r(&error, vp, 0);
5137 VCloseVolumeHandles_r(vp);
5139 if (V_offlineMessage(vp)[0]) {
5140 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5141 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5142 V_offlineMessage(vp));
5144 Log("VOffline: Volume %lu (%s) is now offline\n",
5145 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5148 FreeVolumeHeader(vp);
5149 #ifdef AFS_PTHREAD_ENV
5150 CV_BROADCAST(&vol_put_volume_cond);
5151 #else /* AFS_PTHREAD_ENV */
5152 LWP_NoYieldSignal(VPutVolume);
5153 #endif /* AFS_PTHREAD_ENV */
5157 #endif /* AFS_DEMAND_ATTACH_FS */
5159 /***************************************************/
5160 /* demand attach fs ref counting routines */
5161 /***************************************************/
5163 #ifdef AFS_DEMAND_ATTACH_FS
5164 /* the following two functions handle reference counting for
5165 * asynchronous operations on volume structs.
5167 * their purpose is to prevent a VDetachVolume or VShutdown
5168 * from free()ing the Volume struct during an async i/o op */
5170 /* register with the async volume op ref counter */
5171 /* VCreateReservation_r moved into inline code header because it
5172 * is now needed in vnode.c -- tkeiser 11/20/2007
5176 * decrement volume-package internal refcount.
5178 * @param vp volume object pointer
5180 * @internal volume package internal use only
5183 * @arg VOL_LOCK is held
5184 * @arg lightweight refcount held
5186 * @post volume waiters refcount is decremented; volume may
5187 * have been deallocated/shutdown/offlined/salvaged/
5188 * whatever during the process
5190 * @warning once you have tossed your last reference (you can acquire
5191 * lightweight refs recursively) it is NOT SAFE to reference
5192 * a volume object pointer ever again
5194 * @see VCreateReservation_r
5196 * @note DEMAND_ATTACH_FS only
5199 VCancelReservation_r(Volume * vp)
5201 osi_Assert(--vp->nWaiters >= 0);
5202 if (vp->nWaiters == 0) {
5204 if (!VCheckDetach(vp)) {
5211 /* check to see if we should free this volume now
5212 * return 1 if volume was freed, 0 otherwise */
5214 VCheckFree(Volume * vp)
5217 if ((vp->nUsers == 0) &&
5218 (vp->nWaiters == 0) &&
5219 !(V_attachFlags(vp) & (VOL_IN_HASH |
5223 ReallyFreeVolume(vp);
5228 #endif /* AFS_DEMAND_ATTACH_FS */
5231 /***************************************************/
5232 /* online volume operations routines */
5233 /***************************************************/
5235 #ifdef AFS_DEMAND_ATTACH_FS
5237 * register a volume operation on a given volume.
5239 * @param[in] vp volume object
5240 * @param[in] vopinfo volume operation info object
5242 * @pre VOL_LOCK is held
5244 * @post volume operation info object attached to volume object.
5245 * volume operation statistics updated.
5247 * @note by "attached" we mean a copy of the passed in object is made
5249 * @internal volume package internal use only
5252 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5254 FSSYNC_VolOp_info * info;
5256 /* attach a vol op info node to the volume struct */
5257 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5258 osi_Assert(info != NULL);
5259 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5260 vp->pending_vol_op = info;
5263 vp->stats.last_vol_op = FT_ApproxTime();
5264 vp->stats.vol_ops++;
5265 IncUInt64(&VStats.vol_ops);
5271 * deregister the volume operation attached to this volume.
5273 * @param[in] vp volume object pointer
5275 * @pre VOL_LOCK is held
5277 * @post the volume operation info object is detached from the volume object
5279 * @internal volume package internal use only
5282 VDeregisterVolOp_r(Volume * vp)
5284 if (vp->pending_vol_op) {
5285 free(vp->pending_vol_op);
5286 vp->pending_vol_op = NULL;
5290 #endif /* AFS_DEMAND_ATTACH_FS */
5293 * determine whether it is safe to leave a volume online during
5294 * the volume operation described by the vopinfo object.
5296 * @param[in] vp volume object
5297 * @param[in] vopinfo volume operation info object
5299 * @return whether it is safe to leave volume online
5300 * @retval 0 it is NOT SAFE to leave the volume online
5301 * @retval 1 it is safe to leave the volume online during the operation
5304 * @arg VOL_LOCK is held
5305 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5306 * this condition is met)
5308 * @internal volume package internal use only
5311 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5313 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5314 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5315 (vopinfo->com.reason == V_READONLY ||
5316 (!VolumeWriteable(vp) &&
5317 (vopinfo->com.reason == V_CLONE ||
5318 vopinfo->com.reason == V_DUMP)))));
5322 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5325 * @param[in] vp volume object
5326 * @param[in] vopinfo volume operation info object
5328 * @return whether it is safe to leave volume online
5329 * @retval 0 it is NOT SAFE to leave the volume online
5330 * @retval 1 it is safe to leave the volume online during the operation
5331 * @retval -1 unsure; volume header is required in order to know whether or
5332 * not is is safe to leave the volume online
5334 * @pre VOL_LOCK is held
5336 * @internal volume package internal use only
5339 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5341 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5342 * assume that we don't know VolumeWriteable; return -1 if the answer
5343 * depends on VolumeWriteable */
5345 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5348 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5349 vopinfo->com.reason == V_READONLY) {
5353 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5354 (vopinfo->com.reason == V_CLONE ||
5355 vopinfo->com.reason == V_DUMP)) {
5357 /* must know VolumeWriteable */
5364 * determine whether VBUSY should be set during this volume operation.
5366 * @param[in] vp volume object
5367 * @param[in] vopinfo volume operation info object
5369 * @return whether VBUSY should be set
5370 * @retval 0 VBUSY does NOT need to be set
5371 * @retval 1 VBUSY SHOULD be set
5373 * @pre VOL_LOCK is held
5375 * @internal volume package internal use only
5378 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5380 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5381 vopinfo->com.reason == FSYNC_SALVAGE) ||
5382 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5383 (vopinfo->com.reason == V_CLONE ||
5384 vopinfo->com.reason == V_DUMP)));
5388 /***************************************************/
5389 /* online salvager routines */
5390 /***************************************************/
5391 #if defined(AFS_DEMAND_ATTACH_FS)
5394 * offline a volume to let it be salvaged.
5396 * @param[in] vp Volume to offline
5398 * @return whether we offlined the volume successfully
5399 * @retval 0 volume was not offlined
5400 * @retval 1 volume is now offline
5402 * @note This is similar to VCheckOffline, but slightly different. We do not
5403 * deal with vp->goingOffline, and we try to avoid touching the volume
5404 * header except just to set needsSalvaged
5406 * @pre VOL_LOCK held
5407 * @pre vp->nUsers == 0
5408 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5411 VOfflineForSalvage_r(struct Volume *vp)
5415 VCreateReservation_r(vp);
5416 VWaitExclusiveState_r(vp);
5418 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5419 /* Someone's using the volume, or someone got to scheduling the salvage
5420 * before us. I don't think either of these should be possible, as we
5421 * should gain no new heavyweight references while we're trying to
5422 * salvage, but just to be sure... */
5423 VCancelReservation_r(vp);
5427 VChangeState_r(vp, VOL_STATE_OFFLINING);
5431 V_needsSalvaged(vp) = 1;
5432 /* ignore error; updating needsSalvaged is just best effort */
5433 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5435 VCloseVolumeHandles_r(vp);
5437 FreeVolumeHeader(vp);
5439 /* volume has been effectively offlined; we can mark it in the SALVAGING
5440 * state now, which lets FSSYNC give it away */
5441 VChangeState_r(vp, VOL_STATE_SALVAGING);
5443 VCancelReservation_r(vp);
5449 * check whether a salvage needs to be performed on this volume.
5451 * @param[in] vp pointer to volume object
5453 * @return status code
5454 * @retval 0 no salvage scheduled
5455 * @retval 1 a salvage has been scheduled with the salvageserver
5457 * @pre VOL_LOCK is held
5459 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5460 * then a salvage will be requested
5462 * @note this is one of the event handlers called by VCancelReservation_r
5464 * @note the caller must check if the volume needs to be freed after calling
5465 * this; the volume may not have any references or be on any lists after
5466 * we return, and we do not free it
5468 * @see VCancelReservation_r
5470 * @internal volume package internal use only.
5473 VCheckSalvage(Volume * vp)
5476 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5479 if (!vp->salvage.requested) {
5483 /* prevent recursion; some of the code below creates and removes
5484 * lightweight refs, which can call VCheckSalvage */
5485 if (vp->salvage.scheduling) {
5488 vp->salvage.scheduling = 1;
5490 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5491 if (!VOfflineForSalvage_r(vp)) {
5492 vp->salvage.scheduling = 0;
5497 if (vp->salvage.requested) {
5498 VScheduleSalvage_r(vp);
5501 vp->salvage.scheduling = 0;
5502 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5507 * request volume salvage.
5509 * @param[out] ec computed client error code
5510 * @param[in] vp volume object pointer
5511 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5512 * @param[in] flags see flags note below
5515 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5516 * not been fully attached
5518 * @pre VOL_LOCK is held.
5520 * @post volume state is changed.
5521 * for fileserver, salvage will be requested once refcount reaches zero.
5523 * @return operation status code
5524 * @retval 0 volume salvage will occur
5525 * @retval 1 volume salvage could not be scheduled
5529 * @note in the fileserver, this call does not synchronously schedule a volume
5530 * salvage. rather, it sets volume state so that when volume refcounts
5531 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5532 * nUsers and nWaiters must be zero.
5534 * @internal volume package internal use only.
5537 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5541 * for DAFS volume utilities that are not supposed to schedule salvages,
5542 * just transition to error state instead
5544 if (!VCanScheduleSalvage()) {
5545 VChangeState_r(vp, VOL_STATE_ERROR);
5550 if (programType != fileServer && !VCanUseFSSYNC()) {
5551 VChangeState_r(vp, VOL_STATE_ERROR);
5556 if (!vp->salvage.requested) {
5557 vp->salvage.requested = 1;
5558 vp->salvage.reason = reason;
5559 vp->stats.last_salvage = FT_ApproxTime();
5561 /* Note that it is not possible for us to reach this point if a
5562 * salvage is already running on this volume (even if the fileserver
5563 * was restarted during the salvage). If a salvage were running, the
5564 * salvager would have write-locked the volume header file, so when
5565 * we tried to lock the volume header, the lock would have failed,
5566 * and we would have failed during attachment prior to calling
5567 * VRequestSalvage. So we know that we can schedule salvages without
5568 * fear of a salvage already running for this volume. */
5570 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5572 /* if we don't need to offline the volume, we can go directly
5573 * to SALVAGING. SALVAGING says the volume is offline and is
5574 * either salvaging or ready to be handed to the salvager.
5575 * SALVAGE_REQ says that we want to salvage the volume, but we
5576 * are waiting for it to go offline first. */
5577 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5578 VChangeState_r(vp, VOL_STATE_SALVAGING);
5580 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5581 if (vp->nUsers == 0) {
5582 /* normally VOfflineForSalvage_r would be called from
5583 * PutVolume et al when nUsers reaches 0, but if
5584 * it's already 0, just do it ourselves, since PutVolume
5585 * isn't going to get called */
5586 VOfflineForSalvage_r(vp);
5589 /* If we are non-fileserver, we're telling the fileserver to
5590 * salvage the vol, so we don't need to give it back separately. */
5591 vp->needsPutBack = 0;
5595 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5597 /* make sure neither VScheduleSalvage_r nor
5598 * VUpdateSalvagePriority_r try to schedule another salvage */
5599 vp->salvage.requested = vp->salvage.scheduled = 0;
5601 VChangeState_r(vp, VOL_STATE_ERROR);
5610 * update salvageserver scheduling priority for a volume.
5612 * @param[in] vp pointer to volume object
5614 * @return operation status
5616 * @retval 1 request denied, or SALVSYNC communications failure
5618 * @pre VOL_LOCK is held.
5620 * @post in-core salvage priority counter is incremented. if at least
5621 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5622 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5623 * to update its priority queue. if no salvage is scheduled,
5624 * this function is a no-op.
5626 * @note DAFS fileserver only
5628 * @note this should be called whenever a VGetVolume fails due to a
5629 * pending salvage request
5631 * @todo should set exclusive state and drop glock around salvsync call
5633 * @internal volume package internal use only.
5636 VUpdateSalvagePriority_r(Volume * vp)
5640 #ifdef SALVSYNC_BUILD_CLIENT
5645 now = FT_ApproxTime();
5647 /* update the salvageserver priority queue occasionally so that
5648 * frequently requested volumes get moved to the head of the queue
5650 if ((vp->salvage.scheduled) &&
5651 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5652 code = SALVSYNC_SalvageVolume(vp->hashid,
5653 VPartitionPath(vp->partition),
5658 vp->stats.last_salvage_req = now;
5659 if (code != SYNC_OK) {
5663 #endif /* SALVSYNC_BUILD_CLIENT */
5668 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5670 /* A couple of little helper functions. These return true if we tried to
5671 * use this mechanism to schedule a salvage, false if we haven't tried.
5672 * If we did try a salvage then the results are contained in code.
5676 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5677 #ifdef SALVSYNC_BUILD_CLIENT
5678 if (VCanUseSALVSYNC()) {
5679 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5680 afs_printable_uint32_lu(vp->hashid), partName);
5682 /* can't use V_id() since there's no guarantee
5683 * we have the disk data header at this point */
5684 *code = SALVSYNC_SalvageVolume(vp->hashid,
5697 try_FSSYNC(Volume *vp, char *partName, int *code) {
5698 #ifdef FSSYNC_BUILD_CLIENT
5699 if (VCanUseFSSYNC()) {
5700 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5701 afs_printable_uint32_lu(vp->hashid), partName);
5704 * If we aren't the fileserver, tell the fileserver the volume
5705 * needs to be salvaged. We could directly tell the
5706 * salvageserver, but the fileserver keeps track of some stats
5707 * related to salvages, and handles some other salvage-related
5708 * complications for us.
5710 *code = FSYNC_VolOp(vp->hashid, partName,
5711 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5714 #endif /* FSSYNC_BUILD_CLIENT */
5719 * schedule a salvage with the salvage server or fileserver.
5721 * @param[in] vp pointer to volume object
5723 * @return operation status
5724 * @retval 0 salvage scheduled successfully
5725 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5728 * @arg VOL_LOCK is held.
5729 * @arg nUsers and nWaiters should be zero.
5731 * @post salvageserver or fileserver is sent a salvage request
5733 * @note If we are the fileserver, the request will be sent to the salvage
5734 * server over SALVSYNC. If we are not the fileserver, the request will be
5735 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5737 * @note the caller must check if the volume needs to be freed after calling
5738 * this; the volume may not have any references or be on any lists after
5739 * we return, and we do not free it
5743 * @internal volume package internal use only.
5746 VScheduleSalvage_r(Volume * vp)
5750 VolState state_save;
5751 VThreadOptions_t * thread_opts;
5754 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5756 if (vp->nWaiters || vp->nUsers) {
5760 /* prevent endless salvage,attach,salvage,attach,... loops */
5761 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5765 * don't perform salvsync ops on certain threads
5767 thread_opts = pthread_getspecific(VThread_key);
5768 if (thread_opts == NULL) {
5769 thread_opts = &VThread_defaults;
5771 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5775 if (vp->salvage.scheduled) {
5779 VCreateReservation_r(vp);
5780 VWaitExclusiveState_r(vp);
5783 * XXX the scheduling process should really be done asynchronously
5784 * to avoid fssync deadlocks
5786 if (!vp->salvage.scheduled) {
5787 /* if we haven't previously scheduled a salvage, do so now
5789 * set the volume to an exclusive state and drop the lock
5790 * around the SALVSYNC call
5792 strlcpy(partName, vp->partition->name, sizeof(partName));
5793 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5796 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5797 try_FSSYNC(vp, partName, &code));
5800 VChangeState_r(vp, state_save);
5802 if (code == SYNC_OK) {
5803 vp->salvage.scheduled = 1;
5804 vp->stats.last_salvage_req = FT_ApproxTime();
5805 if (VCanUseSALVSYNC()) {
5806 /* don't record these stats for non-fileservers; let the
5807 * fileserver take care of these */
5808 vp->stats.salvages++;
5809 IncUInt64(&VStats.salvages);
5814 case SYNC_BAD_COMMAND:
5815 case SYNC_COM_ERROR:
5818 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5819 "denied\n", afs_printable_uint32_lu(vp->hashid));
5822 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5823 "failed\n", afs_printable_uint32_lu(vp->hashid));
5826 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5827 "received unknown protocol error %d\n",
5828 afs_printable_uint32_lu(vp->hashid), code);
5832 if (VCanUseFSSYNC()) {
5833 VChangeState_r(vp, VOL_STATE_ERROR);
5838 /* NB: this is cancelling the reservation we obtained above, but we do
5839 * not call VCancelReservation_r, since that may trigger the vp dtor,
5840 * possibly free'ing the vp. We need to keep the vp around after
5841 * this, as the caller may reference vp without any refs. Instead, it
5842 * is the duty of the caller to inspect 'vp' after we return to see if
5843 * needs to be freed. */
5844 osi_Assert(--vp->nWaiters >= 0);
5847 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5849 #ifdef SALVSYNC_BUILD_CLIENT
5852 * connect to the salvageserver SYNC service.
5854 * @return operation status
5858 * @post connection to salvageserver SYNC service established
5860 * @see VConnectSALV_r
5861 * @see VDisconnectSALV
5862 * @see VReconnectSALV
5869 retVal = VConnectSALV_r();
5875 * connect to the salvageserver SYNC service.
5877 * @return operation status
5881 * @pre VOL_LOCK is held.
5883 * @post connection to salvageserver SYNC service established
5886 * @see VDisconnectSALV_r
5887 * @see VReconnectSALV_r
5888 * @see SALVSYNC_clientInit
5890 * @internal volume package internal use only.
5893 VConnectSALV_r(void)
5895 return SALVSYNC_clientInit();
5899 * disconnect from the salvageserver SYNC service.
5901 * @return operation status
5904 * @pre client should have a live connection to the salvageserver
5906 * @post connection to salvageserver SYNC service destroyed
5908 * @see VDisconnectSALV_r
5910 * @see VReconnectSALV
5913 VDisconnectSALV(void)
5916 VDisconnectSALV_r();
5922 * disconnect from the salvageserver SYNC service.
5924 * @return operation status
5928 * @arg VOL_LOCK is held.
5929 * @arg client should have a live connection to the salvageserver.
5931 * @post connection to salvageserver SYNC service destroyed
5933 * @see VDisconnectSALV
5934 * @see VConnectSALV_r
5935 * @see VReconnectSALV_r
5936 * @see SALVSYNC_clientFinis
5938 * @internal volume package internal use only.
5941 VDisconnectSALV_r(void)
5943 return SALVSYNC_clientFinis();
5947 * disconnect and then re-connect to the salvageserver SYNC service.
5949 * @return operation status
5953 * @pre client should have a live connection to the salvageserver
5955 * @post old connection is dropped, and a new one is established
5958 * @see VDisconnectSALV
5959 * @see VReconnectSALV_r
5962 VReconnectSALV(void)
5966 retVal = VReconnectSALV_r();
5972 * disconnect and then re-connect to the salvageserver SYNC service.
5974 * @return operation status
5979 * @arg VOL_LOCK is held.
5980 * @arg client should have a live connection to the salvageserver.
5982 * @post old connection is dropped, and a new one is established
5984 * @see VConnectSALV_r
5985 * @see VDisconnectSALV
5986 * @see VReconnectSALV
5987 * @see SALVSYNC_clientReconnect
5989 * @internal volume package internal use only.
5992 VReconnectSALV_r(void)
5994 return SALVSYNC_clientReconnect();
5996 #endif /* SALVSYNC_BUILD_CLIENT */
5997 #endif /* AFS_DEMAND_ATTACH_FS */
6000 /***************************************************/
6001 /* FSSYNC routines */
6002 /***************************************************/
6004 /* This must be called by any volume utility which needs to run while the
6005 file server is also running. This is separated from VInitVolumePackage2 so
6006 that a utility can fork--and each of the children can independently
6007 initialize communication with the file server */
6008 #ifdef FSSYNC_BUILD_CLIENT
6010 * connect to the fileserver SYNC service.
6012 * @return operation status
6017 * @arg VInit must equal 2.
6018 * @arg Program Type must not be fileserver or salvager.
6020 * @post connection to fileserver SYNC service established
6023 * @see VDisconnectFS
6024 * @see VChildProcReconnectFS
6031 retVal = VConnectFS_r();
6037 * connect to the fileserver SYNC service.
6039 * @return operation status
6044 * @arg VInit must equal 2.
6045 * @arg Program Type must not be fileserver or salvager.
6046 * @arg VOL_LOCK is held.
6048 * @post connection to fileserver SYNC service established
6051 * @see VDisconnectFS_r
6052 * @see VChildProcReconnectFS_r
6054 * @internal volume package internal use only.
6060 osi_Assert((VInit == 2) &&
6061 (programType != fileServer) &&
6062 (programType != salvager));
6063 rc = FSYNC_clientInit();
6071 * disconnect from the fileserver SYNC service.
6074 * @arg client should have a live connection to the fileserver.
6075 * @arg VOL_LOCK is held.
6076 * @arg Program Type must not be fileserver or salvager.
6078 * @post connection to fileserver SYNC service destroyed
6080 * @see VDisconnectFS
6082 * @see VChildProcReconnectFS_r
6084 * @internal volume package internal use only.
6087 VDisconnectFS_r(void)
6089 osi_Assert((programType != fileServer) &&
6090 (programType != salvager));
6091 FSYNC_clientFinis();
6096 * disconnect from the fileserver SYNC service.
6099 * @arg client should have a live connection to the fileserver.
6100 * @arg Program Type must not be fileserver or salvager.
6102 * @post connection to fileserver SYNC service destroyed
6104 * @see VDisconnectFS_r
6106 * @see VChildProcReconnectFS
6117 * connect to the fileserver SYNC service from a child process following a fork.
6119 * @return operation status
6124 * @arg VOL_LOCK is held.
6125 * @arg current FSYNC handle is shared with a parent process
6127 * @post current FSYNC handle is discarded and a new connection to the
6128 * fileserver SYNC service is established
6130 * @see VChildProcReconnectFS
6132 * @see VDisconnectFS_r
6134 * @internal volume package internal use only.
6137 VChildProcReconnectFS_r(void)
6139 return FSYNC_clientChildProcReconnect();
6143 * connect to the fileserver SYNC service from a child process following a fork.
6145 * @return operation status
6149 * @pre current FSYNC handle is shared with a parent process
6151 * @post current FSYNC handle is discarded and a new connection to the
6152 * fileserver SYNC service is established
6154 * @see VChildProcReconnectFS_r
6156 * @see VDisconnectFS
6159 VChildProcReconnectFS(void)
6163 ret = VChildProcReconnectFS_r();
6167 #endif /* FSSYNC_BUILD_CLIENT */
6170 /***************************************************/
6171 /* volume bitmap routines */
6172 /***************************************************/
6175 * Grow the bitmap by the defined increment
6178 VGrowBitmap(struct vnodeIndex *index)
6182 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6183 osi_Assert(bp != NULL);
6185 bp += index->bitmapSize;
6186 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6187 index->bitmapOffset = index->bitmapSize;
6188 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6194 * allocate a vnode bitmap number for the vnode
6196 * @param[out] ec error code
6197 * @param[in] vp volume object pointer
6198 * @param[in] index vnode index number for the vnode
6199 * @param[in] flags flag values described in note
6201 * @note for DAFS, flags parameter controls locking behavior.
6202 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6203 * will create a reservation and block on any other exclusive
6204 * operations. Otherwise, this function assumes the caller
6205 * already has exclusive access to vp, and we just change the
6208 * @pre VOL_LOCK held
6210 * @return bit number allocated
6216 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6217 struct vnodeIndex *index, int flags)
6221 #ifdef AFS_DEMAND_ATTACH_FS
6222 VolState state_save;
6223 #endif /* AFS_DEMAND_ATTACH_FS */
6227 /* This test is probably redundant */
6228 if (!VolumeWriteable(vp)) {
6229 *ec = (bit32) VREADONLY;
6233 #ifdef AFS_DEMAND_ATTACH_FS
6234 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6235 VCreateReservation_r(vp);
6236 VWaitExclusiveState_r(vp);
6238 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6239 #endif /* AFS_DEMAND_ATTACH_FS */
6242 if ((programType == fileServer) && !index->bitmap) {
6244 #ifndef AFS_DEMAND_ATTACH_FS
6245 /* demand attach fs uses the volume state to avoid races.
6246 * specialStatus field is not used at all */
6248 if (vp->specialStatus == VBUSY) {
6249 if (vp->goingOffline) { /* vos dump waiting for the volume to
6250 * go offline. We probably come here
6251 * from AddNewReadableResidency */
6254 while (vp->specialStatus == VBUSY) {
6255 #ifdef AFS_PTHREAD_ENV
6259 #else /* !AFS_PTHREAD_ENV */
6261 #endif /* !AFS_PTHREAD_ENV */
6265 #endif /* !AFS_DEMAND_ATTACH_FS */
6267 if (!index->bitmap) {
6268 #ifndef AFS_DEMAND_ATTACH_FS
6269 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6270 #endif /* AFS_DEMAND_ATTACH_FS */
6271 for (i = 0; i < nVNODECLASSES; i++) {
6272 VGetBitmap_r(ec, vp, i);
6274 #ifdef AFS_DEMAND_ATTACH_FS
6275 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6276 #else /* AFS_DEMAND_ATTACH_FS */
6277 DeleteVolumeFromHashTable(vp);
6278 vp->shuttingDown = 1; /* Let who has it free it. */
6279 vp->specialStatus = 0;
6280 #endif /* AFS_DEMAND_ATTACH_FS */
6284 #ifndef AFS_DEMAND_ATTACH_FS
6286 vp->specialStatus = 0; /* Allow others to have access. */
6287 #endif /* AFS_DEMAND_ATTACH_FS */
6290 #endif /* BITMAP_LATER */
6292 #ifdef AFS_DEMAND_ATTACH_FS
6294 #endif /* AFS_DEMAND_ATTACH_FS */
6295 bp = index->bitmap + index->bitmapOffset;
6296 ep = index->bitmap + index->bitmapSize;
6298 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6300 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6303 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6305 ret = ((bp - index->bitmap) * 8 + o);
6306 #ifdef AFS_DEMAND_ATTACH_FS
6308 #endif /* AFS_DEMAND_ATTACH_FS */
6311 bp += sizeof(bit32) /* i.e. 4 */ ;
6313 /* No bit map entry--must grow bitmap */
6317 ret = index->bitmapOffset * 8;
6318 #ifdef AFS_DEMAND_ATTACH_FS
6320 #endif /* AFS_DEMAND_ATTACH_FS */
6323 #ifdef AFS_DEMAND_ATTACH_FS
6324 VChangeState_r(vp, state_save);
6325 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6326 VCancelReservation_r(vp);
6328 #endif /* AFS_DEMAND_ATTACH_FS */
6333 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6337 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6343 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6344 unsigned bitNumber, int flags)
6346 unsigned int offset;
6350 #ifdef AFS_DEMAND_ATTACH_FS
6351 if (flags & VOL_FREE_BITMAP_WAIT) {
6352 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6353 * state, so ensure we're not in an exclusive volume state when we update
6355 VCreateReservation_r(vp);
6356 VWaitExclusiveState_r(vp);
6363 #endif /* BITMAP_LATER */
6365 offset = bitNumber >> 3;
6366 if (offset >= index->bitmapSize) {
6370 if (offset < index->bitmapOffset)
6371 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6372 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6375 #ifdef AFS_DEMAND_ATTACH_FS
6376 VCancelReservation_r(vp);
6378 return; /* make the compiler happy for non-DAFS */
6382 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6386 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6390 /* this function will drop the glock internally.
6391 * for old pthread fileservers, this is safe thanks to vbusy.
6393 * for demand attach fs, caller must have already called
6394 * VCreateReservation_r and VWaitExclusiveState_r */
6396 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6398 StreamHandle_t *file;
6399 afs_sfsize_t nVnodes, size;
6400 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6401 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6402 struct VnodeDiskObject *vnode;
6403 unsigned int unique = 0;
6407 #endif /* BITMAP_LATER */
6408 #ifdef AFS_DEMAND_ATTACH_FS
6409 VolState state_save;
6410 #endif /* AFS_DEMAND_ATTACH_FS */
6414 #ifdef AFS_DEMAND_ATTACH_FS
6415 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6416 #endif /* AFS_DEMAND_ATTACH_FS */
6419 fdP = IH_OPEN(vip->handle);
6420 osi_Assert(fdP != NULL);
6421 file = FDH_FDOPEN(fdP, "r");
6422 osi_Assert(file != NULL);
6423 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6424 osi_Assert(vnode != NULL);
6425 size = OS_SIZE(fdP->fd_fd);
6426 osi_Assert(size != -1);
6427 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6429 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6430 * a few files can be created in this volume,
6431 * the whole thing is rounded up to nearest 4
6432 * bytes, because the bit map allocator likes
6435 BitMap = (byte *) calloc(1, vip->bitmapSize);
6436 osi_Assert(BitMap != NULL);
6437 #else /* BITMAP_LATER */
6438 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6439 osi_Assert(vip->bitmap != NULL);
6440 vip->bitmapOffset = 0;
6441 #endif /* BITMAP_LATER */
6442 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6444 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6445 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6447 if (vnode->type != vNull) {
6448 if (vnode->vnodeMagic != vcp->magic) {
6449 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6454 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6455 #else /* BITMAP_LATER */
6456 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6457 #endif /* BITMAP_LATER */
6458 if (unique <= vnode->uniquifier)
6459 unique = vnode->uniquifier + 1;
6461 #ifndef AFS_PTHREAD_ENV
6462 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6465 #endif /* !AFS_PTHREAD_ENV */
6468 if (vp->nextVnodeUnique < unique) {
6469 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6472 /* Paranoia, partly justified--I think fclose after fdopen
6473 * doesn't seem to close fd. In any event, the documentation
6474 * doesn't specify, so it's safer to close it twice.
6482 /* There may have been a racing condition with some other thread, both
6483 * creating the bitmaps for this volume. If the other thread was faster
6484 * the pointer to bitmap should already be filled and we can free ours.
6486 if (vip->bitmap == NULL) {
6487 vip->bitmap = BitMap;
6488 vip->bitmapOffset = 0;
6491 #endif /* BITMAP_LATER */
6492 #ifdef AFS_DEMAND_ATTACH_FS
6493 VChangeState_r(vp, state_save);
6494 #endif /* AFS_DEMAND_ATTACH_FS */
6498 /***************************************************/
6499 /* Volume Path and Volume Number utility routines */
6500 /***************************************************/
6503 * find the first occurrence of a volume header file and return the path.
6505 * @param[out] ec outbound error code
6506 * @param[in] volumeId volume id to find
6507 * @param[out] partitionp pointer to disk partition path string
6508 * @param[out] namep pointer to volume header file name string
6510 * @post path to first occurrence of volume header is returned in partitionp
6511 * and namep, or ec is set accordingly.
6513 * @warning this function is NOT re-entrant -- partitionp and namep point to
6514 * static data segments
6516 * @note if a volume utility inadvertently leaves behind a stale volume header
6517 * on a vice partition, it is possible for callers to get the wrong one,
6518 * depending on the order of the disk partition linked list.
6522 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6524 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6525 char path[VMAXPATHLEN];
6527 struct DiskPartition64 *dp;
6530 name[0] = OS_DIRSEPC;
6531 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6532 afs_printable_uint32_lu(volumeId));
6533 for (dp = DiskPartitionList; dp; dp = dp->next) {
6534 struct afs_stat_st status;
6535 strcpy(path, VPartitionPath(dp));
6537 if (afs_stat(path, &status) == 0) {
6538 strcpy(partition, dp->name);
6545 *partitionp = *namep = NULL;
6547 *partitionp = partition;
6553 * extract a volume number from a volume header filename string.
6555 * @param[in] name volume header filename string
6557 * @return volume number
6559 * @note the string must be of the form VFORMAT. the only permissible
6560 * deviation is a leading OS_DIRSEPC character.
6565 VolumeNumber(char *name)
6567 if (*name == OS_DIRSEPC)
6569 return strtoul(name + 1, NULL, 10);
6573 * compute the volume header filename.
6575 * @param[in] volumeId
6577 * @return volume header filename
6579 * @post volume header filename string is constructed
6581 * @warning this function is NOT re-entrant -- the returned string is
6582 * stored in a static char array. see VolumeExternalName_r
6583 * for a re-entrant equivalent.
6585 * @see VolumeExternalName_r
6587 * @deprecated due to the above re-entrancy warning, this interface should
6588 * be considered deprecated. Please use VolumeExternalName_r
6592 VolumeExternalName(VolumeId volumeId)
6594 static char name[VMAXPATHLEN];
6595 snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6600 * compute the volume header filename.
6602 * @param[in] volumeId
6603 * @param[inout] name array in which to store filename
6604 * @param[in] len length of name array
6606 * @return result code from afs_snprintf
6608 * @see VolumeExternalName
6611 * @note re-entrant equivalent of VolumeExternalName
6614 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6616 return snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6620 /***************************************************/
6621 /* Volume Usage Statistics routines */
6622 /***************************************************/
6624 #define OneDay (86400) /* 24 hours' worth of seconds */
6627 Midnight(time_t t) {
6628 struct tm local, *l;
6631 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6632 l = localtime_r(&t, &local);
6638 /* the following is strictly speaking problematic on the
6639 switching day to daylight saving time, after the switch,
6640 as tm_isdst does not match. Similarly, on the looong day when
6641 switching back the OneDay check will not do what naively expected!
6642 The effects are minor, though, and more a matter of interpreting
6644 #ifndef AFS_PTHREAD_ENV
6647 local.tm_hour = local.tm_min=local.tm_sec = 0;
6648 midnight = mktime(&local);
6649 if (midnight != (time_t) -1) return(midnight);
6651 return( (t/OneDay)*OneDay );
6655 /*------------------------------------------------------------------------
6656 * [export] VAdjustVolumeStatistics
6659 * If we've passed midnight, we need to update all the day use
6660 * statistics as well as zeroing the detailed volume statistics
6661 * (if we are implementing them).
6664 * vp : Pointer to the volume structure describing the lucky
6665 * volume being considered for update.
6671 * Nothing interesting.
6675 *------------------------------------------------------------------------*/
6678 VAdjustVolumeStatistics_r(Volume * vp)
6680 unsigned int now = FT_ApproxTime();
6682 if (now - V_dayUseDate(vp) > OneDay) {
6685 ndays = (now - V_dayUseDate(vp)) / OneDay;
6686 for (i = 6; i > ndays - 1; i--)
6687 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6688 for (i = 0; i < ndays - 1 && i < 7; i++)
6689 V_weekUse(vp)[i] = 0;
6691 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6693 V_dayUseDate(vp) = Midnight(now);
6696 * All we need to do is bzero the entire VOL_STATS_BYTES of
6697 * the detailed volume statistics area.
6699 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6702 /*It's been more than a day of collection */
6704 * Always return happily.
6707 } /*VAdjustVolumeStatistics */
6710 VAdjustVolumeStatistics(Volume * vp)
6714 retVal = VAdjustVolumeStatistics_r(vp);
6720 VBumpVolumeUsage_r(Volume * vp)
6722 unsigned int now = FT_ApproxTime();
6723 V_accessDate(vp) = now;
6724 if (now - V_dayUseDate(vp) > OneDay)
6725 VAdjustVolumeStatistics_r(vp);
6727 * Save the volume header image to disk after a threshold of bumps to dayUse,
6728 * at most every usage_rate_limit seconds.
6731 vp->usage_bumps_outstanding++;
6732 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6733 && vp->usage_bumps_next_write <= now) {
6735 vp->usage_bumps_outstanding = 0;
6736 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6737 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6742 VBumpVolumeUsage(Volume * vp)
6745 VBumpVolumeUsage_r(vp);
6750 VSetDiskUsage_r(void)
6752 #ifndef AFS_DEMAND_ATTACH_FS
6753 static int FifteenMinuteCounter = 0;
6757 /* NOTE: Don't attempt to access the partitions list until the
6758 * initialization level indicates that all volumes are attached,
6759 * which implies that all partitions are initialized. */
6760 #ifdef AFS_PTHREAD_ENV
6761 VOL_CV_WAIT(&vol_vinit_cond);
6762 #else /* AFS_PTHREAD_ENV */
6764 #endif /* AFS_PTHREAD_ENV */
6767 VResetDiskUsage_r();
6769 #ifndef AFS_DEMAND_ATTACH_FS
6770 if (++FifteenMinuteCounter == 3) {
6771 FifteenMinuteCounter = 0;
6774 #endif /* !AFS_DEMAND_ATTACH_FS */
6786 /***************************************************/
6787 /* Volume Update List routines */
6788 /***************************************************/
6790 /* The number of minutes that a volume hasn't been updated before the
6791 * "Dont salvage" flag in the volume header will be turned on */
6792 #define SALVAGE_INTERVAL (10*60)
6797 * volume update list functionality has been moved into the VLRU
6798 * the DONT_SALVAGE flag is now set during VLRU demotion
6801 #ifndef AFS_DEMAND_ATTACH_FS
6802 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6803 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6804 static int updateSize = 0; /* number of entries possible */
6805 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6806 #endif /* !AFS_DEMAND_ATTACH_FS */
6809 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6812 vp->updateTime = FT_ApproxTime();
6813 if (V_dontSalvage(vp) == 0)
6815 V_dontSalvage(vp) = 0;
6816 VSyncVolume_r(ec, vp, 0);
6817 #ifdef AFS_DEMAND_ATTACH_FS
6818 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6819 #else /* !AFS_DEMAND_ATTACH_FS */
6822 if (UpdateList == NULL) {
6823 updateSize = UPDATE_LIST_SIZE;
6824 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6826 if (nUpdatedVolumes == updateSize) {
6828 if (updateSize > 524288) {
6829 Log("warning: there is likely a bug in the volume update scanner\n");
6832 UpdateList = realloc(UpdateList,
6833 sizeof(VolumeId) * updateSize);
6836 osi_Assert(UpdateList != NULL);
6837 UpdateList[nUpdatedVolumes++] = V_id(vp);
6838 #endif /* !AFS_DEMAND_ATTACH_FS */
6841 #ifndef AFS_DEMAND_ATTACH_FS
6843 VScanUpdateList(void)
6848 afs_uint32 now = FT_ApproxTime();
6849 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6850 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6852 UpdateList[i - gap] = UpdateList[i];
6854 /* XXX this routine needlessly messes up the Volume LRU by
6855 * breaking the LRU temporal-locality assumptions.....
6856 * we should use a special volume header allocator here */
6857 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6860 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6861 V_dontSalvage(vp) = DONT_SALVAGE;
6862 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6870 #ifndef AFS_PTHREAD_ENV
6872 #endif /* !AFS_PTHREAD_ENV */
6874 nUpdatedVolumes -= gap;
6876 #endif /* !AFS_DEMAND_ATTACH_FS */
6879 /***************************************************/
6880 /* Volume LRU routines */
6881 /***************************************************/
6886 * with demand attach fs, we attempt to soft detach(1)
6887 * volumes which have not been accessed in a long time
6888 * in order to speed up fileserver shutdown
6890 * (1) by soft detach we mean a process very similar
6891 * to VOffline, except the final state of the
6892 * Volume will be VOL_STATE_PREATTACHED, instead
6893 * of the usual VOL_STATE_UNATTACHED
6895 #ifdef AFS_DEMAND_ATTACH_FS
6897 /* implementation is reminiscent of a generational GC
6899 * queue 0 is newly attached volumes. this queue is
6900 * sorted by attach timestamp
6902 * queue 1 is volumes that have been around a bit
6903 * longer than queue 0. this queue is sorted by
6906 * queue 2 is volumes tha have been around the longest.
6907 * this queue is unsorted
6909 * queue 3 is volumes that have been marked as
6910 * candidates for soft detachment. this queue is
6913 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6914 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6917 * definition of a VLRU queue.
6920 volatile struct rx_queue q;
6927 * main VLRU data structure.
6930 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6933 /** time interval (in seconds) between promotion passes for
6934 * each young generation queue. */
6935 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6937 /** time interval (in seconds) between soft detach candidate
6938 * scans for each generation queue.
6940 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6941 * we perform a soft detach pass. */
6942 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6944 /* scheduler state */
6945 int next_idx; /**< next queue to receive attention */
6946 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6947 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6949 int scanner_state; /**< state of scanner thread */
6950 pthread_cond_t cv; /**< state transition CV */
6953 /** global VLRU state */
6954 static struct VLRU volume_LRU;
6957 * defined states for VLRU scanner thread.
6960 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6961 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6962 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6963 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6964 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6965 } vlru_thread_state_t;
6967 /* vlru disk data header stuff */
6968 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6969 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6971 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6972 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6975 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6976 * soft detachment. */
6977 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6979 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6980 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6982 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6983 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6985 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6986 static afs_uint32 VLRU_enabled = 1;
6988 /* queue synchronization routines */
6989 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6990 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6991 static void VLRU_Wait_r(struct VLRU_q * q);
6994 * set VLRU subsystem tunable parameters.
6996 * @param[in] option tunable option to modify
6997 * @param[in] val new value for tunable parameter
6999 * @pre @c VInitVolumePackage2 has not yet been called.
7001 * @post tunable parameter is modified
7005 * @note valid option parameters are:
7006 * @arg @c VLRU_SET_THRESH
7007 * set the period of inactivity after which
7008 * volumes are eligible for soft detachment
7009 * @arg @c VLRU_SET_INTERVAL
7010 * set the time interval between calls
7011 * to the volume LRU "garbage collector"
7012 * @arg @c VLRU_SET_MAX
7013 * set the max number of volumes to deallocate
7017 VLRU_SetOptions(int option, afs_uint32 val)
7019 if (option == VLRU_SET_THRESH) {
7020 VLRU_offline_thresh = val;
7021 } else if (option == VLRU_SET_INTERVAL) {
7022 VLRU_offline_interval = val;
7023 } else if (option == VLRU_SET_MAX) {
7024 VLRU_offline_max = val;
7025 } else if (option == VLRU_SET_ENABLED) {
7028 VLRU_ComputeConstants();
7032 * compute VLRU internal timing parameters.
7034 * @post VLRU scanner thread internal timing parameters are computed
7036 * @note computes internal timing parameters based upon user-modifiable
7037 * tunable parameters.
7041 * @internal volume package internal use only.
7044 VLRU_ComputeConstants(void)
7046 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7048 /* compute the candidate scan interval */
7049 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7051 /* compute the promotion intervals */
7052 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7053 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7056 /* compute the gen 0 scan interval */
7057 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7059 /* compute the gen 0 scan interval */
7060 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7065 * initialize VLRU subsystem.
7067 * @pre this function has not yet been called
7069 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7073 * @internal volume package internal use only.
7079 pthread_attr_t attrs;
7082 if (!VLRU_enabled) {
7083 Log("VLRU: disabled\n");
7087 /* initialize each of the VLRU queues */
7088 for (i = 0; i < VLRU_QUEUES; i++) {
7089 queue_Init(&volume_LRU.q[i]);
7090 volume_LRU.q[i].len = 0;
7091 volume_LRU.q[i].busy = 0;
7092 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7095 /* setup the timing constants */
7096 VLRU_ComputeConstants();
7098 /* XXX put inside LogLevel check? */
7099 Log("VLRU: starting scanner with the following configuration parameters:\n");
7100 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7101 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7102 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7103 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7104 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7105 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7107 /* start up the VLRU scanner */
7108 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7109 if (programType == fileServer) {
7110 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7111 osi_Assert(pthread_attr_init(&attrs) == 0);
7112 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7113 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7118 * initialize the VLRU-related fields of a newly allocated volume object.
7120 * @param[in] vp pointer to volume object
7123 * @arg @c VOL_LOCK is held.
7124 * @arg volume object is not on a VLRU queue.
7126 * @post VLRU fields are initialized to indicate that volume object is not
7127 * currently registered with the VLRU subsystem
7131 * @internal volume package interal use only.
7134 VLRU_Init_Node_r(Volume * vp)
7139 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7140 vp->vlru.idx = VLRU_QUEUE_INVALID;
7144 * add a volume object to a VLRU queue.
7146 * @param[in] vp pointer to volume object
7149 * @arg @c VOL_LOCK is held.
7150 * @arg caller MUST hold a lightweight ref on @p vp.
7151 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7153 * @post the volume object is added to the appropriate VLRU queue
7155 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7156 * then the volume is added to that queue. Otherwise, the value
7157 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7158 * volume is added to the NEW generation queue.
7160 * @note @c VOL_LOCK may be dropped internally
7162 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7163 * during the add operation, and is restored to the previous
7164 * state prior to return.
7168 * @internal volume package internal use only.
7171 VLRU_Add_r(Volume * vp)
7174 VolState state_save;
7179 if (queue_IsOnQueue(&vp->vlru))
7182 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7185 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7186 idx = VLRU_QUEUE_NEW;
7189 VLRU_Wait_r(&volume_LRU.q[idx]);
7191 /* repeat check since VLRU_Wait_r may have dropped
7193 if (queue_IsNotOnQueue(&vp->vlru)) {
7195 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7196 volume_LRU.q[idx].len++;
7197 V_attachFlags(vp) |= VOL_ON_VLRU;
7198 vp->stats.last_promote = FT_ApproxTime();
7201 VChangeState_r(vp, state_save);
7205 * delete a volume object from a VLRU queue.
7207 * @param[in] vp pointer to volume object
7210 * @arg @c VOL_LOCK is held.
7211 * @arg caller MUST hold a lightweight ref on @p vp.
7212 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7214 * @post volume object is removed from the VLRU queue
7216 * @note @c VOL_LOCK may be dropped internally
7220 * @todo We should probably set volume state to something exlcusive
7221 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7223 * @internal volume package internal use only.
7226 VLRU_Delete_r(Volume * vp)
7233 if (queue_IsNotOnQueue(&vp->vlru))
7239 if (idx == VLRU_QUEUE_INVALID)
7241 VLRU_Wait_r(&volume_LRU.q[idx]);
7242 } while (idx != vp->vlru.idx);
7244 /* now remove from the VLRU and update
7245 * the appropriate counter */
7246 queue_Remove(&vp->vlru);
7247 volume_LRU.q[idx].len--;
7248 vp->vlru.idx = VLRU_QUEUE_INVALID;
7249 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7253 * tell the VLRU subsystem that a volume was just accessed.
7255 * @param[in] vp pointer to volume object
7258 * @arg @c VOL_LOCK is held
7259 * @arg caller MUST hold a lightweight ref on @p vp
7260 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7262 * @post volume VLRU access statistics are updated. If the volume was on
7263 * the VLRU soft detach candidate queue, it is moved to the NEW
7266 * @note @c VOL_LOCK may be dropped internally
7270 * @internal volume package internal use only.
7273 VLRU_UpdateAccess_r(Volume * vp)
7275 Volume * rvp = NULL;
7280 if (queue_IsNotOnQueue(&vp->vlru))
7283 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7285 /* update the access timestamp */
7286 vp->stats.last_get = FT_ApproxTime();
7289 * if the volume is on the soft detach candidate
7290 * list, we need to safely move it back to a
7291 * regular generation. this has to be done
7292 * carefully so we don't race against the scanner
7296 /* if this volume is on the soft detach candidate queue,
7297 * then grab exclusive access to the necessary queues */
7298 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7300 VCreateReservation_r(rvp);
7302 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7303 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7304 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7305 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7308 /* make sure multiple threads don't race to update */
7309 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7310 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7314 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7315 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7316 VCancelReservation_r(rvp);
7321 * switch a volume between two VLRU queues.
7323 * @param[in] vp pointer to volume object
7324 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7325 * @param[in] append controls whether the volume will be appended or
7326 * prepended to the queue. A nonzero value means it will
7327 * be appended; zero means it will be prepended.
7329 * @pre The new (and old, if applicable) queue(s) must either be owned
7330 * exclusively by the calling thread for asynchronous manipulation,
7331 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7332 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7333 * for further details of the queue asynchronous processing mechanism.
7335 * @post If the volume object was already on a VLRU queue, it is
7336 * removed from the queue. Depending on the value of the append
7337 * parameter, the volume object is either appended or prepended
7338 * to the VLRU queue referenced by the new_idx parameter.
7342 * @see VLRU_BeginExclusive_r
7343 * @see VLRU_EndExclusive_r
7346 * @internal volume package internal use only.
7349 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7351 if (queue_IsNotOnQueue(&vp->vlru))
7354 queue_Remove(&vp->vlru);
7355 volume_LRU.q[vp->vlru.idx].len--;
7357 /* put the volume back on the correct generational queue */
7359 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7361 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7364 volume_LRU.q[new_idx].len++;
7365 vp->vlru.idx = new_idx;
7369 * VLRU background thread.
7371 * The VLRU Scanner Thread is responsible for periodically scanning through
7372 * each VLRU queue looking for volumes which should be moved to another
7373 * queue, or soft detached.
7375 * @param[in] args unused thread arguments parameter
7377 * @return unused thread return value
7378 * @retval NULL always
7380 * @internal volume package internal use only.
7383 VLRU_ScannerThread(void * args)
7385 afs_uint32 now, min_delay, delay;
7386 int i, min_idx, min_op, overdue, state;
7388 /* set t=0 for promotion cycle to be
7389 * fileserver startup */
7390 now = FT_ApproxTime();
7391 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7392 volume_LRU.last_promotion[i] = now;
7395 /* don't start the scanner until VLRU_offline_thresh
7396 * plus a small delay for VInitVolumePackage2 to finish
7399 sleep(VLRU_offline_thresh + 60);
7401 /* set t=0 for scan cycle to be now */
7402 now = FT_ApproxTime();
7403 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7404 volume_LRU.last_scan[i] = now;
7408 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7409 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7412 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7413 /* check to see if we've been asked to pause */
7414 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7415 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7416 CV_BROADCAST(&volume_LRU.cv);
7418 VOL_CV_WAIT(&volume_LRU.cv);
7419 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7422 /* scheduling can happen outside the glock */
7425 /* figure out what is next on the schedule */
7427 /* figure out a potential schedule for the new generation first */
7429 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7432 if (min_delay > volume_LRU.scan_interval[0]) {
7433 /* unsigned overflow -- we're overdue to run this scan */
7438 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7440 i = VLRU_QUEUE_CANDIDATE;
7441 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7442 if (delay < min_delay) {
7446 if (delay > volume_LRU.scan_interval[i]) {
7447 /* unsigned overflow -- we're overdue to run this scan */
7454 /* if we're still not overdue for something, figure out schedules for promotions */
7455 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7456 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7457 if (delay < min_delay) {
7462 if (delay > volume_LRU.promotion_interval[i]) {
7463 /* unsigned overflow -- we're overdue to run this promotion */
7472 /* sleep as needed */
7477 /* do whatever is next */
7480 VLRU_Promote_r(min_idx);
7481 VLRU_Demote_r(min_idx+1);
7483 VLRU_Scan_r(min_idx);
7485 now = FT_ApproxTime();
7488 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7490 /* signal that scanner is down */
7491 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7492 CV_BROADCAST(&volume_LRU.cv);
7498 * promote volumes from one VLRU generation to the next.
7500 * This routine scans a VLRU generation looking for volumes which are
7501 * eligible to be promoted to the next generation. All volumes which
7502 * meet the eligibility requirement are promoted.
7504 * Promotion eligibility is based upon meeting both of the following
7507 * @arg The volume has been accessed since the last promotion:
7508 * @c (vp->stats.last_get >= vp->stats.last_promote)
7509 * @arg The last promotion occurred at least
7510 * @c volume_LRU.promotion_interval[idx] seconds ago
7512 * As a performance optimization, promotions are "globbed". In other
7513 * words, we promote arbitrarily large contiguous sublists of elements
7516 * @param[in] idx VLRU queue index to scan
7520 * @internal VLRU internal use only.
7523 VLRU_Promote_r(int idx)
7525 int len, chaining, promote;
7526 afs_uint32 now, thresh;
7527 struct rx_queue *qp, *nqp;
7528 Volume * vp, *start = NULL, *end = NULL;
7530 /* get exclusive access to two chains, and drop the glock */
7531 VLRU_Wait_r(&volume_LRU.q[idx]);
7532 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7533 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7534 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7537 thresh = volume_LRU.promotion_interval[idx];
7538 now = FT_ApproxTime();
7541 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7542 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7543 promote = (((vp->stats.last_promote + thresh) <= now) &&
7544 (vp->stats.last_get >= vp->stats.last_promote));
7552 /* promote and prepend chain */
7553 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7567 /* promote and prepend */
7568 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7572 volume_LRU.q[idx].len -= len;
7573 volume_LRU.q[idx+1].len += len;
7576 /* release exclusive access to the two chains */
7578 volume_LRU.last_promotion[idx] = now;
7579 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7580 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7583 /* run the demotions */
7585 VLRU_Demote_r(int idx)
7588 int len, chaining, demote;
7589 afs_uint32 now, thresh;
7590 struct rx_queue *qp, *nqp;
7591 Volume * vp, *start = NULL, *end = NULL;
7592 Volume ** salv_flag_vec = NULL;
7593 int salv_vec_offset = 0;
7595 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7597 /* get exclusive access to two chains, and drop the glock */
7598 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7599 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7600 VLRU_Wait_r(&volume_LRU.q[idx]);
7601 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7604 /* no big deal if this allocation fails */
7605 if (volume_LRU.q[idx].len) {
7606 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7609 now = FT_ApproxTime();
7610 thresh = volume_LRU.promotion_interval[idx-1];
7613 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7614 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7615 demote = (((vp->stats.last_promote + thresh) <= now) &&
7616 (vp->stats.last_get < (now - thresh)));
7618 /* we now do volume update list DONT_SALVAGE flag setting during
7619 * demotion passes */
7620 if (salv_flag_vec &&
7621 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7623 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7624 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7625 salv_flag_vec[salv_vec_offset++] = vp;
7626 VCreateReservation_r(vp);
7635 /* demote and append chain */
7636 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7650 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7654 volume_LRU.q[idx].len -= len;
7655 volume_LRU.q[idx-1].len += len;
7658 /* release exclusive access to the two chains */
7660 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7661 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7663 /* now go back and set the DONT_SALVAGE flags as appropriate */
7664 if (salv_flag_vec) {
7666 for (i = 0; i < salv_vec_offset; i++) {
7667 vp = salv_flag_vec[i];
7668 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7669 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7670 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7673 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7674 V_dontSalvage(vp) = DONT_SALVAGE;
7675 VUpdateVolume_r(&ec, vp, 0);
7679 VCancelReservation_r(vp);
7681 free(salv_flag_vec);
7685 /* run a pass of the VLRU GC scanner */
7687 VLRU_Scan_r(int idx)
7689 afs_uint32 now, thresh;
7690 struct rx_queue *qp, *nqp;
7694 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7696 /* gain exclusive access to the idx VLRU */
7697 VLRU_Wait_r(&volume_LRU.q[idx]);
7698 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7700 if (idx != VLRU_QUEUE_CANDIDATE) {
7701 /* gain exclusive access to the candidate VLRU */
7702 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7703 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7706 now = FT_ApproxTime();
7707 thresh = now - VLRU_offline_thresh;
7709 /* perform candidate selection and soft detaching */
7710 if (idx == VLRU_QUEUE_CANDIDATE) {
7711 /* soft detach some volumes from the candidate pool */
7715 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7716 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7717 if (i >= VLRU_offline_max) {
7720 /* check timestamp to see if it's a candidate for soft detaching */
7721 if (vp->stats.last_get <= thresh) {
7723 if (VCheckSoftDetach(vp, thresh))
7729 /* scan for volumes to become soft detach candidates */
7730 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7731 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7733 /* check timestamp to see if it's a candidate for soft detaching */
7734 if (vp->stats.last_get <= thresh) {
7735 VCheckSoftDetachCandidate(vp, thresh);
7738 if (!(i&0x7f)) { /* lock coarsening optimization */
7746 /* relinquish exclusive access to the VLRU chains */
7750 volume_LRU.last_scan[idx] = now;
7751 if (idx != VLRU_QUEUE_CANDIDATE) {
7752 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7754 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7757 /* check whether volume is safe to soft detach
7758 * caller MUST NOT hold a ref count on vp */
7760 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7764 if (vp->nUsers || vp->nWaiters)
7767 if (vp->stats.last_get <= thresh) {
7768 ret = VSoftDetachVolume_r(vp, thresh);
7774 /* check whether volume should be made a
7775 * soft detach candidate */
7777 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7780 if (vp->nUsers || vp->nWaiters)
7785 osi_Assert(idx == VLRU_QUEUE_NEW);
7787 if (vp->stats.last_get <= thresh) {
7788 /* move to candidate pool */
7789 queue_Remove(&vp->vlru);
7790 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7791 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7792 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7793 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7801 /* begin exclusive access on VLRU */
7803 VLRU_BeginExclusive_r(struct VLRU_q * q)
7805 osi_Assert(q->busy == 0);
7809 /* end exclusive access on VLRU */
7811 VLRU_EndExclusive_r(struct VLRU_q * q)
7813 osi_Assert(q->busy);
7815 CV_BROADCAST(&q->cv);
7818 /* wait for another thread to end exclusive access on VLRU */
7820 VLRU_Wait_r(struct VLRU_q * q)
7823 VOL_CV_WAIT(&q->cv);
7828 * volume soft detach
7830 * caller MUST NOT hold a ref count on vp */
7832 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7837 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7839 ts_save = vp->stats.last_get;
7840 if (ts_save > thresh)
7843 if (vp->nUsers || vp->nWaiters)
7846 if (VIsExclusiveState(V_attachState(vp))) {
7850 switch (V_attachState(vp)) {
7851 case VOL_STATE_UNATTACHED:
7852 case VOL_STATE_PREATTACHED:
7853 case VOL_STATE_ERROR:
7854 case VOL_STATE_GOING_OFFLINE:
7855 case VOL_STATE_SHUTTING_DOWN:
7856 case VOL_STATE_SALVAGING:
7857 case VOL_STATE_DELETED:
7858 volume_LRU.q[vp->vlru.idx].len--;
7860 /* create and cancel a reservation to
7861 * give the volume an opportunity to
7863 VCreateReservation_r(vp);
7864 queue_Remove(&vp->vlru);
7865 vp->vlru.idx = VLRU_QUEUE_INVALID;
7866 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7867 VCancelReservation_r(vp);
7873 /* hold the volume and take it offline.
7874 * no need for reservations, as VHold_r
7875 * takes care of that internally. */
7876 if (VHold_r(vp) == 0) {
7877 /* vhold drops the glock, so now we should
7878 * check to make sure we aren't racing against
7879 * other threads. if we are racing, offlining vp
7880 * would be wasteful, and block the scanner for a while
7884 (vp->shuttingDown) ||
7885 (vp->goingOffline) ||
7886 (vp->stats.last_get != ts_save)) {
7887 /* looks like we're racing someone else. bail */
7891 /* pull it off the VLRU */
7892 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7893 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7894 queue_Remove(&vp->vlru);
7895 vp->vlru.idx = VLRU_QUEUE_INVALID;
7896 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7898 /* take if offline */
7899 VOffline_r(vp, "volume has been soft detached");
7901 /* invalidate the volume header cache */
7902 FreeVolumeHeader(vp);
7905 IncUInt64(&VStats.soft_detaches);
7906 vp->stats.soft_detaches++;
7908 /* put in pre-attached state so demand
7909 * attacher can work on it */
7910 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7916 #endif /* AFS_DEMAND_ATTACH_FS */
7919 /***************************************************/
7920 /* Volume Header Cache routines */
7921 /***************************************************/
7924 * volume header cache.
7926 struct volume_hdr_LRU_t volume_hdr_LRU;
7929 * initialize the volume header cache.
7931 * @param[in] howMany number of header cache entries to preallocate
7933 * @pre VOL_LOCK held. Function has never been called before.
7935 * @post howMany cache entries are allocated, initialized, and added
7936 * to the LRU list. Header cache statistics are initialized.
7938 * @note only applicable to fileServer program type. Should only be
7939 * called once during volume package initialization.
7941 * @internal volume package internal use only.
7944 VInitVolumeHeaderCache(afs_uint32 howMany)
7946 struct volHeader *hp;
7947 if (programType != fileServer)
7949 queue_Init(&volume_hdr_LRU);
7950 volume_hdr_LRU.stats.free = 0;
7951 volume_hdr_LRU.stats.used = howMany;
7952 volume_hdr_LRU.stats.attached = 0;
7953 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7954 osi_Assert(hp != NULL);
7957 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7958 * to ensure they have the right values
7960 ReleaseVolumeHeader(hp++);
7963 /* get a volume header off of the volume header LRU.
7965 * @return volume header
7966 * @retval NULL no usable volume header is available on the LRU
7968 * @pre VOL_LOCK held
7970 * @post for DAFS, if the returned header is associated with a volume, that
7971 * volume is NOT in an exclusive state
7973 * @internal volume package internal use only.
7975 #ifdef AFS_DEMAND_ATTACH_FS
7976 static struct volHeader*
7977 GetVolHeaderFromLRU(void)
7979 struct volHeader *hd = NULL, *qh, *nqh;
7980 /* Usually, a volume in an exclusive state will not have its header on
7981 * the LRU. However, it is possible for this to occur when a salvage
7982 * request is received over FSSYNC, and possibly in other corner cases.
7983 * So just skip over headers whose volumes are in an exclusive state. We
7984 * could VWaitExclusiveState_r instead, but not waiting is faster and
7986 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
7987 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
7995 #else /* AFS_DEMAND_ATTACH_FS */
7996 static struct volHeader*
7997 GetVolHeaderFromLRU(void)
7999 struct volHeader *hd = NULL;
8000 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8001 hd = queue_First(&volume_hdr_LRU, volHeader);
8006 #endif /* !AFS_DEMAND_ATTACH_FS */
8009 * get a volume header and attach it to the volume object.
8011 * @param[in] vp pointer to volume object
8013 * @return cache entry status
8014 * @retval 0 volume header was newly attached; cache data is invalid
8015 * @retval 1 volume header was previously attached; cache data is valid
8017 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8019 * @post volume header attached to volume object. if necessary, header cache
8020 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8022 * @note VOL_LOCK may be dropped
8024 * @warning this interface does not load header data from disk. it merely
8025 * attaches a header object to the volume object, and may sync the old
8026 * header cache data out to disk in the process.
8028 * @internal volume package internal use only.
8031 GetVolumeHeader(Volume * vp)
8034 struct volHeader *hd;
8036 static int everLogged = 0;
8038 #ifdef AFS_DEMAND_ATTACH_FS
8039 VolState vp_save = 0, back_save = 0;
8041 /* XXX debug 9/19/05 we've apparently got
8042 * a ref counting bug somewhere that's
8043 * breaking the nUsers == 0 => header on LRU
8045 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8046 Log("nUsers == 0, but header not on LRU\n");
8051 old = (vp->header != NULL); /* old == volume already has a header */
8053 if (programType != fileServer) {
8054 /* for volume utilities, we allocate volHeaders as needed */
8056 hd = calloc(1, sizeof(*vp->header));
8057 osi_Assert(hd != NULL);
8060 #ifdef AFS_DEMAND_ATTACH_FS
8061 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8065 /* for the fileserver, we keep a volume header cache */
8067 /* the header we previously dropped in the lru is
8068 * still available. pull it off the lru and return */
8071 osi_Assert(hd->back == vp);
8072 #ifdef AFS_DEMAND_ATTACH_FS
8073 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8076 hd = GetVolHeaderFromLRU();
8078 /* LRU is empty, so allocate a new volHeader
8079 * this is probably indicative of a leak, so let the user know */
8080 hd = calloc(1, sizeof(struct volHeader));
8081 osi_Assert(hd != NULL);
8083 Log("****Allocated more volume headers, probably leak****\n");
8086 volume_hdr_LRU.stats.free++;
8089 /* this header used to belong to someone else.
8090 * we'll need to check if the header needs to
8091 * be sync'd out to disk */
8093 #ifdef AFS_DEMAND_ATTACH_FS
8094 /* GetVolHeaderFromLRU had better not give us back a header
8095 * with a volume in exclusive state... */
8096 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8099 if (hd->diskstuff.inUse) {
8100 /* volume was in use, so we'll need to sync
8101 * its header to disk */
8103 #ifdef AFS_DEMAND_ATTACH_FS
8104 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8105 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8106 VCreateReservation_r(hd->back);
8110 WriteVolumeHeader_r(&error, hd->back);
8111 /* Ignore errors; catch them later */
8113 #ifdef AFS_DEMAND_ATTACH_FS
8118 hd->back->header = NULL;
8119 #ifdef AFS_DEMAND_ATTACH_FS
8120 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8122 if (hd->diskstuff.inUse) {
8123 VChangeState_r(hd->back, back_save);
8124 VCancelReservation_r(hd->back);
8125 VChangeState_r(vp, vp_save);
8129 volume_hdr_LRU.stats.attached++;
8133 #ifdef AFS_DEMAND_ATTACH_FS
8134 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8137 volume_hdr_LRU.stats.free--;
8138 volume_hdr_LRU.stats.used++;
8140 IncUInt64(&VStats.hdr_gets);
8141 #ifdef AFS_DEMAND_ATTACH_FS
8142 IncUInt64(&vp->stats.hdr_gets);
8143 vp->stats.last_hdr_get = FT_ApproxTime();
8150 * make sure volume header is attached and contains valid cache data.
8152 * @param[out] ec outbound error code
8153 * @param[in] vp pointer to volume object
8155 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8157 * @post header cache entry attached, and loaded with valid data, or
8158 * *ec is nonzero, and the header is released back into the LRU.
8160 * @internal volume package internal use only.
8163 LoadVolumeHeader(Error * ec, Volume * vp)
8165 #ifdef AFS_DEMAND_ATTACH_FS
8166 VolState state_save;
8170 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8171 IncUInt64(&VStats.hdr_loads);
8172 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8175 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8176 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8178 IncUInt64(&vp->stats.hdr_loads);
8179 now = FT_ApproxTime();
8183 V_attachFlags(vp) |= VOL_HDR_LOADED;
8184 vp->stats.last_hdr_load = now;
8186 VChangeState_r(vp, state_save);
8188 #else /* AFS_DEMAND_ATTACH_FS */
8190 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8191 IncUInt64(&VStats.hdr_loads);
8193 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8194 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8197 #endif /* AFS_DEMAND_ATTACH_FS */
8199 /* maintain (nUsers==0) => header in LRU invariant */
8200 FreeVolumeHeader(vp);
8205 * release a header cache entry back into the LRU list.
8207 * @param[in] hd pointer to volume header cache object
8209 * @pre VOL_LOCK held.
8211 * @post header cache object appended onto end of LRU list.
8213 * @note only applicable to fileServer program type.
8215 * @note used to place a header cache entry back into the
8216 * LRU pool without invalidating it as a cache entry.
8218 * @internal volume package internal use only.
8221 ReleaseVolumeHeader(struct volHeader *hd)
8223 if (programType != fileServer)
8225 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8227 queue_Append(&volume_hdr_LRU, hd);
8228 #ifdef AFS_DEMAND_ATTACH_FS
8230 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8233 volume_hdr_LRU.stats.free++;
8234 volume_hdr_LRU.stats.used--;
8238 * free/invalidate a volume header cache entry.
8240 * @param[in] vp pointer to volume object
8242 * @pre VOL_LOCK is held.
8244 * @post For fileserver, header cache entry is returned to LRU, and it is
8245 * invalidated as a cache entry. For volume utilities, the header
8246 * cache entry is freed.
8248 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8249 * whenever it is necessary to invalidate the header cache entry.
8251 * @see ReleaseVolumeHeader
8253 * @internal volume package internal use only.
8256 FreeVolumeHeader(Volume * vp)
8258 struct volHeader *hd = vp->header;
8261 if (programType == fileServer) {
8262 ReleaseVolumeHeader(hd);
8267 #ifdef AFS_DEMAND_ATTACH_FS
8268 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8270 volume_hdr_LRU.stats.attached--;
8275 /***************************************************/
8276 /* Volume Hash Table routines */
8277 /***************************************************/
8280 * set size of volume object hash table.
8282 * @param[in] logsize log(2) of desired hash table size
8284 * @return operation status
8286 * @retval -1 failure
8288 * @pre MUST be called prior to VInitVolumePackage2
8290 * @post Volume Hash Table will have 2^logsize buckets
8293 VSetVolHashSize(int logsize)
8295 /* 64 to 268435456 hash buckets seems like a reasonable range */
8296 if ((logsize < 6 ) || (logsize > 28)) {
8301 VolumeHashTable.Size = 1 << logsize;
8302 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8304 /* we can't yet support runtime modification of this
8305 * parameter. we'll need a configuration rwlock to
8306 * make runtime modification feasible.... */
8313 * initialize dynamic data structures for volume hash table.
8315 * @post hash table is allocated, and fields are initialized.
8317 * @internal volume package internal use only.
8320 VInitVolumeHash(void)
8324 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8325 sizeof(VolumeHashChainHead));
8326 osi_Assert(VolumeHashTable.Table != NULL);
8328 for (i=0; i < VolumeHashTable.Size; i++) {
8329 queue_Init(&VolumeHashTable.Table[i]);
8330 #ifdef AFS_DEMAND_ATTACH_FS
8331 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8332 #endif /* AFS_DEMAND_ATTACH_FS */
8337 * add a volume object to the hash table.
8339 * @param[in] vp pointer to volume object
8340 * @param[in] hashid hash of volume id
8342 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8345 * @post volume is added to hash chain.
8347 * @internal volume package internal use only.
8349 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8350 * asynchronous hash chain reordering to finish.
8353 AddVolumeToHashTable(Volume * vp, int hashid)
8355 VolumeHashChainHead * head;
8357 if (queue_IsOnQueue(vp))
8360 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8362 #ifdef AFS_DEMAND_ATTACH_FS
8363 /* wait for the hash chain to become available */
8366 V_attachFlags(vp) |= VOL_IN_HASH;
8367 vp->chainCacheCheck = ++head->cacheCheck;
8368 #endif /* AFS_DEMAND_ATTACH_FS */
8371 vp->hashid = hashid;
8372 queue_Append(head, vp);
8373 vp->vnodeHashOffset = VolumeHashOffset_r();
8377 * delete a volume object from the hash table.
8379 * @param[in] vp pointer to volume object
8381 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8384 * @post volume is removed from hash chain.
8386 * @internal volume package internal use only.
8388 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8389 * asynchronous hash chain reordering to finish.
8392 DeleteVolumeFromHashTable(Volume * vp)
8394 VolumeHashChainHead * head;
8396 if (!queue_IsOnQueue(vp))
8399 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8401 #ifdef AFS_DEMAND_ATTACH_FS
8402 /* wait for the hash chain to become available */
8405 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8407 #endif /* AFS_DEMAND_ATTACH_FS */
8411 /* do NOT reset hashid to zero, as the online
8412 * salvager package may need to know the volume id
8413 * after the volume is removed from the hash */
8417 * lookup a volume object in the hash table given a volume id.
8419 * @param[out] ec error code return
8420 * @param[in] volumeId volume id
8421 * @param[in] hint volume object which we believe could be the correct
8424 * @return volume object pointer
8425 * @retval NULL no such volume id is registered with the hash table.
8427 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8430 * @post volume object with the given id is returned. volume object and
8431 * hash chain access statistics are updated. hash chain may have
8434 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8435 * asynchronous hash chain reordering operation to finish, or
8436 * in order for us to perform an asynchronous chain reordering.
8438 * @note Hash chain reorderings occur when the access count for the
8439 * volume object being looked up exceeds the sum of the previous
8440 * node's (the node ahead of it in the hash chain linked list)
8441 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8443 * @note For DAFS, the hint parameter allows us to short-circuit if the
8444 * cacheCheck fields match between the hash chain head and the
8445 * hint volume object.
8448 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8452 #ifdef AFS_DEMAND_ATTACH_FS
8455 VolumeHashChainHead * head;
8458 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8460 #ifdef AFS_DEMAND_ATTACH_FS
8461 /* wait for the hash chain to become available */
8464 /* check to see if we can short circuit without walking the hash chain */
8465 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8466 IncUInt64(&hint->stats.hash_short_circuits);
8469 #endif /* AFS_DEMAND_ATTACH_FS */
8471 /* someday we need to either do per-chain locks, RWlocks,
8472 * or both for volhash access.
8473 * (and move to a data structure with better cache locality) */
8475 /* search the chain for this volume id */
8476 for(queue_Scan(head, vp, np, Volume)) {
8478 if (vp->hashid == volumeId) {
8483 if (queue_IsEnd(head, vp)) {
8487 #ifdef AFS_DEMAND_ATTACH_FS
8488 /* update hash chain statistics */
8491 FillInt64(lks, 0, looks);
8492 AddUInt64(head->looks, lks, &head->looks);
8493 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8494 IncUInt64(&head->gets);
8499 IncUInt64(&vp->stats.hash_lookups);
8501 /* for demand attach fileserver, we permit occasional hash chain reordering
8502 * so that frequently looked up volumes move towards the head of the chain */
8503 pp = queue_Prev(vp, Volume);
8504 if (!queue_IsEnd(head, pp)) {
8505 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8506 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8507 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8508 VReorderHash_r(head, pp, vp);
8512 /* update the short-circuit cache check */
8513 vp->chainCacheCheck = head->cacheCheck;
8515 #endif /* AFS_DEMAND_ATTACH_FS */
8520 #ifdef AFS_DEMAND_ATTACH_FS
8521 /* perform volume hash chain reordering.
8523 * advance a subchain beginning at vp ahead of
8524 * the adjacent subchain ending at pp */
8526 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8528 Volume *tp, *np, *lp;
8529 afs_uint64 move_thresh;
8531 /* this should never be called if the chain is already busy, so
8532 * no need to wait for other exclusive chain ops to finish */
8534 /* this is a rather heavy set of operations,
8535 * so let's set the chain busy flag and drop
8537 VHashBeginExclusive_r(head);
8540 /* scan forward in the chain from vp looking for the last element
8541 * in the chain we want to advance */
8542 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8543 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8544 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8545 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8549 lp = queue_Prev(tp, Volume);
8551 /* scan backwards from pp to determine where to splice and
8552 * insert the subchain we're advancing */
8553 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8554 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8558 tp = queue_Next(tp, Volume);
8560 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8561 queue_MoveChainBefore(tp,vp,lp);
8564 IncUInt64(&VStats.hash_reorders);
8566 IncUInt64(&head->reorders);
8568 /* wake up any threads waiting for the hash chain */
8569 VHashEndExclusive_r(head);
8573 /* demand-attach fs volume hash
8574 * asynchronous exclusive operations */
8577 * begin an asynchronous exclusive operation on a volume hash chain.
8579 * @param[in] head pointer to volume hash chain head object
8581 * @pre VOL_LOCK held. hash chain is quiescent.
8583 * @post hash chain marked busy.
8585 * @note this interface is used in conjunction with VHashEndExclusive_r and
8586 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8587 * volume hash chain. Its main use case is hash chain reordering, which
8588 * has the potential to be a highly latent operation.
8590 * @see VHashEndExclusive_r
8595 * @internal volume package internal use only.
8598 VHashBeginExclusive_r(VolumeHashChainHead * head)
8600 osi_Assert(head->busy == 0);
8605 * relinquish exclusive ownership of a volume hash chain.
8607 * @param[in] head pointer to volume hash chain head object
8609 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8611 * @post hash chain is marked quiescent. threads awaiting use of
8612 * chain are awakened.
8614 * @see VHashBeginExclusive_r
8619 * @internal volume package internal use only.
8622 VHashEndExclusive_r(VolumeHashChainHead * head)
8624 osi_Assert(head->busy);
8626 CV_BROADCAST(&head->chain_busy_cv);
8630 * wait for all asynchronous operations on a hash chain to complete.
8632 * @param[in] head pointer to volume hash chain head object
8634 * @pre VOL_LOCK held.
8636 * @post hash chain object is quiescent.
8638 * @see VHashBeginExclusive_r
8639 * @see VHashEndExclusive_r
8643 * @note This interface should be called before any attempt to
8644 * traverse the hash chain. It is permissible for a thread
8645 * to gain exclusive access to the chain, and then perform
8646 * latent operations on the chain asynchronously wrt the
8649 * @warning if waiting is necessary, VOL_LOCK is dropped
8651 * @internal volume package internal use only.
8654 VHashWait_r(VolumeHashChainHead * head)
8656 while (head->busy) {
8657 VOL_CV_WAIT(&head->chain_busy_cv);
8660 #endif /* AFS_DEMAND_ATTACH_FS */
8663 /***************************************************/
8664 /* Volume by Partition List routines */
8665 /***************************************************/
8668 * demand attach fileserver adds a
8669 * linked list of volumes to each
8670 * partition object, thus allowing
8671 * for quick enumeration of all
8672 * volumes on a partition
8675 #ifdef AFS_DEMAND_ATTACH_FS
8677 * add a volume to its disk partition VByPList.
8679 * @param[in] vp pointer to volume object
8681 * @pre either the disk partition VByPList is owned exclusively
8682 * by the calling thread, or the list is quiescent and
8685 * @post volume is added to disk partition VByPList
8689 * @warning it is the caller's responsibility to ensure list
8692 * @see VVByPListWait_r
8693 * @see VVByPListBeginExclusive_r
8694 * @see VVByPListEndExclusive_r
8696 * @internal volume package internal use only.
8699 AddVolumeToVByPList_r(Volume * vp)
8701 if (queue_IsNotOnQueue(&vp->vol_list)) {
8702 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8703 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8704 vp->partition->vol_list.len++;
8709 * delete a volume from its disk partition VByPList.
8711 * @param[in] vp pointer to volume object
8713 * @pre either the disk partition VByPList is owned exclusively
8714 * by the calling thread, or the list is quiescent and
8717 * @post volume is removed from the disk partition VByPList
8721 * @warning it is the caller's responsibility to ensure list
8724 * @see VVByPListWait_r
8725 * @see VVByPListBeginExclusive_r
8726 * @see VVByPListEndExclusive_r
8728 * @internal volume package internal use only.
8731 DeleteVolumeFromVByPList_r(Volume * vp)
8733 if (queue_IsOnQueue(&vp->vol_list)) {
8734 queue_Remove(&vp->vol_list);
8735 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8736 vp->partition->vol_list.len--;
8741 * begin an asynchronous exclusive operation on a VByPList.
8743 * @param[in] dp pointer to disk partition object
8745 * @pre VOL_LOCK held. VByPList is quiescent.
8747 * @post VByPList marked busy.
8749 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8750 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8753 * @see VVByPListEndExclusive_r
8754 * @see VVByPListWait_r
8758 * @internal volume package internal use only.
8760 /* take exclusive control over the list */
8762 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8764 osi_Assert(dp->vol_list.busy == 0);
8765 dp->vol_list.busy = 1;
8769 * relinquish exclusive ownership of a VByPList.
8771 * @param[in] dp pointer to disk partition object
8773 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8775 * @post VByPList is marked quiescent. threads awaiting use of
8776 * the list are awakened.
8778 * @see VVByPListBeginExclusive_r
8779 * @see VVByPListWait_r
8783 * @internal volume package internal use only.
8786 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8788 osi_Assert(dp->vol_list.busy);
8789 dp->vol_list.busy = 0;
8790 CV_BROADCAST(&dp->vol_list.cv);
8794 * wait for all asynchronous operations on a VByPList to complete.
8796 * @param[in] dp pointer to disk partition object
8798 * @pre VOL_LOCK is held.
8800 * @post disk partition's VByP list is quiescent
8804 * @note This interface should be called before any attempt to
8805 * traverse the VByPList. It is permissible for a thread
8806 * to gain exclusive access to the list, and then perform
8807 * latent operations on the list asynchronously wrt the
8810 * @warning if waiting is necessary, VOL_LOCK is dropped
8812 * @see VVByPListEndExclusive_r
8813 * @see VVByPListBeginExclusive_r
8815 * @internal volume package internal use only.
8818 VVByPListWait_r(struct DiskPartition64 * dp)
8820 while (dp->vol_list.busy) {
8821 VOL_CV_WAIT(&dp->vol_list.cv);
8824 #endif /* AFS_DEMAND_ATTACH_FS */
8826 /***************************************************/
8827 /* Volume Cache Statistics routines */
8828 /***************************************************/
8831 VPrintCacheStats_r(void)
8833 struct VnodeClassInfo *vcp;
8834 vcp = &VnodeClassInfo[vLarge];
8835 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);
8836 vcp = &VnodeClassInfo[vSmall];
8837 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);
8838 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8839 "%"AFS_INT64_FMT" replacements\n",
8840 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8844 VPrintCacheStats(void)
8847 VPrintCacheStats_r();
8851 #ifdef AFS_DEMAND_ATTACH_FS
8853 UInt64ToDouble(afs_uint64 * x)
8855 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8857 SplitInt64(*x, h, l);
8858 return (((double)h) * c32) + ((double) l);
8862 DoubleToPrintable(double x, char * buf, int len)
8864 static double billion = 1000000000.0;
8867 y[0] = (afs_uint32) (x / (billion * billion));
8868 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8869 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8872 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8874 snprintf(buf, len, "%d%09d", y[1], y[2]);
8876 snprintf(buf, len, "%d", y[2]);
8882 struct VLRUExtStatsEntry {
8886 struct VLRUExtStats {
8892 } queue_info[VLRU_QUEUE_INVALID];
8893 struct VLRUExtStatsEntry * vec;
8897 * add a 256-entry fudge factor onto the vector in case state changes
8898 * out from under us.
8900 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8903 * collect extended statistics for the VLRU subsystem.
8905 * @param[out] stats pointer to stats structure to be populated
8906 * @param[in] nvols number of volumes currently known to exist
8908 * @pre VOL_LOCK held
8910 * @post stats->vec allocated and populated
8912 * @return operation status
8917 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8919 afs_uint32 cur, idx, len;
8920 struct rx_queue * qp, * nqp;
8922 struct VLRUExtStatsEntry * vec;
8924 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8925 vec = stats->vec = calloc(len,
8926 sizeof(struct VLRUExtStatsEntry));
8932 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8933 VLRU_Wait_r(&volume_LRU.q[idx]);
8934 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8937 stats->queue_info[idx].start = cur;
8939 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8941 /* out of space in vec */
8944 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8945 vec[cur].volid = vp->hashid;
8949 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8952 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8960 #define ENUMTOSTRING(en) #en
8961 #define ENUMCASE(en) \
8962 case en: return ENUMTOSTRING(en)
8965 vlru_idx_to_string(int idx)
8968 ENUMCASE(VLRU_QUEUE_NEW);
8969 ENUMCASE(VLRU_QUEUE_MID);
8970 ENUMCASE(VLRU_QUEUE_OLD);
8971 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8972 ENUMCASE(VLRU_QUEUE_HELD);
8973 ENUMCASE(VLRU_QUEUE_INVALID);
8975 return "**UNKNOWN**";
8980 VPrintExtendedCacheStats_r(int flags)
8983 afs_uint32 vol_sum = 0;
8990 struct stats looks, gets, reorders, len;
8991 struct stats ch_looks, ch_gets, ch_reorders;
8993 VolumeHashChainHead *head;
8995 struct VLRUExtStats vlru_stats;
8997 /* zero out stats */
8998 memset(&looks, 0, sizeof(struct stats));
8999 memset(&gets, 0, sizeof(struct stats));
9000 memset(&reorders, 0, sizeof(struct stats));
9001 memset(&len, 0, sizeof(struct stats));
9002 memset(&ch_looks, 0, sizeof(struct stats));
9003 memset(&ch_gets, 0, sizeof(struct stats));
9004 memset(&ch_reorders, 0, sizeof(struct stats));
9006 for (i = 0; i < VolumeHashTable.Size; i++) {
9007 head = &VolumeHashTable.Table[i];
9010 VHashBeginExclusive_r(head);
9013 ch_looks.sum = UInt64ToDouble(&head->looks);
9014 ch_gets.sum = UInt64ToDouble(&head->gets);
9015 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9017 /* update global statistics */
9019 looks.sum += ch_looks.sum;
9020 gets.sum += ch_gets.sum;
9021 reorders.sum += ch_reorders.sum;
9022 len.sum += (double)head->len;
9023 vol_sum += head->len;
9026 len.min = (double) head->len;
9027 len.max = (double) head->len;
9028 looks.min = ch_looks.sum;
9029 looks.max = ch_looks.sum;
9030 gets.min = ch_gets.sum;
9031 gets.max = ch_gets.sum;
9032 reorders.min = ch_reorders.sum;
9033 reorders.max = ch_reorders.sum;
9035 if (((double)head->len) < len.min)
9036 len.min = (double) head->len;
9037 if (((double)head->len) > len.max)
9038 len.max = (double) head->len;
9039 if (ch_looks.sum < looks.min)
9040 looks.min = ch_looks.sum;
9041 else if (ch_looks.sum > looks.max)
9042 looks.max = ch_looks.sum;
9043 if (ch_gets.sum < gets.min)
9044 gets.min = ch_gets.sum;
9045 else if (ch_gets.sum > gets.max)
9046 gets.max = ch_gets.sum;
9047 if (ch_reorders.sum < reorders.min)
9048 reorders.min = ch_reorders.sum;
9049 else if (ch_reorders.sum > reorders.max)
9050 reorders.max = ch_reorders.sum;
9054 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9055 /* compute detailed per-chain stats */
9056 struct stats hdr_loads, hdr_gets;
9057 double v_looks, v_loads, v_gets;
9059 /* initialize stats with data from first element in chain */
9060 vp = queue_First(head, Volume);
9061 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9062 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9063 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9064 ch_gets.min = ch_gets.max = v_looks;
9065 hdr_loads.min = hdr_loads.max = v_loads;
9066 hdr_gets.min = hdr_gets.max = v_gets;
9067 hdr_loads.sum = hdr_gets.sum = 0;
9069 vp = queue_Next(vp, Volume);
9071 /* pull in stats from remaining elements in chain */
9072 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9073 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9074 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9075 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9077 hdr_loads.sum += v_loads;
9078 hdr_gets.sum += v_gets;
9080 if (v_looks < ch_gets.min)
9081 ch_gets.min = v_looks;
9082 else if (v_looks > ch_gets.max)
9083 ch_gets.max = v_looks;
9085 if (v_loads < hdr_loads.min)
9086 hdr_loads.min = v_loads;
9087 else if (v_loads > hdr_loads.max)
9088 hdr_loads.max = v_loads;
9090 if (v_gets < hdr_gets.min)
9091 hdr_gets.min = v_gets;
9092 else if (v_gets > hdr_gets.max)
9093 hdr_gets.max = v_gets;
9096 /* compute per-chain averages */
9097 ch_gets.avg = ch_gets.sum / ((double)head->len);
9098 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9099 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9101 /* dump per-chain stats */
9102 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9104 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9105 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9106 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9107 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9108 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9109 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9110 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9111 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9112 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9113 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9114 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9115 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9116 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9117 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9118 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9119 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9120 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9121 } else if (flags & VOL_STATS_PER_CHAIN) {
9122 /* dump simple per-chain stats */
9123 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9125 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9126 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9127 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9131 VHashEndExclusive_r(head);
9136 /* compute global averages */
9137 len.avg = len.sum / ((double)VolumeHashTable.Size);
9138 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9139 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9140 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9142 /* dump global stats */
9143 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9144 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9145 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9146 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9147 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9148 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9149 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9150 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9151 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9152 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9153 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9154 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9155 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9156 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9157 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9158 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9159 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9160 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9161 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9162 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9163 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9165 /* print extended disk related statistics */
9167 struct DiskPartition64 * diskP;
9168 afs_uint32 vol_count[VOLMAXPARTS+1];
9169 byte part_exists[VOLMAXPARTS+1];
9173 memset(vol_count, 0, sizeof(vol_count));
9174 memset(part_exists, 0, sizeof(part_exists));
9178 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9180 vol_count[id] = diskP->vol_list.len;
9181 part_exists[id] = 1;
9185 for (i = 0; i <= VOLMAXPARTS; i++) {
9186 if (part_exists[i]) {
9187 /* XXX while this is currently safe, it is a violation
9188 * of the VGetPartitionById_r interface contract. */
9189 diskP = VGetPartitionById_r(i, 0);
9191 Log("Partition %s has %d online volumes\n",
9192 VPartitionPath(diskP), diskP->vol_list.len);
9199 /* print extended VLRU statistics */
9200 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9201 afs_uint32 idx, cur, lpos;
9206 Log("VLRU State Dump:\n\n");
9208 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9209 Log("\t%s:\n", vlru_idx_to_string(idx));
9212 for (cur = vlru_stats.queue_info[idx].start;
9213 cur < vlru_stats.queue_info[idx].len;
9215 line[lpos++] = vlru_stats.vec[cur].volid;
9217 Log("\t\t%u, %u, %u, %u, %u,\n",
9218 line[0], line[1], line[2], line[3], line[4]);
9227 Log("\t\t%u, %u, %u, %u, %u\n",
9228 line[0], line[1], line[2], line[3], line[4]);
9233 free(vlru_stats.vec);
9240 VPrintExtendedCacheStats(int flags)
9243 VPrintExtendedCacheStats_r(flags);
9246 #endif /* AFS_DEMAND_ATTACH_FS */
9249 VCanScheduleSalvage(void)
9251 return vol_opts.canScheduleSalvage;
9257 return vol_opts.canUseFSSYNC;
9261 VCanUseSALVSYNC(void)
9263 return vol_opts.canUseSALVSYNC;
9267 VCanUnsafeAttach(void)
9269 return vol_opts.unsafe_attach;