2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
9 * Portions Copyright (c) 2005-2008 Sine Nomine Associates
12 /* 1/1/89: NB: this stuff is all going to be replaced. Don't take it too seriously */
17 Institution: The Information Technology Center, Carnegie-Mellon University
21 #include <afsconfig.h>
22 #include <afs/param.h>
30 #ifdef HAVE_SYS_FILE_H
34 #ifdef AFS_PTHREAD_ENV
35 # include <opr/lock.h>
37 # include <opr/lockstub.h>
40 #include <opr/jhash.h>
42 #include <afs/afsint.h>
44 #include <rx/rx_queue.h>
47 #if !defined(AFS_SGI_ENV)
48 #ifdef AFS_VFSINCL_ENV
51 #include <sys/fs/ufs_fs.h>
53 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
54 #include <ufs/ufs/dinode.h>
55 #include <ufs/ffs/fs.h>
60 #else /* AFS_VFSINCL_ENV */
61 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
64 #endif /* AFS_VFSINCL_ENV */
65 #endif /* AFS_SGI_ENV */
66 #endif /* !AFS_NT40_ENV */
74 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
76 #include <sys/mnttab.h>
77 #include <sys/mntent.h>
83 #if defined(AFS_SGI_ENV)
86 #ifndef AFS_LINUX20_ENV
87 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
90 #endif /* AFS_SGI_ENV */
92 #endif /* AFS_HPUX_ENV */
96 #include <afs/errors.h>
99 #include <afs/afssyscalls.h>
101 #include <afs/afsutil.h>
102 #include "daemon_com.h"
104 #include "salvsync.h"
107 #include "partition.h"
108 #include "volume_inline.h"
113 #ifdef AFS_PTHREAD_ENV
114 pthread_mutex_t vol_glock_mutex;
115 pthread_mutex_t vol_trans_mutex;
116 pthread_cond_t vol_put_volume_cond;
117 pthread_cond_t vol_sleep_cond;
118 pthread_cond_t vol_init_attach_cond;
119 pthread_cond_t vol_vinit_cond;
120 int vol_attach_threads = 1;
121 #endif /* AFS_PTHREAD_ENV */
123 #ifdef AFS_DEMAND_ATTACH_FS
124 pthread_mutex_t vol_salvsync_mutex;
127 * Set this to 1 to disallow SALVSYNC communication in all threads; used
128 * during shutdown, since the salvageserver may have gone away.
130 static volatile sig_atomic_t vol_disallow_salvsync = 0;
131 #endif /* AFS_DEMAND_ATTACH_FS */
134 * has VShutdown_r been called / is VShutdown_r running?
136 static int vol_shutting_down = 0;
138 /* Forward declarations */
139 static Volume *attach2(Error * ec, VolumeId volumeId, char *path,
140 struct DiskPartition64 *partp, Volume * vp,
141 int isbusy, int mode, int *acheckedOut);
142 static void ReallyFreeVolume(Volume * vp);
143 #ifdef AFS_DEMAND_ATTACH_FS
144 static void FreeVolume(Volume * vp);
145 #else /* !AFS_DEMAND_ATTACH_FS */
146 #define FreeVolume(vp) ReallyFreeVolume(vp)
147 static void VScanUpdateList(void);
148 #endif /* !AFS_DEMAND_ATTACH_FS */
149 static void VInitVolumeHeaderCache(afs_uint32 howMany);
150 static int GetVolumeHeader(Volume * vp);
151 static void ReleaseVolumeHeader(struct volHeader *hd);
152 static void FreeVolumeHeader(Volume * vp);
153 static void AddVolumeToHashTable(Volume * vp, VolumeId hashid);
154 static void DeleteVolumeFromHashTable(Volume * vp);
155 static int VHold_r(Volume * vp);
156 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
157 static void VReleaseVolumeHandles_r(Volume * vp);
158 static void VCloseVolumeHandles_r(Volume * vp);
159 static void LoadVolumeHeader(Error * ec, Volume * vp);
160 static int VCheckOffline(Volume * vp);
161 static int VCheckDetach(Volume * vp);
162 static Volume * GetVolume(Error * ec, Error * client_ec, VolumeId volumeId,
163 Volume * hint, const struct timespec *ts);
165 ProgramType programType; /* The type of program using the package */
166 static VolumePackageOptions vol_opts;
168 /* extended volume package statistics */
171 #ifdef VOL_LOCK_DEBUG
172 pthread_t vol_glock_holder = 0;
176 /* this parameter needs to be tunable at runtime.
177 * 128 was really inadequate for largish servers -- at 16384 volumes this
178 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
179 * talk about bad spatial locality...
181 * an AVL or splay tree might work a lot better, but we'll just increase
182 * the default hash table size for now
184 #define DEFAULT_VOLUME_HASH_BITS 10
185 #define DEFAULT_VOLUME_HASH_SIZE opr_jhash_size(DEFAULT_VOLUME_HASH_BITS)
186 #define DEFAULT_VOLUME_HASH_MASK opr_jhash_mask(DEFAULT_VOLUME_HASH_BITS)
187 #define VOLUME_HASH(volumeId) \
188 (opr_jhash_int(volumeId, 0) & VolumeHashTable.Mask)
191 * turn volume hash chains into partially ordered lists.
192 * when the threshold is exceeded between two adjacent elements,
193 * perform a chain rebalancing operation.
195 * keep the threshold high in order to keep cache line invalidates
196 * low "enough" on SMPs
198 #define VOLUME_HASH_REORDER_THRESHOLD 200
201 * when possible, don't just reorder single elements, but reorder
202 * entire chains of elements at once. a chain of elements that
203 * exceed the element previous to the pivot by at least CHAIN_THRESH
204 * accesses are moved in front of the chain whose elements have at
205 * least CHAIN_THRESH less accesses than the pivot element
207 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
210 * The per volume uniquifier is bumped by 200 and and written to disk
211 * every 200 file creates.
213 #define VOLUME_UPDATE_UNIQUIFIER_BUMP 200
215 #include "rx/rx_queue.h"
218 VolumeHashTable_t VolumeHashTable = {
219 DEFAULT_VOLUME_HASH_SIZE,
220 DEFAULT_VOLUME_HASH_MASK,
225 static void VInitVolumeHash(void);
228 #ifdef AFS_PTHREAD_ENV
230 * disk partition queue element
232 typedef struct diskpartition_queue_t {
233 struct rx_queue queue; /**< queue header */
234 struct DiskPartition64 *diskP; /**< disk partition table entry */
235 } diskpartition_queue_t;
237 #ifndef AFS_DEMAND_ATTACH_FS
239 typedef struct vinitvolumepackage_thread_t {
240 struct rx_queue queue;
241 pthread_cond_t thread_done_cv;
242 int n_threads_complete;
243 } vinitvolumepackage_thread_t;
244 static void * VInitVolumePackageThread(void * args);
246 #else /* !AFS_DEMAND_ATTTACH_FS */
247 #define VINIT_BATCH_MAX_SIZE 512
250 * disk partition work queue
252 struct partition_queue {
253 struct rx_queue head; /**< diskpartition_queue_t queue */
254 pthread_mutex_t mutex;
259 * volumes parameters for preattach
261 struct volume_init_batch {
262 struct rx_queue queue; /**< queue header */
263 int thread; /**< posting worker thread */
264 int last; /**< indicates thread is done */
265 int size; /**< number of volume ids in batch */
266 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
270 * volume parameters work queue
272 struct volume_init_queue {
273 struct rx_queue head; /**< volume_init_batch queue */
274 pthread_mutex_t mutex;
279 * volume init worker thread parameters
281 struct vinitvolumepackage_thread_param {
282 int nthreads; /**< total number of worker threads */
283 int thread; /**< thread number for this worker thread */
284 struct partition_queue *pq; /**< queue partitions to scan */
285 struct volume_init_queue *vq; /**< queue of volume to preattach */
288 static void *VInitVolumePackageThread(void *args);
289 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
290 static VolumeId VInitNextVolumeId(DIR *dirp);
291 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
293 #endif /* !AFS_DEMAND_ATTACH_FS */
294 #endif /* AFS_PTHREAD_ENV */
296 #ifndef AFS_DEMAND_ATTACH_FS
297 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
298 int * nAttached, int * nUnattached);
299 #endif /* AFS_DEMAND_ATTACH_FS */
302 #ifdef AFS_DEMAND_ATTACH_FS
303 /* demand attach fileserver extensions */
306 * in the future we will support serialization of VLRU state into the fs_state
309 * these structures are the beginning of that effort
311 struct VLRU_DiskHeader {
312 struct versionStamp stamp; /* magic and structure version number */
313 afs_uint32 mtime; /* time of dump to disk */
314 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
317 struct VLRU_DiskEntry {
318 VolumeId vid; /* volume ID */
319 afs_uint32 idx; /* generation */
320 afs_uint32 last_get; /* timestamp of last get */
323 struct VLRU_StartupQueue {
324 struct VLRU_DiskEntry * entry;
329 typedef struct vshutdown_thread_t {
331 pthread_mutex_t lock;
333 pthread_cond_t master_cv;
335 int n_threads_complete;
337 int schedule_version;
340 byte n_parts_done_pass;
341 byte part_thread_target[VOLMAXPARTS+1];
342 byte part_done_pass[VOLMAXPARTS+1];
343 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
344 int stats[4][VOLMAXPARTS+1];
345 } vshutdown_thread_t;
346 static void * VShutdownThread(void * args);
349 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
350 static int VCheckFree(Volume * vp);
353 static void AddVolumeToVByPList_r(Volume * vp);
354 static void DeleteVolumeFromVByPList_r(Volume * vp);
355 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
356 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
357 static void VVByPListWait_r(struct DiskPartition64 * dp);
359 /* online salvager */
361 VCHECK_SALVAGE_OK = 0, /**< no pending salvage */
362 VCHECK_SALVAGE_SCHEDULED = 1, /**< salvage has been scheduled */
363 VCHECK_SALVAGE_ASYNC = 2, /**< salvage being scheduled */
364 VCHECK_SALVAGE_DENIED = 3, /**< salvage not scheduled; denied */
365 VCHECK_SALVAGE_FAIL = 4 /**< salvage not scheduled; failed */
367 static int VCheckSalvage(Volume * vp);
368 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
369 static int VScheduleSalvage_r(Volume * vp);
372 /* Volume hash table */
373 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
374 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
375 static void VHashEndExclusive_r(VolumeHashChainHead * head);
376 static void VHashWait_r(VolumeHashChainHead * head);
379 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
380 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
381 struct rx_queue ** idx);
382 static void ShutdownController(vshutdown_thread_t * params);
383 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
386 static void VLRU_ComputeConstants(void);
387 static void VInitVLRU(void);
388 static void VLRU_Init_Node_r(Volume * vp);
389 static void VLRU_Add_r(Volume * vp);
390 static void VLRU_Delete_r(Volume * vp);
391 static void VLRU_UpdateAccess_r(Volume * vp);
392 static void * VLRU_ScannerThread(void * args);
393 static void VLRU_Scan_r(int idx);
394 static void VLRU_Promote_r(int idx);
395 static void VLRU_Demote_r(int idx);
396 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
399 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
400 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
401 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
404 pthread_key_t VThread_key;
405 VThreadOptions_t VThread_defaults = {
406 0 /**< allow salvsync */
408 #endif /* AFS_DEMAND_ATTACH_FS */
411 struct Lock vol_listLock; /* Lock obtained when listing volumes:
412 * prevents a volume from being missed
413 * if the volume is attached during a
417 /* Common message used when the volume goes off line */
418 char *VSalvageMessage =
419 "Files in this volume are currently unavailable; call operations";
421 int VInit; /* 0 - uninitialized,
422 * 1 - initialized but not all volumes have been attached,
423 * 2 - initialized and all volumes have been attached,
424 * 3 - initialized, all volumes have been attached, and
425 * VConnectFS() has completed. */
427 static int vinit_attach_abort = 0;
429 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
430 * used to stamp volume headers and in-core
431 * vnodes. When the volume goes on-line the
432 * vnode will be invalidated
433 * access only with VOL_LOCK held */
438 /***************************************************/
439 /* Startup routines */
440 /***************************************************/
442 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
443 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
444 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
448 * assign default values to a VolumePackageOptions struct.
450 * Always call this on a VolumePackageOptions struct first, then set any
451 * specific options you want, then call VInitVolumePackage2.
453 * @param[in] pt caller's program type
454 * @param[out] opts volume package options
457 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
459 opts->nLargeVnodes = opts->nSmallVnodes = 5;
462 opts->canScheduleSalvage = 0;
463 opts->canUseFSSYNC = 0;
464 opts->canUseSALVSYNC = 0;
466 opts->interrupt_rxcall = NULL;
467 opts->offline_timeout = -1;
468 opts->offline_shutdown_timeout = -1;
469 opts->usage_threshold = 128;
470 opts->usage_rate_limit = 5;
473 opts->unsafe_attach = 1;
474 #else /* !FAST_RESTART */
475 opts->unsafe_attach = 0;
476 #endif /* !FAST_RESTART */
480 opts->canScheduleSalvage = 1;
481 opts->canUseSALVSYNC = 1;
485 opts->canUseFSSYNC = 1;
489 opts->nLargeVnodes = 0;
490 opts->nSmallVnodes = 0;
492 opts->canScheduleSalvage = 1;
493 opts->canUseFSSYNC = 1;
503 * Set VInit to a certain value, and signal waiters.
505 * @param[in] value the value to set VInit to
510 VSetVInit_r(int value)
513 opr_cv_broadcast(&vol_vinit_cond);
517 VLogOfflineTimeout(const char *type, afs_int32 timeout)
523 Log("VInitVolumePackage: Interrupting clients accessing %s "
524 "immediately\n", type);
526 Log("VInitVolumePackage: Interrupting clients accessing %s "
527 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
532 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
534 int errors = 0; /* Number of errors while finding vice partitions. */
539 #ifndef AFS_PTHREAD_ENV
540 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
541 Log("VInitVolumePackage: offline_timeout and/or "
542 "offline_shutdown_timeout was specified, but the volume package "
543 "does not support these for LWP builds\n");
547 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
548 VLogOfflineTimeout("volumes going offline during shutdown",
549 opts->offline_shutdown_timeout);
551 memset(&VStats, 0, sizeof(VStats));
552 VStats.hdr_cache_size = 200;
554 VInitPartitionPackage();
556 #ifdef AFS_DEMAND_ATTACH_FS
557 if (programType == fileServer) {
560 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
562 opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
565 opr_mutex_init(&vol_glock_mutex);
566 opr_mutex_init(&vol_trans_mutex);
567 opr_cv_init(&vol_put_volume_cond);
568 opr_cv_init(&vol_sleep_cond);
569 opr_cv_init(&vol_init_attach_cond);
570 opr_cv_init(&vol_vinit_cond);
571 #ifndef AFS_PTHREAD_ENV
573 #endif /* AFS_PTHREAD_ENV */
574 Lock_Init(&vol_listLock);
576 srandom(time(0)); /* For VGetVolumeInfo */
578 #ifdef AFS_DEMAND_ATTACH_FS
579 opr_mutex_init(&vol_salvsync_mutex);
580 #endif /* AFS_DEMAND_ATTACH_FS */
582 /* Ok, we have done enough initialization that fileserver can
583 * start accepting calls, even though the volumes may not be
584 * available just yet.
588 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
589 if (programType == salvageServer) {
592 #endif /* AFS_DEMAND_ATTACH_FS */
593 #ifdef FSSYNC_BUILD_SERVER
594 if (programType == fileServer) {
598 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
599 if (VCanUseSALVSYNC()) {
600 /* establish a connection to the salvager at this point */
601 opr_Verify(VConnectSALV() != 0);
603 #endif /* AFS_DEMAND_ATTACH_FS */
605 if (opts->volcache > VStats.hdr_cache_size)
606 VStats.hdr_cache_size = opts->volcache;
607 VInitVolumeHeaderCache(VStats.hdr_cache_size);
609 VInitVnodes(vLarge, opts->nLargeVnodes);
610 VInitVnodes(vSmall, opts->nSmallVnodes);
613 errors = VAttachPartitions();
617 if (programType != fileServer) {
618 errors = VInitAttachVolumes(programType);
624 #ifdef FSSYNC_BUILD_CLIENT
625 if (VCanUseFSSYNC()) {
627 #ifdef AFS_DEMAND_ATTACH_FS
628 if (programType == salvageServer) {
629 Log("Unable to connect to file server; aborted\n");
632 #endif /* AFS_DEMAND_ATTACH_FS */
633 Log("Unable to connect to file server; will retry at need\n");
636 #endif /* FSSYNC_BUILD_CLIENT */
641 #if !defined(AFS_PTHREAD_ENV)
643 * Attach volumes in vice partitions
645 * @param[in] pt calling program type
648 * @note This is the original, non-threaded version of attach parititions.
650 * @post VInit state is 2
653 VInitAttachVolumes(ProgramType pt)
655 opr_Assert(VInit==1);
656 if (pt == fileServer) {
657 struct DiskPartition64 *diskP;
658 /* Attach all the volumes in this partition */
659 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
660 int nAttached = 0, nUnattached = 0;
661 opr_Verify(VAttachVolumesByPartition(diskP,
662 &nAttached, &nUnattached)
667 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
668 LWP_NoYieldSignal(VInitAttachVolumes);
672 #endif /* !AFS_PTHREAD_ENV */
674 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
676 * Attach volumes in vice partitions
678 * @param[in] pt calling program type
681 * @note Threaded version of attach parititions.
683 * @post VInit state is 2
686 VInitAttachVolumes(ProgramType pt)
688 opr_Assert(VInit==1);
689 if (pt == fileServer) {
690 struct DiskPartition64 *diskP;
691 struct vinitvolumepackage_thread_t params;
692 struct diskpartition_queue_t * dpq;
693 int i, threads, parts;
695 pthread_attr_t attrs;
697 opr_cv_init(¶ms.thread_done_cv);
699 params.n_threads_complete = 0;
701 /* create partition work queue */
702 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
703 dpq = malloc(sizeof(struct diskpartition_queue_t));
704 opr_Assert(dpq != NULL);
706 queue_Append(¶ms,dpq);
709 threads = min(parts, vol_attach_threads);
712 /* spawn off a bunch of initialization threads */
713 opr_Verify(pthread_attr_init(&attrs) == 0);
714 opr_Verify(pthread_attr_setdetachstate(&attrs,
715 PTHREAD_CREATE_DETACHED)
718 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
719 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
723 for (i=0; i < threads; i++) {
726 opr_Verify(pthread_create(&tid, &attrs,
727 &VInitVolumePackageThread,
729 AFS_SIGSET_RESTORE();
732 while(params.n_threads_complete < threads) {
733 VOL_CV_WAIT(¶ms.thread_done_cv);
737 opr_Verify(pthread_attr_destroy(&attrs) == 0);
739 /* if we're only going to run one init thread, don't bother creating
741 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
742 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
745 VInitVolumePackageThread(¶ms);
748 opr_cv_destroy(¶ms.thread_done_cv);
751 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
752 opr_cv_broadcast(&vol_init_attach_cond);
758 VInitVolumePackageThread(void * args) {
760 struct DiskPartition64 *diskP;
761 struct vinitvolumepackage_thread_t * params;
762 struct diskpartition_queue_t * dpq;
764 params = (vinitvolumepackage_thread_t *) args;
768 /* Attach all the volumes in this partition */
769 while (queue_IsNotEmpty(params)) {
770 int nAttached = 0, nUnattached = 0;
772 if (vinit_attach_abort) {
773 Log("Aborting initialization\n");
777 dpq = queue_First(params,diskpartition_queue_t);
783 opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
790 params->n_threads_complete++;
791 opr_cv_signal(¶ms->thread_done_cv);
795 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
797 #if defined(AFS_DEMAND_ATTACH_FS)
799 * Attach volumes in vice partitions
801 * @param[in] pt calling program type
804 * @note Threaded version of attach partitions.
806 * @post VInit state is 2
809 VInitAttachVolumes(ProgramType pt)
811 opr_Assert(VInit==1);
812 if (pt == fileServer) {
814 struct DiskPartition64 *diskP;
815 struct partition_queue pq;
816 struct volume_init_queue vq;
818 int i, threads, parts;
820 pthread_attr_t attrs;
822 /* create partition work queue */
825 opr_mutex_init(&pq.mutex);
826 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
827 struct diskpartition_queue_t *dp;
828 dp = malloc(sizeof(struct diskpartition_queue_t));
829 opr_Assert(dp != NULL);
831 queue_Append(&pq, dp);
834 /* number of worker threads; at least one, not to exceed the number of partitions */
835 threads = min(parts, vol_attach_threads);
837 /* create volume work queue */
840 opr_mutex_init(&vq.mutex);
842 opr_Verify(pthread_attr_init(&attrs) == 0);
843 opr_Verify(pthread_attr_setdetachstate(&attrs,
844 PTHREAD_CREATE_DETACHED) == 0);
846 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
847 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
850 /* create threads to scan disk partitions. */
851 for (i=0; i < threads; i++) {
852 struct vinitvolumepackage_thread_param *params;
855 params = malloc(sizeof(struct vinitvolumepackage_thread_param));
859 params->nthreads = threads;
860 params->thread = i+1;
863 opr_Verify(pthread_create(&tid, &attrs,
864 &VInitVolumePackageThread,
865 (void*)params) == 0);
866 AFS_SIGSET_RESTORE();
869 VInitPreAttachVolumes(threads, &vq);
871 opr_Verify(pthread_attr_destroy(&attrs) == 0);
872 opr_cv_destroy(&pq.cv);
873 opr_mutex_destroy(&pq.mutex);
874 opr_cv_destroy(&vq.cv);
875 opr_mutex_destroy(&vq.mutex);
879 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
880 opr_cv_broadcast(&vol_init_attach_cond);
887 * Volume package initialization worker thread. Scan partitions for volume
888 * header files. Gather batches of volume ids and dispatch them to
889 * the main thread to be preattached. The volume preattachement is done
890 * in the main thread to avoid global volume lock contention.
893 VInitVolumePackageThread(void *args)
895 struct vinitvolumepackage_thread_param *params;
896 struct DiskPartition64 *partition;
897 struct partition_queue *pq;
898 struct volume_init_queue *vq;
899 struct volume_init_batch *vb;
902 params = (struct vinitvolumepackage_thread_param *)args;
908 vb = malloc(sizeof(struct volume_init_batch));
910 vb->thread = params->thread;
914 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
915 while((partition = VInitNextPartition(pq))) {
919 Log("Partition %s: pre-attaching volumes\n", partition->name);
920 dirp = opendir(VPartitionPath(partition));
922 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
925 while ((vid = VInitNextVolumeId(dirp))) {
926 Volume *vp = calloc(1, sizeof(Volume));
928 vp->device = partition->device;
929 vp->partition = partition;
931 queue_Init(&vp->vnode_list);
932 queue_Init(&vp->rx_call_list);
933 opr_cv_init(&V_attachCV(vp));
935 vb->batch[vb->size++] = vp;
936 if (vb->size == VINIT_BATCH_MAX_SIZE) {
937 opr_mutex_enter(&vq->mutex);
938 queue_Append(vq, vb);
939 opr_cv_broadcast(&vq->cv);
940 opr_mutex_exit(&vq->mutex);
942 vb = malloc(sizeof(struct volume_init_batch));
944 vb->thread = params->thread;
953 opr_mutex_enter(&vq->mutex);
954 queue_Append(vq, vb);
955 opr_cv_broadcast(&vq->cv);
956 opr_mutex_exit(&vq->mutex);
958 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
964 * Read next element from the pre-populated partition list.
966 static struct DiskPartition64*
967 VInitNextPartition(struct partition_queue *pq)
969 struct DiskPartition64 *partition;
970 struct diskpartition_queue_t *dp; /* queue element */
972 if (vinit_attach_abort) {
973 Log("Aborting volume preattach thread.\n");
977 /* get next partition to scan */
978 opr_mutex_enter(&pq->mutex);
979 if (queue_IsEmpty(pq)) {
980 opr_mutex_exit(&pq->mutex);
983 dp = queue_First(pq, diskpartition_queue_t);
985 opr_mutex_exit(&pq->mutex);
988 opr_Assert(dp->diskP);
990 partition = dp->diskP;
996 * Find next volume id on the partition.
999 VInitNextVolumeId(DIR *dirp)
1005 while((d = readdir(dirp))) {
1006 if (vinit_attach_abort) {
1007 Log("Aborting volume preattach thread.\n");
1010 ext = strrchr(d->d_name, '.');
1011 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1012 vid = VolumeNumber(d->d_name);
1016 Log("Warning: bogus volume header file: %s\n", d->d_name);
1023 * Preattach volumes in batches to avoid lock contention.
1026 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1028 struct volume_init_batch *vb;
1032 /* dequeue next volume */
1033 opr_mutex_enter(&vq->mutex);
1034 if (queue_IsEmpty(vq)) {
1035 opr_cv_wait(&vq->cv, &vq->mutex);
1037 vb = queue_First(vq, volume_init_batch);
1039 opr_mutex_exit(&vq->mutex);
1043 for (i = 0; i<vb->size; i++) {
1049 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1051 Log("Error looking up volume, code=%d\n", ec);
1054 Log("Warning: Duplicate volume id %" AFS_VOLID_FMT " detected.\n", afs_printable_VolumeId_lu(vp->hashid));
1057 /* put pre-attached volume onto the hash table
1058 * and bring it up to the pre-attached state */
1059 AddVolumeToHashTable(vp, vp->hashid);
1060 AddVolumeToVByPList_r(vp);
1061 VLRU_Init_Node_r(vp);
1062 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1075 #endif /* AFS_DEMAND_ATTACH_FS */
1077 #if !defined(AFS_DEMAND_ATTACH_FS)
1079 * attach all volumes on a given disk partition
1082 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1088 Log("Partition %s: attaching volumes\n", diskP->name);
1089 dirp = opendir(VPartitionPath(diskP));
1091 Log("opendir on Partition %s failed!\n", diskP->name);
1095 while ((dp = readdir(dirp))) {
1097 p = strrchr(dp->d_name, '.');
1099 if (vinit_attach_abort) {
1100 Log("Partition %s: abort attach volumes\n", diskP->name);
1104 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1107 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1109 (*(vp ? nAttached : nUnattached))++;
1110 if (error == VOFFLINE)
1111 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1112 else if (GetLogLevel() >= 5) {
1113 Log("Partition %s: attached volume %d (%s)\n",
1114 diskP->name, VolumeNumber(dp->d_name),
1123 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1128 #endif /* !AFS_DEMAND_ATTACH_FS */
1130 /***************************************************/
1131 /* Shutdown routines */
1132 /***************************************************/
1136 * highly multithreaded volume package shutdown
1138 * with the demand attach fileserver extensions,
1139 * VShutdown has been modified to be multithreaded.
1140 * In order to achieve optimal use of many threads,
1141 * the shutdown code involves one control thread and
1142 * n shutdown worker threads. The control thread
1143 * periodically examines the number of volumes available
1144 * for shutdown on each partition, and produces a worker
1145 * thread allocation schedule. The idea is to eliminate
1146 * redundant scheduling computation on the workers by
1147 * having a single master scheduler.
1149 * The scheduler's objectives are:
1151 * each partition with volumes remaining gets allocated
1152 * at least 1 thread (assuming sufficient threads)
1154 * threads are allocated proportional to the number of
1155 * volumes remaining to be offlined. This ensures that
1156 * the OS I/O scheduler has many requests to elevator
1157 * seek on partitions that will (presumably) take the
1158 * longest amount of time (from now) to finish shutdown
1159 * (3) keep threads busy
1160 * when there are extra threads, they are assigned to
1161 * partitions using a simple round-robin algorithm
1163 * In the future, we may wish to add the ability to adapt
1164 * to the relative performance patterns of each disk
1169 * multi-step shutdown process
1171 * demand attach shutdown is a four-step process. Each
1172 * shutdown "pass" shuts down increasingly more difficult
1173 * volumes. The main purpose is to achieve better cache
1174 * utilization during shutdown.
1177 * shutdown volumes in the unattached, pre-attached
1180 * shutdown attached volumes with cached volume headers
1182 * shutdown all volumes in non-exclusive states
1184 * shutdown all remaining volumes
1187 #ifdef AFS_DEMAND_ATTACH_FS
1193 struct DiskPartition64 * diskP;
1194 struct diskpartition_queue_t * dpq;
1195 vshutdown_thread_t params;
1197 pthread_attr_t attrs;
1199 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1202 Log("VShutdown: aborting attach volumes\n");
1203 vinit_attach_abort = 1;
1204 VOL_CV_WAIT(&vol_init_attach_cond);
1207 for (params.n_parts=0, diskP = DiskPartitionList;
1208 diskP; diskP = diskP->next, params.n_parts++);
1210 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1211 params.n_parts, params.n_parts > 1 ? "s" : "");
1213 vol_shutting_down = 1;
1215 if (vol_attach_threads > 1) {
1216 /* prepare for parallel shutdown */
1217 params.n_threads = vol_attach_threads;
1218 opr_mutex_init(¶ms.lock);
1219 opr_cv_init(¶ms.cv);
1220 opr_cv_init(¶ms.master_cv);
1221 opr_Verify(pthread_attr_init(&attrs) == 0);
1222 opr_Verify(pthread_attr_setdetachstate(&attrs,
1223 PTHREAD_CREATE_DETACHED) == 0);
1224 queue_Init(¶ms);
1226 /* setup the basic partition information structures for
1227 * parallel shutdown */
1228 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1230 struct rx_queue * qp, * nqp;
1234 VVByPListWait_r(diskP);
1235 VVByPListBeginExclusive_r(diskP);
1238 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1239 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1243 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1244 VPartitionPath(diskP), count);
1247 /* build up the pass 0 shutdown work queue */
1248 dpq = malloc(sizeof(struct diskpartition_queue_t));
1249 opr_Assert(dpq != NULL);
1251 queue_Prepend(¶ms, dpq);
1253 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1256 Log("VShutdown: beginning parallel fileserver shutdown\n");
1257 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1258 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1260 /* do pass 0 shutdown */
1261 opr_mutex_enter(¶ms.lock);
1262 for (i=0; i < params.n_threads; i++) {
1263 opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1267 /* wait for all the pass 0 shutdowns to complete */
1268 while (params.n_threads_complete < params.n_threads) {
1269 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1271 params.n_threads_complete = 0;
1273 opr_cv_broadcast(¶ms.cv);
1274 opr_mutex_exit(¶ms.lock);
1276 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1277 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1279 /* run the parallel shutdown scheduler. it will drop the glock internally */
1280 ShutdownController(¶ms);
1282 /* wait for all the workers to finish pass 3 and terminate */
1283 while (params.pass < 4) {
1284 VOL_CV_WAIT(¶ms.cv);
1287 opr_Verify(pthread_attr_destroy(&attrs) == 0);
1288 opr_cv_destroy(¶ms.cv);
1289 opr_cv_destroy(¶ms.master_cv);
1290 opr_mutex_destroy(¶ms.lock);
1292 /* drop the VByPList exclusive reservations */
1293 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1294 VVByPListEndExclusive_r(diskP);
1295 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1296 VPartitionPath(diskP),
1297 params.stats[0][diskP->index],
1298 params.stats[1][diskP->index],
1299 params.stats[2][diskP->index],
1300 params.stats[3][diskP->index]);
1303 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1305 /* if we're only going to run one shutdown thread, don't bother creating
1307 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1309 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1310 VShutdownByPartition_r(diskP);
1314 Log("VShutdown: complete.\n");
1317 #else /* AFS_DEMAND_ATTACH_FS */
1327 Log("VShutdown: aborting attach volumes\n");
1328 vinit_attach_abort = 1;
1329 #ifdef AFS_PTHREAD_ENV
1330 VOL_CV_WAIT(&vol_init_attach_cond);
1332 LWP_WaitProcess(VInitAttachVolumes);
1333 #endif /* AFS_PTHREAD_ENV */
1336 Log("VShutdown: shutting down on-line volumes...\n");
1337 vol_shutting_down = 1;
1338 for (i = 0; i < VolumeHashTable.Size; i++) {
1339 /* try to hold first volume in the hash table */
1340 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1343 if (GetLogLevel() >= 5)
1344 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1345 afs_printable_VolumeId_lu(vp->hashid));
1347 /* next, take the volume offline (drops reference count) */
1348 VOffline_r(vp, "File server was shut down");
1352 Log("VShutdown: complete.\n");
1354 #endif /* AFS_DEMAND_ATTACH_FS */
1360 opr_Assert(VInit>0);
1367 * stop new activity (e.g. SALVSYNC) from occurring
1369 * Use this to make the volume package less busy; for example, during
1370 * shutdown. This doesn't actually shutdown/detach anything in the
1371 * volume package, but prevents certain processes from ocurring. For
1372 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1373 * could also use this to prevent new volume attachment, or prevent
1374 * other programs from checking out volumes, etc.
1379 #ifdef AFS_DEMAND_ATTACH_FS
1380 /* make sure we don't try to contact the salvageserver, since it may
1381 * not be around anymore */
1382 vol_disallow_salvsync = 1;
1386 #ifdef AFS_DEMAND_ATTACH_FS
1389 * shutdown control thread
1392 ShutdownController(vshutdown_thread_t * params)
1395 struct DiskPartition64 * diskP;
1397 vshutdown_thread_t shadow;
1399 ShutdownCreateSchedule(params);
1401 while ((params->pass < 4) &&
1402 (params->n_threads_complete < params->n_threads)) {
1403 /* recompute schedule once per second */
1405 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1409 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1410 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1411 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1412 shadow.n_threads_complete, shadow.n_parts_done_pass);
1413 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1415 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1417 diskP->vol_list.len,
1418 shadow.part_thread_target[id],
1419 shadow.part_done_pass[id],
1420 shadow.part_pass_head[id]);
1426 ShutdownCreateSchedule(params);
1430 /* create the shutdown thread work schedule.
1431 * this scheduler tries to implement fairness
1432 * by allocating at least 1 thread to each
1433 * partition with volumes to be shutdown,
1434 * and then it attempts to allocate remaining
1435 * threads based upon the amount of work left
1438 ShutdownCreateSchedule(vshutdown_thread_t * params)
1440 struct DiskPartition64 * diskP;
1441 int sum, thr_workload, thr_left;
1442 int part_residue[VOLMAXPARTS+1];
1445 /* compute the total number of outstanding volumes */
1447 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1448 sum += diskP->vol_list.len;
1451 params->schedule_version++;
1452 params->vol_remaining = sum;
1457 /* compute average per-thread workload */
1458 thr_workload = sum / params->n_threads;
1459 if (sum % params->n_threads)
1462 thr_left = params->n_threads;
1463 memset(&part_residue, 0, sizeof(part_residue));
1465 /* for fairness, give every partition with volumes remaining
1466 * at least one thread */
1467 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1469 if (diskP->vol_list.len) {
1470 params->part_thread_target[id] = 1;
1473 params->part_thread_target[id] = 0;
1477 if (thr_left && thr_workload) {
1478 /* compute length-weighted workloads */
1481 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1483 delta = (diskP->vol_list.len / thr_workload) -
1484 params->part_thread_target[id];
1488 if (delta < thr_left) {
1489 params->part_thread_target[id] += delta;
1492 params->part_thread_target[id] += thr_left;
1500 /* try to assign any leftover threads to partitions that
1501 * had volume lengths closer to needing thread_target+1 */
1502 int max_residue, max_id = 0;
1504 /* compute the residues */
1505 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1507 part_residue[id] = diskP->vol_list.len -
1508 (params->part_thread_target[id] * thr_workload);
1511 /* now try to allocate remaining threads to partitions with the
1512 * highest residues */
1515 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1517 if (part_residue[id] > max_residue) {
1518 max_residue = part_residue[id];
1527 params->part_thread_target[max_id]++;
1529 part_residue[max_id] = 0;
1534 /* punt and give any remaining threads equally to each partition */
1536 if (thr_left >= params->n_parts) {
1537 alloc = thr_left / params->n_parts;
1538 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1540 params->part_thread_target[id] += alloc;
1545 /* finish off the last of the threads */
1546 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1548 params->part_thread_target[id]++;
1554 /* worker thread for parallel shutdown */
1556 VShutdownThread(void * args)
1558 vshutdown_thread_t * params;
1559 int found, pass, schedule_version_save, count;
1560 struct DiskPartition64 *diskP;
1561 struct diskpartition_queue_t * dpq;
1564 params = (vshutdown_thread_t *) args;
1566 /* acquire the shutdown pass 0 lock */
1567 opr_mutex_enter(¶ms->lock);
1569 /* if there's still pass 0 work to be done,
1570 * get a work entry, and do a pass 0 shutdown */
1571 if (queue_IsNotEmpty(params)) {
1572 dpq = queue_First(params, diskpartition_queue_t);
1574 opr_mutex_exit(¶ms->lock);
1580 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1582 params->stats[0][diskP->index] = count;
1583 opr_mutex_enter(¶ms->lock);
1586 params->n_threads_complete++;
1587 if (params->n_threads_complete == params->n_threads) {
1588 /* notify control thread that all workers have completed pass 0 */
1589 opr_cv_signal(¶ms->master_cv);
1591 while (params->pass == 0) {
1592 opr_cv_wait(¶ms->cv, ¶ms->lock);
1596 opr_mutex_exit(¶ms->lock);
1599 pass = params->pass;
1600 opr_Assert(pass > 0);
1602 /* now escalate through the more complicated shutdowns */
1604 schedule_version_save = params->schedule_version;
1606 /* find a disk partition to work on */
1607 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1609 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1610 params->part_thread_target[id]--;
1617 /* hmm. for some reason the controller thread couldn't find anything for
1618 * us to do. let's see if there's anything we can do */
1619 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1621 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1624 } else if (!params->part_done_pass[id]) {
1625 params->part_done_pass[id] = 1;
1626 params->n_parts_done_pass++;
1628 Log("VShutdown: done shutting down volumes on partition %s.\n",
1629 VPartitionPath(diskP));
1635 /* do work on this partition until either the controller
1636 * creates a new schedule, or we run out of things to do
1637 * on this partition */
1640 while (!params->part_done_pass[id] &&
1641 (schedule_version_save == params->schedule_version)) {
1642 /* ShutdownVolumeWalk_r will drop the glock internally */
1643 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1644 if (!params->part_done_pass[id]) {
1645 params->part_done_pass[id] = 1;
1646 params->n_parts_done_pass++;
1648 Log("VShutdown: done shutting down volumes on partition %s.\n",
1649 VPartitionPath(diskP));
1657 params->stats[pass][id] += count;
1659 /* ok, everyone is done this pass, proceed */
1662 params->n_threads_complete++;
1663 while (params->pass == pass) {
1664 if (params->n_threads_complete == params->n_threads) {
1665 /* we are the last thread to complete, so we will
1666 * reinitialize worker pool state for the next pass */
1667 params->n_threads_complete = 0;
1668 params->n_parts_done_pass = 0;
1670 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1672 params->part_done_pass[id] = 0;
1673 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1676 /* compute a new thread schedule before releasing all the workers */
1677 ShutdownCreateSchedule(params);
1679 /* wake up all the workers */
1680 opr_cv_broadcast(¶ms->cv);
1683 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1684 pass, params->n_threads, params->n_parts);
1687 VOL_CV_WAIT(¶ms->cv);
1690 pass = params->pass;
1704 /* shut down all volumes on a given disk partition
1706 * note that this function will not allow mp-fast
1707 * shutdown of a partition */
1709 VShutdownByPartition_r(struct DiskPartition64 * dp)
1715 /* wait for other exclusive ops to finish */
1716 VVByPListWait_r(dp);
1718 /* begin exclusive access */
1719 VVByPListBeginExclusive_r(dp);
1721 /* pick the low-hanging fruit first,
1722 * then do the complicated ones last
1723 * (has the advantage of keeping
1724 * in-use volumes up until the bitter end) */
1725 for (pass = 0, total=0; pass < 4; pass++) {
1726 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1727 total += pass_stats[pass];
1730 /* end exclusive access */
1731 VVByPListEndExclusive_r(dp);
1733 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1734 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1739 /* internal shutdown functionality
1741 * for multi-pass shutdown:
1742 * 0 to only "shutdown" {pre,un}attached and error state volumes
1743 * 1 to also shutdown attached volumes w/ volume header loaded
1744 * 2 to also shutdown attached volumes w/o volume header loaded
1745 * 3 to also shutdown exclusive state volumes
1747 * caller MUST hold exclusive access on the hash chain
1748 * because we drop vol_glock_mutex internally
1750 * this function is reentrant for passes 1--3
1751 * (e.g. multiple threads can cooperate to
1752 * shutdown a partition mp-fast)
1754 * pass 0 is not scaleable because the volume state data is
1755 * synchronized by vol_glock mutex, and the locking overhead
1756 * is too high to drop the lock long enough to do linked list
1760 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1762 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1764 const char *pass_strs[4] = {"{un/pre}attached vols", "vols w/ vol header loaded", "vols w/o vol header loaded", "vols with exclusive state"};
1766 while (ShutdownVolumeWalk_r(dp, pass, &q)) {
1769 Log("VShutdownByPartition: ... shut down %d volumes on %s in pass %d (%s)\n", i, VPartitionPath(dp), pass, pass_strs[pass]);
1776 /* conditionally shutdown one volume on partition dp
1777 * returns 1 if a volume was shutdown in this pass,
1780 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1781 struct rx_queue ** idx)
1783 struct rx_queue *qp, *nqp;
1788 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1789 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1793 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1794 (V_attachState(vp) != VOL_STATE_ERROR) &&
1795 (V_attachState(vp) != VOL_STATE_DELETED) &&
1796 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1800 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1801 (vp->header == NULL)) {
1805 if (VIsExclusiveState(V_attachState(vp))) {
1810 DeleteVolumeFromVByPList_r(vp);
1811 VShutdownVolume_r(vp);
1821 * shutdown a specific volume
1823 /* caller MUST NOT hold a heavyweight ref on vp */
1825 VShutdownVolume_r(Volume * vp)
1829 VCreateReservation_r(vp);
1831 if (GetLogLevel() >= 5) {
1832 Log("VShutdownVolume_r: vid=%" AFS_VOLID_FMT ", device=%d, state=%u\n",
1833 afs_printable_VolumeId_lu(vp->hashid), vp->partition->device,
1834 (unsigned int) V_attachState(vp));
1837 /* wait for other blocking ops to finish */
1838 VWaitExclusiveState_r(vp);
1840 opr_Assert(VIsValidState(V_attachState(vp)));
1842 switch(V_attachState(vp)) {
1843 case VOL_STATE_SALVAGING:
1844 /* Leave salvaging volumes alone. Any in-progress salvages will
1845 * continue working after viced shuts down. This is intentional.
1848 case VOL_STATE_PREATTACHED:
1849 case VOL_STATE_ERROR:
1850 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1851 case VOL_STATE_UNATTACHED:
1852 case VOL_STATE_DELETED:
1854 case VOL_STATE_GOING_OFFLINE:
1855 case VOL_STATE_SHUTTING_DOWN:
1856 case VOL_STATE_ATTACHED:
1859 if (GetLogLevel() >= 5)
1860 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1861 afs_printable_VolumeId_lu(vp->hashid));
1863 /* take the volume offline (drops reference count) */
1864 VOffline_r(vp, "File server was shut down");
1871 VCancelReservation_r(vp);
1875 #endif /* AFS_DEMAND_ATTACH_FS */
1878 /***************************************************/
1879 /* Header I/O routines */
1880 /***************************************************/
1883 HeaderName(bit32 magic)
1886 case VOLUMEINFOMAGIC:
1887 return "volume info";
1888 case SMALLINDEXMAGIC:
1889 return "small index";
1890 case LARGEINDEXMAGIC:
1891 return "large index";
1892 case LINKTABLEMAGIC:
1893 return "link table";
1898 /* open a descriptor for the inode (h),
1899 * read in an on-disk structure into buffer (to) of size (size),
1900 * verify versionstamp in structure has magic (magic) and
1901 * optionally verify version (version) if (version) is nonzero
1904 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1907 struct versionStamp *vsn;
1909 afs_sfsize_t nbytes;
1914 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1922 Log("ReadHeader: Failed to open %s header file "
1923 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1924 PrintInode(stmp, h->ih_ino), errno);
1929 vsn = (struct versionStamp *)to;
1930 nbytes = FDH_PREAD(fdP, to, size, 0);
1932 Log("ReadHeader: Failed to read %s header file "
1933 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1934 PrintInode(stmp, h->ih_ino), errno);
1936 FDH_REALLYCLOSE(fdP);
1939 if (nbytes != size) {
1940 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1941 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%d, read=%d\n",
1942 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1943 PrintInode(stmp, h->ih_ino), size, (int)nbytes);
1945 FDH_REALLYCLOSE(fdP);
1948 if (vsn->magic != magic) {
1949 Log("ReadHeader: Incorrect magic for %s header file "
1950 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=0x%x, read=0x%x\n",
1951 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1952 PrintInode(stmp, h->ih_ino), magic, vsn->magic);
1954 FDH_REALLYCLOSE(fdP);
1960 /* Check is conditional, in case caller wants to inspect version himself */
1961 if (version && vsn->version != version) {
1962 Log("ReadHeader: Incorrect version for %s header file "
1963 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%x, read=%x\n",
1964 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid), PrintInode(stmp, h->ih_ino),
1965 version, vsn->version);
1971 WriteVolumeHeader_r(Error * ec, Volume * vp)
1973 IHandle_t *h = V_diskDataHandle(vp);
1983 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1984 != sizeof(V_disk(vp))) {
1986 FDH_REALLYCLOSE(fdP);
1992 /* VolumeHeaderToDisk
1993 * Allows for storing 64 bit inode numbers in on-disk volume header
1996 /* convert in-memory representation of a volume header to the
1997 * on-disk representation of a volume header */
1999 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2002 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2003 dh->stamp = h->stamp;
2005 dh->parent = h->parent;
2007 #ifdef AFS_64BIT_IOPS_ENV
2008 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2009 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2010 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2011 dh->smallVnodeIndex_hi =
2012 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2013 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2014 dh->largeVnodeIndex_hi =
2015 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2016 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2017 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2019 dh->volumeInfo_lo = h->volumeInfo;
2020 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2021 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2022 dh->linkTable_lo = h->linkTable;
2026 /* DiskToVolumeHeader
2027 * Converts an on-disk representation of a volume header to
2028 * the in-memory representation of a volume header.
2030 * Makes the assumption that AFS has *always*
2031 * zero'd the volume header file so that high parts of inode
2032 * numbers are 0 in older (SGI EFS) volume header files.
2035 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2037 memset(h, 0, sizeof(VolumeHeader_t));
2038 h->stamp = dh->stamp;
2040 h->parent = dh->parent;
2042 #ifdef AFS_64BIT_IOPS_ENV
2044 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2046 h->smallVnodeIndex =
2047 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2048 smallVnodeIndex_hi << 32);
2050 h->largeVnodeIndex =
2051 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2052 largeVnodeIndex_hi << 32);
2054 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2056 h->volumeInfo = dh->volumeInfo_lo;
2057 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2058 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2059 h->linkTable = dh->linkTable_lo;
2064 /***************************************************/
2065 /* Volume Attachment routines */
2066 /***************************************************/
2068 #ifdef AFS_DEMAND_ATTACH_FS
2070 * pre-attach a volume given its path.
2072 * @param[out] ec outbound error code
2073 * @param[in] partition partition path string
2074 * @param[in] name volume id string
2076 * @return volume object pointer
2078 * @note A pre-attached volume will only have its partition
2079 * and hashid fields initialized. At first call to
2080 * VGetVolume, the volume will be fully attached.
2084 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2088 vp = VPreAttachVolumeByName_r(ec, partition, name);
2094 * pre-attach a volume given its path.
2096 * @param[out] ec outbound error code
2097 * @param[in] partition path to vice partition
2098 * @param[in] name volume id string
2100 * @return volume object pointer
2102 * @pre VOL_LOCK held
2104 * @internal volume package internal use only.
2107 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2109 return VPreAttachVolumeById_r(ec,
2111 VolumeNumber(name));
2115 * pre-attach a volume given its path and numeric volume id.
2117 * @param[out] ec error code return
2118 * @param[in] partition path to vice partition
2119 * @param[in] volumeId numeric volume id
2121 * @return volume object pointer
2123 * @pre VOL_LOCK held
2125 * @internal volume package internal use only.
2128 VPreAttachVolumeById_r(Error * ec,
2133 struct DiskPartition64 *partp;
2137 opr_Assert(programType == fileServer);
2139 if (!(partp = VGetPartition_r(partition, 0))) {
2141 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2145 /* ensure that any vp we pass to VPreAttachVolumeByVp_r
2146 * is NOT in exclusive state.
2149 vp = VLookupVolume_r(ec, volumeId, NULL);
2155 if (vp && VIsExclusiveState(V_attachState(vp))) {
2156 VCreateReservation_r(vp);
2157 VWaitExclusiveState_r(vp);
2158 VCancelReservation_r(vp);
2160 goto retry; /* look up volume again */
2163 /* vp == NULL or vp not exclusive both OK */
2165 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2169 * preattach a volume.
2171 * @param[out] ec outbound error code
2172 * @param[in] partp pointer to partition object
2173 * @param[in] vp pointer to volume object
2174 * @param[in] vid volume id
2176 * @return volume object pointer
2178 * @pre VOL_LOCK is held.
2180 * @pre vp (if specified) must not be in exclusive state.
2182 * @warning Returned volume object pointer does not have to
2183 * equal the pointer passed in as argument vp. There
2184 * are potential race conditions which can result in
2185 * the pointers having different values. It is up to
2186 * the caller to make sure that references are handled
2187 * properly in this case.
2189 * @note If there is already a volume object registered with
2190 * the same volume id, its pointer MUST be passed as
2191 * argument vp. Failure to do so will result in a silent
2192 * failure to preattach.
2194 * @internal volume package internal use only.
2197 VPreAttachVolumeByVp_r(Error * ec,
2198 struct DiskPartition64 * partp,
2206 /* don't proceed unless it's safe */
2208 opr_Assert(!VIsExclusiveState(V_attachState(vp)));
2211 /* check to see if pre-attach already happened */
2213 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2214 (V_attachState(vp) != VOL_STATE_DELETED) &&
2215 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2216 !VIsErrorState(V_attachState(vp))) {
2218 * pre-attach is a no-op in all but the following cases:
2220 * - volume is unattached
2221 * - volume is in an error state
2222 * - volume is pre-attached
2224 Log("VPreattachVolumeByVp_r: volume %" AFS_VOLID_FMT " not in quiescent state (state %u flags 0x%x)\n",
2225 afs_printable_VolumeId_lu(vid), V_attachState(vp),
2229 /* we're re-attaching a volume; clear out some old state */
2230 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2232 if (V_partition(vp) != partp) {
2233 /* XXX potential race */
2234 DeleteVolumeFromVByPList_r(vp);
2237 /* if we need to allocate a new Volume struct,
2238 * go ahead and drop the vol glock, otherwise
2239 * do the basic setup synchronised, as it's
2240 * probably not worth dropping the lock */
2243 /* allocate the volume structure */
2244 vp = nvp = calloc(1, sizeof(Volume));
2245 opr_Assert(vp != NULL);
2246 queue_Init(&vp->vnode_list);
2247 queue_Init(&vp->rx_call_list);
2248 opr_cv_init(&V_attachCV(vp));
2251 /* link the volume with its associated vice partition */
2252 vp->device = partp->device;
2253 vp->partition = partp;
2256 vp->specialStatus = 0;
2258 /* if we dropped the lock, reacquire the lock,
2259 * check for pre-attach races, and then add
2260 * the volume to the hash table */
2263 nvp = VLookupVolume_r(ec, vid, NULL);
2268 } else if (nvp) { /* race detected */
2273 /* hack to make up for VChangeState_r() decrementing
2274 * the old state counter */
2275 VStats.state_levels[0]++;
2279 /* put pre-attached volume onto the hash table
2280 * and bring it up to the pre-attached state */
2281 AddVolumeToHashTable(vp, vp->hashid);
2282 AddVolumeToVByPList_r(vp);
2283 VLRU_Init_Node_r(vp);
2284 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2286 if (GetLogLevel() >= 5)
2287 Log("VPreAttachVolumeByVp_r: volume %" AFS_VOLID_FMT " pre-attached\n", afs_printable_VolumeId_lu(vp->hashid));
2295 #endif /* AFS_DEMAND_ATTACH_FS */
2297 /* Attach an existing volume, given its pathname, and return a
2298 pointer to the volume header information. The volume also
2299 normally goes online at this time. An offline volume
2300 must be reattached to make it go online */
2302 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2306 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2312 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2315 struct DiskPartition64 *partp;
2320 #ifdef AFS_DEMAND_ATTACH_FS
2321 VolumeStats stats_save;
2323 #endif /* AFS_DEMAND_ATTACH_FS */
2327 volumeId = VolumeNumber(name);
2329 if (!(partp = VGetPartition_r(partition, 0))) {
2331 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2335 if (VRequiresPartLock()) {
2336 opr_Assert(VInit == 3);
2337 VLockPartition_r(partition);
2338 } else if (programType == fileServer) {
2339 #ifdef AFS_DEMAND_ATTACH_FS
2340 /* lookup the volume in the hash table */
2341 vp = VLookupVolume_r(ec, volumeId, NULL);
2347 /* save any counters that are supposed to
2348 * be monotonically increasing over the
2349 * lifetime of the fileserver */
2350 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2352 memset(&stats_save, 0, sizeof(VolumeStats));
2355 /* if there's something in the hash table, and it's not
2356 * in the pre-attach state, then we may need to detach
2357 * it before proceeding */
2358 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2359 VCreateReservation_r(vp);
2360 VWaitExclusiveState_r(vp);
2362 /* at this point state must be one of:
2372 if (vp->specialStatus == VBUSY)
2375 /* if it's already attached, see if we can return it */
2376 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2377 VGetVolumeByVp_r(ec, vp);
2378 if (V_inUse(vp) == fileServer) {
2379 VCancelReservation_r(vp);
2383 /* otherwise, we need to detach, and attempt to re-attach */
2384 VDetachVolume_r(ec, vp);
2386 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2389 /* if it isn't fully attached, delete from the hash tables,
2390 and let the refcounter handle the rest */
2391 DeleteVolumeFromHashTable(vp);
2392 DeleteVolumeFromVByPList_r(vp);
2395 VCancelReservation_r(vp);
2399 /* pre-attach volume if it hasn't been done yet */
2401 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2402 (V_attachState(vp) == VOL_STATE_DELETED) ||
2403 (V_attachState(vp) == VOL_STATE_ERROR)) {
2405 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2411 opr_Assert(vp != NULL);
2413 /* handle pre-attach races
2415 * multiple threads can race to pre-attach a volume,
2416 * but we can't let them race beyond that
2418 * our solution is to let the first thread to bring
2419 * the volume into an exclusive state win; the other
2420 * threads just wait until it finishes bringing the
2421 * volume online, and then they do a vgetvolumebyvp
2423 if (svp && (svp != vp)) {
2424 /* wait for other exclusive ops to finish */
2425 VCreateReservation_r(vp);
2426 VWaitExclusiveState_r(vp);
2428 /* get a heavyweight ref, kill the lightweight ref, and return */
2429 VGetVolumeByVp_r(ec, vp);
2430 VCancelReservation_r(vp);
2434 /* at this point, we are chosen as the thread to do
2435 * demand attachment for this volume. all other threads
2436 * doing a getvolume on vp->hashid will block until we finish */
2438 /* make sure any old header cache entries are invalidated
2439 * before proceeding */
2440 FreeVolumeHeader(vp);
2442 VChangeState_r(vp, VOL_STATE_ATTACHING);
2444 /* restore any saved counters */
2445 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2446 #else /* AFS_DEMAND_ATTACH_FS */
2447 vp = VGetVolume_r(ec, volumeId);
2449 if (V_inUse(vp) == fileServer)
2451 if (vp->specialStatus == VBUSY)
2453 VDetachVolume_r(ec, vp);
2455 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2459 #endif /* AFS_DEMAND_ATTACH_FS */
2463 strcpy(path, VPartitionPath(partp));
2467 strcat(path, OS_DIRSEP);
2471 vp = (Volume *) calloc(1, sizeof(Volume));
2472 opr_Assert(vp != NULL);
2473 vp->hashid = volumeId;
2474 vp->device = partp->device;
2475 vp->partition = partp;
2476 queue_Init(&vp->vnode_list);
2477 queue_Init(&vp->rx_call_list);
2478 #ifdef AFS_DEMAND_ATTACH_FS
2479 opr_cv_init(&V_attachCV(vp));
2480 #endif /* AFS_DEMAND_ATTACH_FS */
2483 /* attach2 is entered without any locks, and returns
2484 * with vol_glock_mutex held */
2485 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2487 if (VCanUseFSSYNC() && vp) {
2488 #ifdef AFS_DEMAND_ATTACH_FS
2489 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2490 /* mark volume header as in use so that volser crashes lead to a
2491 * salvage attempt */
2492 VUpdateVolume_r(ec, vp, 0);
2494 /* for dafs, we should tell the fileserver, except for V_PEEK
2495 * where we know it is not necessary */
2496 if (mode == V_PEEK) {
2497 vp->needsPutBack = 0;
2499 vp->needsPutBack = VOL_PUTBACK;
2501 #else /* !AFS_DEMAND_ATTACH_FS */
2502 /* duplicate computation in fssync.c about whether the server
2503 * takes the volume offline or not. If the volume isn't
2504 * offline, we must not return it when we detach the volume,
2505 * or the server will abort */
2506 if (mode == V_READONLY || mode == V_PEEK
2507 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2508 vp->needsPutBack = 0;
2510 vp->needsPutBack = VOL_PUTBACK;
2511 #endif /* !AFS_DEMAND_ATTACH_FS */
2513 #ifdef FSSYNC_BUILD_CLIENT
2514 /* Only give back the vol to the fileserver if we checked it out; attach2
2515 * will set checkedOut only if we successfully checked it out from the
2517 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2519 #ifdef AFS_DEMAND_ATTACH_FS
2520 /* If we couldn't attach but we scheduled a salvage, we already
2521 * notified the fileserver; don't online it now */
2522 if (*ec != VSALVAGING)
2523 #endif /* AFS_DEMAND_ATTACH_FS */
2524 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2527 if (programType == fileServer && vp) {
2528 #ifdef AFS_DEMAND_ATTACH_FS
2530 * we can get here in cases where we don't "own"
2531 * the volume (e.g. volume owned by a utility).
2532 * short circuit around potential disk header races.
2534 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2538 VUpdateVolume_r(ec, vp, 0);
2540 Log("VAttachVolume: Error updating volume\n");
2545 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2546 #ifndef AFS_DEMAND_ATTACH_FS
2547 /* This is a hack: by temporarily setting the incore
2548 * dontSalvage flag ON, the volume will be put back on the
2549 * Update list (with dontSalvage OFF again). It will then
2550 * come back in N minutes with DONT_SALVAGE eventually
2551 * set. This is the way that volumes that have never had
2552 * it set get it set; or that volumes that have been
2553 * offline without DONT SALVAGE having been set also
2554 * eventually get it set */
2555 V_dontSalvage(vp) = DONT_SALVAGE;
2556 #endif /* !AFS_DEMAND_ATTACH_FS */
2557 VAddToVolumeUpdateList_r(ec, vp);
2559 Log("VAttachVolume: Error adding volume to update list\n");
2565 if (GetLogLevel() != 0)
2566 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n", afs_printable_VolumeId_lu(V_id(vp)),
2571 if (VRequiresPartLock()) {
2572 VUnlockPartition_r(partition);
2575 #ifdef AFS_DEMAND_ATTACH_FS
2576 /* attach failed; make sure we're in error state */
2577 if (vp && !VIsErrorState(V_attachState(vp))) {
2578 VChangeState_r(vp, VOL_STATE_ERROR);
2580 #endif /* AFS_DEMAND_ATTACH_FS */
2587 #ifdef AFS_DEMAND_ATTACH_FS
2588 /* VAttachVolumeByVp_r
2590 * finish attaching a volume that is
2591 * in a less than fully attached state
2593 /* caller MUST hold a ref count on vp */
2595 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2597 char name[VMAXPATHLEN];
2599 struct DiskPartition64 *partp;
2603 Volume * nvp = NULL;
2604 VolumeStats stats_save;
2608 /* volume utility should never call AttachByVp */
2609 opr_Assert(programType == fileServer);
2611 volumeId = vp->hashid;
2612 partp = vp->partition;
2613 VolumeExternalName_r(volumeId, name, sizeof(name));
2616 /* if another thread is performing a blocking op, wait */
2617 VWaitExclusiveState_r(vp);
2619 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2621 /* if it's already attached, see if we can return it */
2622 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2623 VGetVolumeByVp_r(ec, vp);
2624 if (V_inUse(vp) == fileServer) {
2627 if (vp->specialStatus == VBUSY)
2629 VDetachVolume_r(ec, vp);
2631 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2637 /* pre-attach volume if it hasn't been done yet */
2639 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2640 (V_attachState(vp) == VOL_STATE_DELETED) ||
2641 (V_attachState(vp) == VOL_STATE_ERROR)) {
2642 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2648 VCreateReservation_r(nvp);
2653 opr_Assert(vp != NULL);
2654 VChangeState_r(vp, VOL_STATE_ATTACHING);
2656 /* restore monotonically increasing stats */
2657 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2661 /* compute path to disk header */
2662 strcpy(path, VPartitionPath(partp));
2666 strcat(path, OS_DIRSEP);
2671 * NOTE: attach2 is entered without any locks, and returns
2672 * with vol_glock_mutex held */
2673 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2676 * the event that an error was encountered, or
2677 * the volume was not brought to an attached state
2678 * for any reason, skip to the end. We cannot
2679 * safely call VUpdateVolume unless we "own" it.
2683 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2687 VUpdateVolume_r(ec, vp, 0);
2689 Log("VAttachVolume: Error updating volume %" AFS_VOLID_FMT "\n",
2690 afs_printable_VolumeId_lu(vp->hashid));
2694 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2695 #ifndef AFS_DEMAND_ATTACH_FS
2696 /* This is a hack: by temporarily setting the incore
2697 * dontSalvage flag ON, the volume will be put back on the
2698 * Update list (with dontSalvage OFF again). It will then
2699 * come back in N minutes with DONT_SALVAGE eventually
2700 * set. This is the way that volumes that have never had
2701 * it set get it set; or that volumes that have been
2702 * offline without DONT SALVAGE having been set also
2703 * eventually get it set */
2704 V_dontSalvage(vp) = DONT_SALVAGE;
2705 #endif /* !AFS_DEMAND_ATTACH_FS */
2706 VAddToVolumeUpdateList_r(ec, vp);
2708 Log("VAttachVolume: Error adding volume %" AFS_VOLID_FMT " to update list\n",
2709 afs_printable_VolumeId_lu(vp->hashid));
2715 if (GetLogLevel() != 0)
2716 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n",
2717 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
2720 VCancelReservation_r(nvp);
2723 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2724 if (vp && !VIsErrorState(V_attachState(vp))) {
2725 VChangeState_r(vp, VOL_STATE_ERROR);
2734 * lock a volume on disk (non-blocking).
2736 * @param[in] vp The volume to lock
2737 * @param[in] locktype READ_LOCK or WRITE_LOCK
2739 * @return operation status
2740 * @retval 0 success, lock was obtained
2741 * @retval EBUSY a conflicting lock was held by another process
2742 * @retval EIO error acquiring lock
2744 * @pre If we're in the fileserver, vp is in an exclusive state
2746 * @pre vp is not already locked
2749 VLockVolumeNB(Volume *vp, int locktype)
2753 opr_Assert(programType != fileServer
2754 || VIsExclusiveState(V_attachState(vp)));
2755 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2757 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2759 V_attachFlags(vp) |= VOL_LOCKED;
2766 * unlock a volume on disk that was locked with VLockVolumeNB.
2768 * @param[in] vp volume to unlock
2770 * @pre If we're in the fileserver, vp is in an exclusive state
2772 * @pre vp has already been locked
2775 VUnlockVolume(Volume *vp)
2777 opr_Assert(programType != fileServer
2778 || VIsExclusiveState(V_attachState(vp)));
2779 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2781 VUnlockVolumeById(vp->hashid, vp->partition);
2783 V_attachFlags(vp) &= ~VOL_LOCKED;
2785 #endif /* AFS_DEMAND_ATTACH_FS */
2788 * read in a vol header, possibly lock the vol header, and possibly check out
2789 * the vol header from the fileserver, as part of volume attachment.
2791 * @param[out] ec error code
2792 * @param[in] vp volume pointer object
2793 * @param[in] partp disk partition object of the attaching partition
2794 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2796 * @param[in] peek 1 to just try to read in the volume header and make sure
2797 * we don't try to lock the vol, or check it out from
2798 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2800 * @param[out] acheckedOut If we successfully checked-out the volume from
2801 * the fileserver (if we needed to), this is set
2802 * to 1, otherwise it is untouched.
2804 * @note As part of DAFS volume attachment, the volume header may be either
2805 * read- or write-locked to ensure mutual exclusion of certain volume
2806 * operations. In some cases in order to determine whether we need to
2807 * read- or write-lock the header, we need to read in the header to see
2808 * if the volume is RW or not. So, if we read in the header under a
2809 * read-lock and determine that we actually need a write-lock on the
2810 * volume header, this function will drop the read lock, acquire a write
2811 * lock, and read the header in again.
2814 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2815 int mode, int peek, int *acheckedOut)
2817 struct VolumeDiskHeader diskHeader;
2818 struct VolumeHeader header;
2821 int lock_tries = 0, checkout_tries = 0;
2823 VolumeId volid = vp->hashid;
2824 #ifdef FSSYNC_BUILD_CLIENT
2825 int checkout, done_checkout = 0;
2826 #endif /* FSSYNC_BUILD_CLIENT */
2827 #ifdef AFS_DEMAND_ATTACH_FS
2828 int locktype = 0, use_locktype = -1;
2829 #endif /* AFS_DEMAND_ATTACH_FS */
2835 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2836 Log("VAttachVolume: retried too many times trying to lock header for "
2837 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2838 VPartitionPath(partp));
2842 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2843 Log("VAttachVolume: retried too many times trying to checkout "
2844 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2845 VPartitionPath(partp));
2850 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2851 /* short-circuit the 'volume does not exist' case */
2856 #ifdef FSSYNC_BUILD_CLIENT
2857 checkout = !done_checkout;
2859 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2861 memset(&res, 0, sizeof(res));
2863 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2866 if (res.hdr.reason == FSYNC_SALVAGE) {
2867 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2868 afs_printable_uint32_lu(volid));
2871 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2872 afs_printable_uint32_lu(volid));
2873 *ec = VNOVOL; /* XXXX */
2881 #ifdef AFS_DEMAND_ATTACH_FS
2882 if (use_locktype < 0) {
2883 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2884 * if it turns out to be RW */
2885 locktype = VVolLockType(mode, 0);
2888 /* a previous try says we should use use_locktype to lock the volume,
2890 locktype = use_locktype;
2893 if (!peek && locktype) {
2894 code = VLockVolumeNB(vp, locktype);
2896 if (code == EBUSY) {
2897 Log("VAttachVolume: another program has vol %lu locked\n",
2898 afs_printable_uint32_lu(volid));
2900 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2901 code, afs_printable_uint32_lu(volid));
2908 #endif /* AFS_DEMAND_ATTACH_FS */
2910 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2920 DiskToVolumeHeader(&header, &diskHeader);
2922 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2923 header.largeVnodeIndex);
2924 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2925 header.smallVnodeIndex);
2926 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2928 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2931 /* only need to do this once */
2933 GetVolumeHeader(vp);
2937 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2938 /* demand attach changes the V_PEEK mechanism
2940 * we can now suck the current disk data structure over
2941 * the fssync interface without going to disk
2943 * (technically, we don't need to restrict this feature
2944 * to demand attach fileservers. However, I'm trying
2945 * to limit the number of common code changes)
2947 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2949 res.payload.len = sizeof(VolumeDiskData);
2950 res.payload.buf = &(V_disk(vp));
2952 if (FSYNC_VolOp(vp->hashid,
2954 FSYNC_VOL_QUERY_HDR,
2957 goto disk_header_loaded;
2960 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2961 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2962 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2964 #ifdef AFS_DEMAND_ATTACH_FS
2967 IncUInt64(&VStats.hdr_loads);
2968 IncUInt64(&vp->stats.hdr_loads);
2970 #endif /* AFS_DEMAND_ATTACH_FS */
2973 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2974 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2978 #ifdef AFS_DEMAND_ATTACH_FS
2979 # ifdef FSSYNC_BUILD_CLIENT
2981 # endif /* FSSYNC_BUILD_CLIENT */
2983 /* if the lock type we actually used to lock the volume is different than
2984 * the lock type we should have used, retry with the lock type we should
2986 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2987 if (locktype != use_locktype) {
2991 #endif /* AFS_DEMAND_ATTACH_FS */
2996 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2997 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2999 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
3001 if (code == SYNC_DENIED) {
3002 /* must retry checkout; fileserver no longer thinks we have
3008 } else if (code != SYNC_OK) {
3012 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3015 /* either we are going to be called again for a second pass, or we
3016 * encountered an error; clean up in either case */
3018 #ifdef AFS_DEMAND_ATTACH_FS
3019 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3022 #endif /* AFS_DEMAND_ATTACH_FS */
3023 if (vp->linkHandle) {
3024 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3025 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3026 IH_RELEASE(vp->diskDataHandle);
3027 IH_RELEASE(vp->linkHandle);
3033 FreeVolumeHeader(vp);
3043 #ifdef AFS_DEMAND_ATTACH_FS
3045 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3046 Volume *vp, int *acheckedOut)
3050 if (vp->pending_vol_op) {
3054 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3056 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3058 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3059 } else if (code == 0) {
3060 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3063 /* we need the vol header to determine if the volume can be
3064 * left online for the vop, so... get the header */
3068 /* attach header with peek=1 to avoid checking out the volume
3069 * or locking it; we just want the header info, we're not
3070 * messing with the volume itself at all */
3071 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3078 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3079 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3081 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3084 /* make sure we grab a new vol header and re-open stuff on
3085 * actual attachment; we can't keep the data we grabbed, since
3086 * it was not done under a lock and thus not safe */
3087 FreeVolumeHeader(vp);
3088 VReleaseVolumeHandles_r(vp);
3091 /* see if the pending volume op requires exclusive access */
3092 switch (vp->pending_vol_op->vol_op_state) {
3093 case FSSYNC_VolOpPending:
3094 /* this should never happen */
3095 opr_Assert(vp->pending_vol_op->vol_op_state
3096 != FSSYNC_VolOpPending);
3099 case FSSYNC_VolOpRunningUnknown:
3100 /* this should never happen; we resolved 'unknown' above */
3101 opr_Assert(vp->pending_vol_op->vol_op_state
3102 != FSSYNC_VolOpRunningUnknown);
3105 case FSSYNC_VolOpRunningOffline:
3106 /* mark the volume down */
3108 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3110 /* do not set V_offlineMessage here; we don't have ownership of
3111 * the volume (and probably do not have the header loaded), so we
3112 * can't alter the disk header */
3114 /* check to see if we should set the specialStatus flag */
3115 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3116 /* don't overwrite specialStatus if it was already set to
3117 * something else (e.g. VMOVED) */
3118 if (!vp->specialStatus) {
3119 vp->specialStatus = VBUSY;
3131 #endif /* AFS_DEMAND_ATTACH_FS */
3134 * volume attachment helper function.
3136 * @param[out] ec error code
3137 * @param[in] volumeId volume ID of the attaching volume
3138 * @param[in] path full path to the volume header .vol file
3139 * @param[in] partp disk partition object for the attaching partition
3140 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3141 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3142 * DAFS) should already be initialized
3143 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3144 * if there is a volume operation running for this volume
3145 * that should set the volume to VBUSY during its run. 0
3146 * otherwise. (see VVolOpSetVBusy_r)
3147 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3149 * @param[out] acheckedOut If we successfully checked-out the volume from
3150 * the fileserver (if we needed to), this is set
3151 * to 1, otherwise it is 0.
3153 * @return pointer to the semi-attached volume pointer
3154 * @retval NULL an error occurred (check value of *ec)
3155 * @retval vp volume successfully attaching
3157 * @pre no locks held
3159 * @post VOL_LOCK held
3162 attach2(Error * ec, VolumeId volumeId, char *path, struct DiskPartition64 *partp,
3163 Volume * vp, int isbusy, int mode, int *acheckedOut)
3165 /* have we read in the header successfully? */
3166 int read_header = 0;
3168 #ifdef AFS_DEMAND_ATTACH_FS
3169 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3173 /* in the case of an error, to what state should the volume be
3175 VolState error_state = VOL_STATE_ERROR;
3176 #endif /* AFS_DEMAND_ATTACH_FS */
3180 vp->vnodeIndex[vLarge].handle = NULL;
3181 vp->vnodeIndex[vSmall].handle = NULL;
3182 vp->diskDataHandle = NULL;
3183 vp->linkHandle = NULL;
3187 #ifdef AFS_DEMAND_ATTACH_FS
3188 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3190 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3193 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3194 #endif /* !AFS_DEMAND_ATTACH_FS */
3196 if (*ec == VNOVOL) {
3197 /* if the volume doesn't exist, skip straight to 'error' so we don't
3198 * request a salvage */
3199 goto unlocked_error;
3205 /* ensure that we don't override specialStatus if it was set to
3206 * something else (e.g. VMOVED) */
3207 if (isbusy && !vp->specialStatus) {
3208 vp->specialStatus = VBUSY;
3210 vp->shuttingDown = 0;
3211 vp->goingOffline = 0;
3213 #ifdef AFS_DEMAND_ATTACH_FS
3214 vp->stats.last_attach = FT_ApproxTime();
3215 vp->stats.attaches++;
3219 IncUInt64(&VStats.attaches);
3220 vp->cacheCheck = ++VolumeCacheCheck;
3221 /* just in case this ever rolls over */
3222 if (!vp->cacheCheck)
3223 vp->cacheCheck = ++VolumeCacheCheck;
3226 #ifdef AFS_DEMAND_ATTACH_FS
3227 V_attachFlags(vp) |= VOL_HDR_LOADED;
3228 vp->stats.last_hdr_load = vp->stats.last_attach;
3229 #endif /* AFS_DEMAND_ATTACH_FS */
3233 struct IndexFileHeader iHead;
3236 * We just read in the diskstuff part of the header. If the detailed
3237 * volume stats area has not yet been initialized, we should bzero the
3238 * area and mark it as initialized.
3240 if (!(V_stat_initialized(vp))) {
3241 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3242 V_stat_initialized(vp) = 1;
3245 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3246 (char *)&iHead, sizeof(iHead),
3247 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3250 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3255 struct IndexFileHeader iHead;
3257 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3258 (char *)&iHead, sizeof(iHead),
3259 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3262 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3266 #ifdef AFS_NAMEI_ENV
3268 struct versionStamp stamp;
3270 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3271 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3274 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3277 #endif /* AFS_NAMEI_ENV */
3279 #if defined(AFS_DEMAND_ATTACH_FS)
3280 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3282 if (!VCanScheduleSalvage()) {
3283 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3285 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3290 /* volume operation in progress */
3292 /* we have already transitioned the vp away from ATTACHING state, so we
3293 * can go right to the end of attach2, and we do not need to transition
3295 goto error_notbroken;
3297 #else /* AFS_DEMAND_ATTACH_FS */
3299 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3300 goto unlocked_error;
3302 #endif /* AFS_DEMAND_ATTACH_FS */
3304 if (V_needsSalvaged(vp)) {
3305 if (vp->specialStatus)
3306 vp->specialStatus = 0;
3308 #if defined(AFS_DEMAND_ATTACH_FS)
3309 if (!VCanScheduleSalvage()) {
3310 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3312 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3315 #else /* AFS_DEMAND_ATTACH_FS */
3317 #endif /* AFS_DEMAND_ATTACH_FS */
3323 vp->nextVnodeUnique = V_uniquifier(vp);
3325 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3326 if (!V_needsSalvaged(vp)) {
3327 V_needsSalvaged(vp) = 1;
3328 VUpdateVolume_r(ec, vp, 0);
3330 #if defined(AFS_DEMAND_ATTACH_FS)
3331 if (!VCanScheduleSalvage()) {
3332 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3334 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3337 #else /* AFS_DEMAND_ATTACH_FS */
3338 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3340 #endif /* AFS_DEMAND_ATTACH_FS */
3345 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3346 /* Only check destroyMe if we are the fileserver, since the
3347 * volserver et al sometimes need to work with volumes with
3348 * destroyMe set. Examples are 'temporary' volumes the
3349 * volserver creates, and when we create a volume (destroyMe
3350 * is set on creation; sometimes a separate volserver
3351 * transaction is created to clear destroyMe).
3354 #if defined(AFS_DEMAND_ATTACH_FS)
3355 /* schedule a salvage so the volume goes away on disk */
3356 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3357 VChangeState_r(vp, VOL_STATE_ERROR);
3360 #endif /* AFS_DEMAND_ATTACH_FS */
3361 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3366 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3367 #ifndef BITMAP_LATER
3368 if (programType == fileServer && VolumeWriteable(vp)) {
3370 for (i = 0; i < nVNODECLASSES; i++) {
3371 VGetBitmap_r(ec, vp, i);
3373 #ifdef AFS_DEMAND_ATTACH_FS
3374 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3376 #endif /* AFS_DEMAND_ATTACH_FS */
3377 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3383 #endif /* BITMAP_LATER */
3385 if (VInit >= 2 && V_needsCallback(vp)) {
3386 if (V_BreakVolumeCallbacks) {
3387 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3388 afs_printable_uint32_lu(V_id(vp)));
3389 V_needsCallback(vp) = 0;
3391 (*V_BreakVolumeCallbacks) (V_id(vp));
3394 VUpdateVolume_r(ec, vp, 0);
3396 #ifdef FSSYNC_BUILD_CLIENT
3397 else if (VCanUseFSSYNC()) {
3398 afs_int32 fsync_code;
3400 V_needsCallback(vp) = 0;
3402 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3406 V_needsCallback(vp) = 1;
3407 Log("Error trying to tell the fileserver to break callbacks for "
3408 "changed volume %lu; error code %ld\n",
3409 afs_printable_uint32_lu(V_id(vp)),
3410 afs_printable_int32_ld(fsync_code));
3412 VUpdateVolume_r(ec, vp, 0);
3415 #endif /* FSSYNC_BUILD_CLIENT */
3418 Log("VAttachVolume: error %d clearing needsCallback on volume "
3419 "%lu; needs salvage\n", (int)*ec,
3420 afs_printable_uint32_lu(V_id(vp)));
3421 #ifdef AFS_DEMAND_ATTACH_FS
3422 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3424 #else /* !AFS_DEMAND_ATTACH_FS */
3426 #endif /* !AFS_DEMAND_ATTACh_FS */
3431 if (programType == fileServer) {
3432 if (vp->specialStatus)
3433 vp->specialStatus = 0;
3434 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3435 V_inUse(vp) = fileServer;
3436 V_offlineMessage(vp)[0] = '\0';
3438 #ifdef AFS_DEMAND_ATTACH_FS
3439 /* check if the volume is actually usable. only do this for DAFS; for
3440 * non-DAFS, volumes that are not inService/blessed can still be
3441 * attached, even if clients cannot access them. this is relevant
3442 * because for non-DAFS, we try to attach the volume when e.g.
3443 * volserver gives us back then vol when its done with it, but
3444 * volserver may give us back a volume that is not inService/blessed. */
3448 /* Put the vol into PREATTACHED state, so if someone tries to
3449 * access it again, we try to attach, see that we're not blessed,
3450 * and give a VNOVOL error again. Putting it into UNATTACHED state
3451 * would result in a VOFFLINE error instead. */
3452 error_state = VOL_STATE_PREATTACHED;
3454 /* mimic e.g. GetVolume errors */
3455 if (!V_blessed(vp)) {
3456 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3457 FreeVolumeHeader(vp);
3458 } else if (!V_inService(vp)) {
3459 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3460 /* the volume is offline and should be unattached */
3462 error_state = VOL_STATE_UNATTACHED;
3463 FreeVolumeHeader(vp);
3465 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3467 error_state = VOL_STATE_ERROR;
3468 /* see if we can recover */
3469 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3474 #endif /* AFS_DEMAND_ATTACH_FS */
3476 #ifdef AFS_DEMAND_ATTACH_FS
3477 if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3478 V_inUse(vp) = programType;
3479 #endif /* AFS_DEMAND_ATTACH_FS */
3480 V_checkoutMode(vp) = mode;
3483 AddVolumeToHashTable(vp, vp->hashid);
3484 #ifdef AFS_DEMAND_ATTACH_FS
3485 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3488 if ((programType != fileServer) ||
3489 (V_inUse(vp) == fileServer)) {
3490 AddVolumeToVByPList_r(vp);
3492 VChangeState_r(vp, VOL_STATE_ATTACHED);
3494 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3503 #ifdef AFS_DEMAND_ATTACH_FS
3504 if (!VIsErrorState(V_attachState(vp))) {
3505 if (programType != fileServer && *ec == VNOVOL) {
3506 /* do not log anything in this case; it is common for
3507 * non-fileserver programs to fail here with VNOVOL, since that
3508 * is what happens when they simply try to use a volume, but that
3509 * volume doesn't exist. */
3511 } else if (VIsErrorState(error_state)) {
3512 Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3513 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3514 V_attachFlags(vp), *ec);
3516 VChangeState_r(vp, error_state);
3518 #endif /* AFS_DEMAND_ATTACH_FS */
3521 VReleaseVolumeHandles_r(vp);
3524 #ifdef AFS_DEMAND_ATTACH_FS
3526 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3527 /* The salvage could not be scheduled with the salvage server
3528 * due to a hard error. Reset the error code to prevent retry loops by
3530 if (*ec == VSALVAGING) {
3539 #else /* !AFS_DEMAND_ATTACH_FS */
3541 #endif /* !AFS_DEMAND_ATTACH_FS */
3545 /* Attach an existing volume.
3546 The volume also normally goes online at this time.
3547 An offline volume must be reattached to make it go online.
3551 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3555 retVal = VAttachVolume_r(ec, volumeId, mode);
3561 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3564 VGetVolumePath(ec, volumeId, &part, &name);
3568 vp = VGetVolume_r(&error, volumeId);
3570 opr_Assert(V_inUse(vp) == 0);
3571 VDetachVolume_r(ec, vp);
3575 return VAttachVolumeByName_r(ec, part, name, mode);
3578 /* Increment a reference count to a volume, sans context swaps. Requires
3579 * possibly reading the volume header in from the disk, since there's
3580 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3582 * N.B. This call can fail if we can't read in the header!! In this case
3583 * we still guarantee we won't context swap, but the ref count won't be
3584 * incremented (otherwise we'd violate the invariant).
3586 /* NOTE: with the demand attach fileserver extensions, the global lock
3587 * is dropped within VHold */
3588 #ifdef AFS_DEMAND_ATTACH_FS
3590 VHold_r(Volume * vp)
3594 VCreateReservation_r(vp);
3595 VWaitExclusiveState_r(vp);
3597 LoadVolumeHeader(&error, vp);
3599 VCancelReservation_r(vp);
3603 VCancelReservation_r(vp);
3606 #else /* AFS_DEMAND_ATTACH_FS */
3608 VHold_r(Volume * vp)
3612 LoadVolumeHeader(&error, vp);
3618 #endif /* AFS_DEMAND_ATTACH_FS */
3620 /**** volume timeout-related stuff ****/
3622 #ifdef AFS_PTHREAD_ENV
3624 static struct timespec *shutdown_timeout;
3625 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3628 VTimedOut(const struct timespec *ts)
3633 if (ts->tv_sec == 0) {
3634 /* short-circuit; this will have always timed out */
3638 code = gettimeofday(&tv, NULL);
3640 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3641 /* assume no timeout; failure mode is we just wait longer than normal
3642 * instead of returning errors when we shouldn't */
3646 if (tv.tv_sec < ts->tv_sec ||
3647 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3656 * Calculate an absolute timeout.
3658 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3659 * NULL, the memory is not touched
3660 * @param[in] timeout How long the timeout should be from now
3662 * @return timeout to use
3663 * @retval NULL no timeout; wait forever
3664 * @retval non-NULL the given value for "ts"
3668 static struct timespec *
3669 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3679 ts->tv_sec = ts->tv_nsec = 0;
3683 code = gettimeofday(&now, NULL);
3685 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3689 ts->tv_sec = now.tv_sec + timeout;
3690 ts->tv_nsec = now.tv_usec * 1000;
3696 * Initialize the shutdown_timeout global.
3699 VShutdownTimeoutInit(void)
3701 struct timespec *ts;
3703 ts = malloc(sizeof(*ts));
3705 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3707 if (!shutdown_timeout) {
3713 * Figure out the timeout that should be used for waiting for offline volumes.
3715 * @param[out] ats Storage space for a local timeout value if needed
3717 * @return The timeout value that should be used
3718 * @retval NULL No timeout; wait forever for offlining volumes
3719 * @retval non-NULL A pointer to the absolute time that should be used as
3720 * the deadline for waiting for offlining volumes.
3722 * @note If we return non-NULL, the pointer we return may or may not be the
3725 static const struct timespec *
3726 VOfflineTimeout(struct timespec *ats)
3728 if (vol_shutting_down) {
3729 opr_Verify(pthread_once(&shutdown_timeout_once,
3730 VShutdownTimeoutInit) == 0);
3731 return shutdown_timeout;
3733 return VCalcTimeout(ats, vol_opts.offline_timeout);
3737 #else /* AFS_PTHREAD_ENV */
3739 /* Waiting a certain amount of time for offlining volumes is not supported
3740 * for LWP due to a lack of primitives. So, we never time out */
3741 # define VTimedOut(x) (0)
3742 # define VOfflineTimeout(x) (NULL)
3744 #endif /* !AFS_PTHREAD_ENV */
3747 VIsGoingOffline_r(struct Volume *vp)
3751 if (vp->goingOffline) {
3752 if (vp->specialStatus) {
3753 code = vp->specialStatus;
3754 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3765 * Tell the caller if a volume is waiting to go offline.
3767 * @param[in] vp The volume we want to know about
3769 * @return volume status
3770 * @retval 0 volume is not waiting to go offline, go ahead and use it
3771 * @retval nonzero volume is waiting to offline, and give the returned code
3772 * as an error to anyone accessing the volume
3774 * @pre VOL_LOCK is NOT held
3775 * @pre caller holds a heavyweight reference on vp
3778 VIsGoingOffline(struct Volume *vp)
3783 code = VIsGoingOffline_r(vp);
3790 * Register an RX call with a volume.
3792 * @param[inout] ec Error code; if unset when passed in, may be set if
3793 * the volume starts going offline
3794 * @param[out] client_ec @see GetVolume
3795 * @param[in] vp Volume struct
3796 * @param[in] cbv VCallByVol struct containing the RX call to register
3798 * @pre VOL_LOCK held
3799 * @pre caller holds heavy ref on vp
3804 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3807 #ifdef AFS_DEMAND_ATTACH_FS
3809 /* just in case the volume started going offline after we got the
3810 * reference to it... otherwise, if the volume started going
3811 * offline right at the end of GetVolume(), we might race with the
3812 * RX call scanner, and return success and add our cbv to the
3813 * rx_call_list _after_ the scanner has scanned the list. */
3814 *ec = VIsGoingOffline_r(vp);
3820 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3821 VWaitStateChange_r(vp);
3823 #endif /* AFS_DEMAND_ATTACH_FS */
3825 queue_Prepend(&vp->rx_call_list, cbv);
3830 * Deregister an RX call with a volume.
3832 * @param[in] vp Volume struct
3833 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3835 * @pre VOL_LOCK held
3836 * @pre caller holds heavy ref on vp
3841 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3843 if (cbv && queue_IsOnQueue(cbv)) {
3844 #ifdef AFS_DEMAND_ATTACH_FS
3845 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3846 VWaitStateChange_r(vp);
3848 #endif /* AFS_DEMAND_ATTACH_FS */
3854 /***************************************************/
3855 /* get and put volume routines */
3856 /***************************************************/
3859 * put back a heavyweight reference to a volume object.
3861 * @param[in] vp volume object pointer
3863 * @pre VOL_LOCK held
3865 * @post heavyweight volume reference put back.
3866 * depending on state, volume may have been taken offline,
3867 * detached, salvaged, freed, etc.
3869 * @internal volume package internal use only
3872 VPutVolume_r(Volume * vp)
3874 opr_Verify(--vp->nUsers >= 0);
3875 if (vp->nUsers == 0) {
3877 ReleaseVolumeHeader(vp->header);
3878 #ifdef AFS_DEMAND_ATTACH_FS
3879 if (!VCheckDetach(vp)) {
3883 #else /* AFS_DEMAND_ATTACH_FS */
3885 #endif /* AFS_DEMAND_ATTACH_FS */
3890 VPutVolume(Volume * vp)
3898 * Puts a volume reference obtained with VGetVolumeWithCall.
3900 * @param[in] vp Volume struct
3901 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3903 * @pre VOL_LOCK is NOT held
3906 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3909 VDeregisterCall_r(vp, cbv);
3914 /* Get a pointer to an attached volume. The pointer is returned regardless
3915 of whether or not the volume is in service or on/off line. An error
3916 code, however, is returned with an indication of the volume's status */
3918 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3922 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3928 * Get a volume reference associated with an RX call.
3930 * @param[out] ec @see GetVolume
3931 * @param[out] client_ec @see GetVolume
3932 * @param[in] volumeId @see GetVolume
3933 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3934 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3935 * with an error if the volume is going offline.
3936 * @param[in] cbv Contains an RX call to be associated with this volume
3937 * reference. This call may be interrupted if the volume is
3938 * requested to go offline while we hold a ref on it. Give NULL
3939 * to not associate an RX call with this reference.
3941 * @return @see GetVolume
3943 * @note for LWP builds, ts must be NULL
3945 * @note A reference obtained with this function MUST be put back with
3946 * VPutVolumeWithCall
3949 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3950 const struct timespec *ts, struct VCallByVol *cbv)
3954 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3955 VRegisterCall_r(ec, client_ec, retVal, cbv);
3961 VGetVolume_r(Error * ec, VolumeId volumeId)
3963 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3966 /* try to get a volume we've previously looked up */
3967 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3969 VGetVolumeByVp_r(Error * ec, Volume * vp)
3971 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3975 * private interface for getting a volume handle
3977 * @param[out] ec error code (0 if no error)
3978 * @param[out] client_ec wire error code to be given to clients
3979 * @param[in] volumeId ID of the volume we want
3980 * @param[in] hint optional hint for hash lookups, or NULL
3981 * @param[in] timeout absolute deadline for waiting for the volume to go
3982 * offline, if it is going offline. NULL to wait forever.
3984 * @return a volume handle for the specified volume
3985 * @retval NULL an error occurred, or the volume is in such a state that
3986 * we cannot load a header or return any volume struct
3988 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3990 * @note 'timeout' is only checked if the volume is actually going offline; so
3991 * if you pass timeout->tv_sec = 0, this will exhibit typical
3992 * nonblocking behavior.
3994 * @note for LWP builds, 'timeout' must be NULL
3997 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
3998 const struct timespec *timeout)
4001 #ifdef AFS_DEMAND_ATTACH_FS
4002 Volume *avp, * rvp = hint;
4006 * if VInit is zero, the volume package dynamic
4007 * data structures have not been initialized yet,
4008 * and we must immediately return an error
4014 *client_ec = VOFFLINE;
4019 #ifdef AFS_DEMAND_ATTACH_FS
4021 VCreateReservation_r(rvp);
4023 #endif /* AFS_DEMAND_ATTACH_FS */
4030 vp = VLookupVolume_r(ec, volumeId, vp);
4036 #ifdef AFS_DEMAND_ATTACH_FS
4037 if (rvp && (rvp != vp)) {
4038 /* break reservation on old vp */
4039 VCancelReservation_r(rvp);
4042 #endif /* AFS_DEMAND_ATTACH_FS */
4046 /* Until we have reached an initialization level of 2
4047 * we don't know whether this volume exists or not.
4048 * We can't sleep and retry later because before a volume
4049 * is attached, the caller tries to get it first. Just
4050 * return VOFFLINE and the caller can choose whether to
4051 * retry the command or not. */
4060 IncUInt64(&VStats.hdr_gets);
4062 #ifdef AFS_DEMAND_ATTACH_FS
4063 /* block if someone else is performing an exclusive op on this volume */
4066 VCreateReservation_r(rvp);
4068 VWaitExclusiveState_r(vp);
4070 /* short circuit with VNOVOL in the following circumstances:
4073 * - VOL_STATE_SHUTTING_DOWN
4075 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4076 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4083 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4084 * VNOVOL for VOL_STATE_DELETED
4086 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4087 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4088 (V_attachState(vp) == VOL_STATE_DELETED)) {
4089 if (vp->specialStatus) {
4090 *ec = vp->specialStatus;
4091 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4100 /* allowable states:
4107 if (vp->salvage.requested) {
4108 VUpdateSalvagePriority_r(vp);
4111 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4112 if (vp->specialStatus) {
4113 *ec = vp->specialStatus;
4117 avp = VAttachVolumeByVp_r(ec, vp, 0);
4120 /* VAttachVolumeByVp_r can return a pointer
4121 * != the vp passed to it under certain
4122 * conditions; make sure we don't leak
4123 * reservations if that happens */
4125 VCancelReservation_r(rvp);
4127 VCreateReservation_r(rvp);
4138 if (vp->specialStatus) {
4139 *ec = vp->specialStatus;
4144 if (vp->specialStatus) {
4145 *ec = vp->specialStatus;
4158 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4160 /* see CheckVnode() in afsfileprocs.c for an explanation
4161 * of this error code logic */
4162 afs_uint32 now = FT_ApproxTime();
4163 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4166 *client_ec = VRESTARTING;
4174 if (VIsErrorState(V_attachState(vp))) {
4175 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4176 * it, or transition it out of that state */
4185 * this test MUST happen after VAttachVolymeByVp, so we have no
4186 * conflicting vol op. (attach2 would have errored out if we had one;
4187 * specifically attach_check_vop must have detected a conflicting vop)
4189 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4191 #endif /* AFS_DEMAND_ATTACH_FS */
4193 LoadVolumeHeader(ec, vp);
4195 /* Only log the error if it was a totally unexpected error. Simply
4196 * a missing inode is likely to be caused by the volume being deleted */
4197 if (errno != ENXIO || GetLogLevel() != 0)
4198 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4199 afs_printable_VolumeId_lu(vp->hashid));
4200 #ifdef AFS_DEMAND_ATTACH_FS
4201 if (VCanScheduleSalvage()) {
4202 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4207 #else /* AFS_DEMAND_ATTACH_FS */
4210 #endif /* AFS_DEMAND_ATTACH_FS */
4214 if (vp->shuttingDown) {
4220 if (programType == fileServer) {
4221 if (vp->goingOffline) {
4222 if (timeout && VTimedOut(timeout)) {
4223 /* we've timed out; don't wait for the vol */
4225 #ifdef AFS_DEMAND_ATTACH_FS
4226 /* wait for the volume to go offline */
4227 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4228 VTimedWaitStateChange_r(vp, timeout, NULL);
4230 #elif defined(AFS_PTHREAD_ENV)
4231 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4232 #else /* AFS_PTHREAD_ENV */
4233 /* LWP has no timed wait, so the caller better not be
4235 opr_Assert(!timeout);
4236 LWP_WaitProcess(VPutVolume);
4237 #endif /* AFS_PTHREAD_ENV */
4241 if (vp->specialStatus) {
4242 *ec = vp->specialStatus;
4243 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4245 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4252 #ifdef AFS_DEMAND_ATTACH_FS
4253 /* if no error, bump nUsers */
4256 VLRU_UpdateAccess_r(vp);
4259 VCancelReservation_r(rvp);
4262 if (client_ec && !*client_ec) {
4265 #else /* AFS_DEMAND_ATTACH_FS */
4266 /* if no error, bump nUsers */
4273 #endif /* AFS_DEMAND_ATTACH_FS */
4276 opr_Assert(vp || *ec);
4281 /***************************************************/
4282 /* Volume offline/detach routines */
4283 /***************************************************/
4285 /* caller MUST hold a heavyweight ref on vp */
4286 #ifdef AFS_DEMAND_ATTACH_FS
4288 VTakeOffline_r(Volume * vp)
4292 opr_Assert(vp->nUsers > 0);
4293 opr_Assert(programType == fileServer);
4295 VCreateReservation_r(vp);
4296 VWaitExclusiveState_r(vp);
4298 vp->goingOffline = 1;
4299 V_needsSalvaged(vp) = 1;
4301 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4302 VCancelReservation_r(vp);
4304 #else /* AFS_DEMAND_ATTACH_FS */
4306 VTakeOffline_r(Volume * vp)
4308 opr_Assert(vp->nUsers > 0);
4309 opr_Assert(programType == fileServer);
4311 vp->goingOffline = 1;
4312 V_needsSalvaged(vp) = 1;
4314 #endif /* AFS_DEMAND_ATTACH_FS */
4317 VTakeOffline(Volume * vp)
4325 * force a volume offline.
4327 * @param[in] vp volume object pointer
4328 * @param[in] flags flags (see note below)
4330 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4331 * used when VUpdateVolume_r needs to call VForceOffline_r
4332 * (which in turn would normally call VUpdateVolume_r)
4334 * @see VUpdateVolume_r
4336 * @pre VOL_LOCK must be held.
4337 * for DAFS, caller must hold ref.
4339 * @note for DAFS, it _is safe_ to call this function from an
4342 * @post needsSalvaged flag is set.
4343 * for DAFS, salvage is requested.
4344 * no further references to the volume through the volume
4345 * package will be honored.
4346 * all file descriptor and vnode caches are invalidated.
4348 * @warning this is a heavy-handed interface. it results in
4349 * a volume going offline regardless of the current
4350 * reference count state.
4352 * @internal volume package internal use only
4355 VForceOffline_r(Volume * vp, int flags)
4359 #ifdef AFS_DEMAND_ATTACH_FS
4360 VChangeState_r(vp, VOL_STATE_ERROR);
4365 strcpy(V_offlineMessage(vp),
4366 "Forced offline due to internal error: volume needs to be salvaged");
4367 Log("Volume %" AFS_VOLID_FMT " forced offline: it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4370 vp->goingOffline = 0;
4371 V_needsSalvaged(vp) = 1;
4372 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4373 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4376 #ifdef AFS_DEMAND_ATTACH_FS
4377 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4378 #endif /* AFS_DEMAND_ATTACH_FS */
4380 #ifdef AFS_PTHREAD_ENV
4381 opr_cv_broadcast(&vol_put_volume_cond);
4382 #else /* AFS_PTHREAD_ENV */
4383 LWP_NoYieldSignal(VPutVolume);
4384 #endif /* AFS_PTHREAD_ENV */
4386 VReleaseVolumeHandles_r(vp);
4390 * force a volume offline.
4392 * @param[in] vp volume object pointer
4394 * @see VForceOffline_r
4397 VForceOffline(Volume * vp)
4400 VForceOffline_r(vp, 0);
4405 * Iterate over the RX calls associated with a volume, and interrupt them.
4407 * @param[in] vp The volume whose RX calls we want to scan
4409 * @pre VOL_LOCK held
4412 VScanCalls_r(struct Volume *vp)
4414 struct VCallByVol *cbv, *ncbv;
4416 #ifdef AFS_DEMAND_ATTACH_FS
4417 VolState state_save;
4420 if (queue_IsEmpty(&vp->rx_call_list))
4421 return; /* no calls to interrupt */
4422 if (!vol_opts.interrupt_rxcall)
4423 return; /* we have no function with which to interrupt calls */
4424 err = VIsGoingOffline_r(vp);
4426 return; /* we're not going offline anymore */
4428 #ifdef AFS_DEMAND_ATTACH_FS
4429 VWaitExclusiveState_r(vp);
4430 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4432 #endif /* AFS_DEMAND_ATTACH_FS */
4434 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4435 if (GetLogLevel() != 0) {
4436 struct rx_peer *peer;
4438 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4440 Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4441 "from it; kicking client off with error %ld\n",
4442 afs_printable_VolumeId_lu(vp->hashid),
4443 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4444 (unsigned) ntohs(rx_PortOf(peer)),
4447 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4450 #ifdef AFS_DEMAND_ATTACH_FS
4452 VChangeState_r(vp, state_save);
4453 #endif /* AFS_DEMAND_ATTACH_FS */
4456 #ifdef AFS_DEMAND_ATTACH_FS
4458 * Wait for a vp to go offline.
4460 * @param[out] ec 1 if a salvage on the volume has been requested and
4461 * salvok == 0, 0 otherwise
4462 * @param[in] vp The volume to wait for
4463 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4464 * has been requested to salvage. Otherwise we keep waiting
4465 * until the volume has gone offline.
4467 * @pre VOL_LOCK held
4468 * @pre caller holds a lightweight ref on vp
4473 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4475 struct timespec timeout_ts;
4476 const struct timespec *ts;
4479 ts = VOfflineTimeout(&timeout_ts);
4483 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4484 if (!salvok && vp->salvage.requested) {
4488 VTimedWaitStateChange_r(vp, ts, &timedout);
4491 /* we didn't time out, so the volume must be offline, so we're done */
4495 /* If we got here, we timed out waiting for the volume to go offline.
4496 * Kick off the accessing RX calls and wait again */
4500 while (!VIsOfflineState(V_attachState(vp))) {
4501 if (!salvok && vp->salvage.requested) {
4506 VWaitStateChange_r(vp);
4510 #else /* AFS_DEMAND_ATTACH_FS */
4513 * Wait for a volume to go offline.
4515 * @pre VOL_LOCK held
4517 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)