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>
26 #include <afs/afsint.h>
30 #include <sys/param.h>
31 #if !defined(AFS_SGI_ENV)
34 #else /* AFS_OSF_ENV */
35 #ifdef AFS_VFSINCL_ENV
38 #include <sys/fs/ufs_fs.h>
40 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
41 #include <ufs/ufs/dinode.h>
42 #include <ufs/ffs/fs.h>
47 #else /* AFS_VFSINCL_ENV */
48 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
51 #endif /* AFS_VFSINCL_ENV */
52 #endif /* AFS_OSF_ENV */
53 #endif /* AFS_SGI_ENV */
54 #endif /* AFS_NT40_ENV */
72 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
74 #include <sys/mnttab.h>
75 #include <sys/mntent.h>
81 #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 <netinet/in.h>
100 #include <sys/time.h>
101 #endif /* ITIMER_REAL */
102 #endif /* AFS_NT40_ENV */
103 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
110 #include <afs/errors.h>
113 #include <afs/afssyscalls.h>
115 #include <afs/afsutil.h>
119 #include "daemon_com.h"
121 #include "salvsync.h"
124 #include "partition.h"
125 #include "volume_inline.h"
127 #include "afs/afs_assert.h"
134 #if !defined(offsetof)
139 #define afs_stat stat64
140 #define afs_fstat fstat64
141 #define afs_open open64
142 #else /* !O_LARGEFILE */
143 #define afs_stat stat
144 #define afs_fstat fstat
145 #define afs_open open
146 #endif /* !O_LARGEFILE */
148 #ifdef AFS_PTHREAD_ENV
149 pthread_mutex_t vol_glock_mutex;
150 pthread_mutex_t vol_trans_mutex;
151 pthread_cond_t vol_put_volume_cond;
152 pthread_cond_t vol_sleep_cond;
153 pthread_cond_t vol_init_attach_cond;
154 pthread_cond_t vol_vinit_cond;
155 int vol_attach_threads = 1;
156 #endif /* AFS_PTHREAD_ENV */
158 /* start-time configurable I/O parameters */
159 ih_init_params vol_io_params;
161 #ifdef AFS_DEMAND_ATTACH_FS
162 pthread_mutex_t vol_salvsync_mutex;
165 * Set this to 1 to disallow SALVSYNC communication in all threads; used
166 * during shutdown, since the salvageserver may have gone away.
168 static volatile sig_atomic_t vol_disallow_salvsync = 0;
169 #endif /* AFS_DEMAND_ATTACH_FS */
172 extern void *calloc(), *realloc();
175 /* Forward declarations */
176 static Volume *attach2(Error * ec, VolId volumeId, char *path,
177 struct DiskPartition64 *partp, Volume * vp,
178 int isbusy, int mode, int *acheckedOut);
179 static void ReallyFreeVolume(Volume * vp);
180 #ifdef AFS_DEMAND_ATTACH_FS
181 static void FreeVolume(Volume * vp);
182 #else /* !AFS_DEMAND_ATTACH_FS */
183 #define FreeVolume(vp) ReallyFreeVolume(vp)
184 static void VScanUpdateList(void);
185 #endif /* !AFS_DEMAND_ATTACH_FS */
186 static void VInitVolumeHeaderCache(afs_uint32 howMany);
187 static int GetVolumeHeader(Volume * vp);
188 static void ReleaseVolumeHeader(struct volHeader *hd);
189 static void FreeVolumeHeader(Volume * vp);
190 static void AddVolumeToHashTable(Volume * vp, int hashid);
191 static void DeleteVolumeFromHashTable(Volume * vp);
193 static int VHold(Volume * vp);
195 static int VHold_r(Volume * vp);
196 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
197 static void VReleaseVolumeHandles_r(Volume * vp);
198 static void VCloseVolumeHandles_r(Volume * vp);
199 static void LoadVolumeHeader(Error * ec, Volume * vp);
200 static int VCheckOffline(Volume * vp);
201 static int VCheckDetach(Volume * vp);
202 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
203 Volume * hint, const struct timespec *ts);
205 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
206 * defined when not linked with vice, XXXX */
207 ProgramType programType; /* The type of program using the package */
208 static VolumePackageOptions vol_opts;
210 /* extended volume package statistics */
213 #ifdef VOL_LOCK_DEBUG
214 pthread_t vol_glock_holder = 0;
218 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
219 /* Must be a multiple of 4 (1 word) !! */
221 /* this parameter needs to be tunable at runtime.
222 * 128 was really inadequate for largish servers -- at 16384 volumes this
223 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
224 * talk about bad spatial locality...
226 * an AVL or splay tree might work a lot better, but we'll just increase
227 * the default hash table size for now
229 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
230 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
231 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
234 * turn volume hash chains into partially ordered lists.
235 * when the threshold is exceeded between two adjacent elements,
236 * perform a chain rebalancing operation.
238 * keep the threshold high in order to keep cache line invalidates
239 * low "enough" on SMPs
241 #define VOLUME_HASH_REORDER_THRESHOLD 200
244 * when possible, don't just reorder single elements, but reorder
245 * entire chains of elements at once. a chain of elements that
246 * exceed the element previous to the pivot by at least CHAIN_THRESH
247 * accesses are moved in front of the chain whose elements have at
248 * least CHAIN_THRESH less accesses than the pivot element
250 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
252 #include "rx/rx_queue.h"
255 VolumeHashTable_t VolumeHashTable = {
256 DEFAULT_VOLUME_HASH_SIZE,
257 DEFAULT_VOLUME_HASH_MASK,
262 static void VInitVolumeHash(void);
266 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
270 afs_int32 ffs_tmp = x;
274 for (ffs_i = 1;; ffs_i++) {
281 #endif /* !AFS_HAVE_FFS */
283 #ifdef AFS_PTHREAD_ENV
285 * disk partition queue element
287 typedef struct diskpartition_queue_t {
288 struct rx_queue queue; /**< queue header */
289 struct DiskPartition64 *diskP; /**< disk partition table entry */
290 } diskpartition_queue_t;
292 #ifndef AFS_DEMAND_ATTACH_FS
294 typedef struct vinitvolumepackage_thread_t {
295 struct rx_queue queue;
296 pthread_cond_t thread_done_cv;
297 int n_threads_complete;
298 } vinitvolumepackage_thread_t;
299 static void * VInitVolumePackageThread(void * args);
301 #else /* !AFS_DEMAND_ATTTACH_FS */
302 #define VINIT_BATCH_MAX_SIZE 512
305 * disk partition work queue
307 struct partition_queue {
308 struct rx_queue head; /**< diskpartition_queue_t queue */
309 pthread_mutex_t mutex;
314 * volumes parameters for preattach
316 struct volume_init_batch {
317 struct rx_queue queue; /**< queue header */
318 int thread; /**< posting worker thread */
319 int last; /**< indicates thread is done */
320 int size; /**< number of volume ids in batch */
321 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
325 * volume parameters work queue
327 struct volume_init_queue {
328 struct rx_queue head; /**< volume_init_batch queue */
329 pthread_mutex_t mutex;
334 * volume init worker thread parameters
336 struct vinitvolumepackage_thread_param {
337 int nthreads; /**< total number of worker threads */
338 int thread; /**< thread number for this worker thread */
339 struct partition_queue *pq; /**< queue partitions to scan */
340 struct volume_init_queue *vq; /**< queue of volume to preattach */
343 static void *VInitVolumePackageThread(void *args);
344 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
345 static VolId VInitNextVolumeId(DIR *dirp);
346 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
348 #endif /* !AFS_DEMAND_ATTACH_FS */
349 #endif /* AFS_PTHREAD_ENV */
351 #ifndef AFS_DEMAND_ATTACH_FS
352 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
353 int * nAttached, int * nUnattached);
354 #endif /* AFS_DEMAND_ATTACH_FS */
357 #ifdef AFS_DEMAND_ATTACH_FS
358 /* demand attach fileserver extensions */
361 * in the future we will support serialization of VLRU state into the fs_state
364 * these structures are the beginning of that effort
366 struct VLRU_DiskHeader {
367 struct versionStamp stamp; /* magic and structure version number */
368 afs_uint32 mtime; /* time of dump to disk */
369 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
372 struct VLRU_DiskEntry {
373 afs_uint32 vid; /* volume ID */
374 afs_uint32 idx; /* generation */
375 afs_uint32 last_get; /* timestamp of last get */
378 struct VLRU_StartupQueue {
379 struct VLRU_DiskEntry * entry;
384 typedef struct vshutdown_thread_t {
386 pthread_mutex_t lock;
388 pthread_cond_t master_cv;
390 int n_threads_complete;
392 int schedule_version;
395 byte n_parts_done_pass;
396 byte part_thread_target[VOLMAXPARTS+1];
397 byte part_done_pass[VOLMAXPARTS+1];
398 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
399 int stats[4][VOLMAXPARTS+1];
400 } vshutdown_thread_t;
401 static void * VShutdownThread(void * args);
404 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
405 static int VCheckFree(Volume * vp);
408 static void AddVolumeToVByPList_r(Volume * vp);
409 static void DeleteVolumeFromVByPList_r(Volume * vp);
410 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
411 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
412 static void VVByPListWait_r(struct DiskPartition64 * dp);
414 /* online salvager */
415 static int VCheckSalvage(Volume * vp);
416 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
417 static int VScheduleSalvage_r(Volume * vp);
420 /* Volume hash table */
421 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
422 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
423 static void VHashEndExclusive_r(VolumeHashChainHead * head);
424 static void VHashWait_r(VolumeHashChainHead * head);
427 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
428 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
429 struct rx_queue ** idx);
430 static void ShutdownController(vshutdown_thread_t * params);
431 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
434 static void VLRU_ComputeConstants(void);
435 static void VInitVLRU(void);
436 static void VLRU_Init_Node_r(Volume * vp);
437 static void VLRU_Add_r(Volume * vp);
438 static void VLRU_Delete_r(Volume * vp);
439 static void VLRU_UpdateAccess_r(Volume * vp);
440 static void * VLRU_ScannerThread(void * args);
441 static void VLRU_Scan_r(int idx);
442 static void VLRU_Promote_r(int idx);
443 static void VLRU_Demote_r(int idx);
444 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
447 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
448 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
449 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
452 pthread_key_t VThread_key;
453 VThreadOptions_t VThread_defaults = {
454 0 /**< allow salvsync */
456 #endif /* AFS_DEMAND_ATTACH_FS */
459 struct Lock vol_listLock; /* Lock obtained when listing volumes:
460 * prevents a volume from being missed
461 * if the volume is attached during a
465 /* Common message used when the volume goes off line */
466 char *VSalvageMessage =
467 "Files in this volume are currently unavailable; call operations";
469 int VInit; /* 0 - uninitialized,
470 * 1 - initialized but not all volumes have been attached,
471 * 2 - initialized and all volumes have been attached,
472 * 3 - initialized, all volumes have been attached, and
473 * VConnectFS() has completed. */
475 static int vinit_attach_abort = 0;
477 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
478 * used to stamp volume headers and in-core
479 * vnodes. When the volume goes on-line the
480 * vnode will be invalidated
481 * access only with VOL_LOCK held */
486 /***************************************************/
487 /* Startup routines */
488 /***************************************************/
490 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
491 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
492 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
496 * assign default values to a VolumePackageOptions struct.
498 * Always call this on a VolumePackageOptions struct first, then set any
499 * specific options you want, then call VInitVolumePackage2.
501 * @param[in] pt caller's program type
502 * @param[out] opts volume package options
505 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
507 opts->nLargeVnodes = opts->nSmallVnodes = 5;
510 opts->canScheduleSalvage = 0;
511 opts->canUseFSSYNC = 0;
512 opts->canUseSALVSYNC = 0;
515 opts->unsafe_attach = 1;
516 #else /* !FAST_RESTART */
517 opts->unsafe_attach = 0;
518 #endif /* !FAST_RESTART */
522 opts->canScheduleSalvage = 1;
523 opts->canUseSALVSYNC = 1;
527 opts->canUseFSSYNC = 1;
531 opts->nLargeVnodes = 0;
532 opts->nSmallVnodes = 0;
534 opts->canScheduleSalvage = 1;
535 opts->canUseFSSYNC = 1;
545 * Set VInit to a certain value, and signal waiters.
547 * @param[in] value the value to set VInit to
552 VSetVInit_r(int value)
555 CV_BROADCAST(&vol_vinit_cond);
559 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
561 int errors = 0; /* Number of errors while finding vice partitions. */
566 memset(&VStats, 0, sizeof(VStats));
567 VStats.hdr_cache_size = 200;
569 VInitPartitionPackage();
571 #ifdef AFS_DEMAND_ATTACH_FS
572 if (programType == fileServer) {
575 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
577 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
580 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
581 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
582 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
583 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
584 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
585 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
586 #ifndef AFS_PTHREAD_ENV
588 #endif /* AFS_PTHREAD_ENV */
589 Lock_Init(&vol_listLock);
591 srandom(time(0)); /* For VGetVolumeInfo */
593 #ifdef AFS_DEMAND_ATTACH_FS
594 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
595 #endif /* AFS_DEMAND_ATTACH_FS */
597 /* Ok, we have done enough initialization that fileserver can
598 * start accepting calls, even though the volumes may not be
599 * available just yet.
603 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
604 if (programType == salvageServer) {
607 #endif /* AFS_DEMAND_ATTACH_FS */
608 #ifdef FSSYNC_BUILD_SERVER
609 if (programType == fileServer) {
613 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
614 if (VCanUseSALVSYNC()) {
615 /* establish a connection to the salvager at this point */
616 osi_Assert(VConnectSALV() != 0);
618 #endif /* AFS_DEMAND_ATTACH_FS */
620 if (opts->volcache > VStats.hdr_cache_size)
621 VStats.hdr_cache_size = opts->volcache;
622 VInitVolumeHeaderCache(VStats.hdr_cache_size);
624 VInitVnodes(vLarge, opts->nLargeVnodes);
625 VInitVnodes(vSmall, opts->nSmallVnodes);
628 errors = VAttachPartitions();
632 if (programType != fileServer) {
633 errors = VInitAttachVolumes(programType);
639 #ifdef FSSYNC_BUILD_CLIENT
640 if (VCanUseFSSYNC()) {
642 #ifdef AFS_DEMAND_ATTACH_FS
643 if (programType == salvageServer) {
644 Log("Unable to connect to file server; aborted\n");
647 #endif /* AFS_DEMAND_ATTACH_FS */
648 Log("Unable to connect to file server; will retry at need\n");
651 #endif /* FSSYNC_BUILD_CLIENT */
656 #if !defined(AFS_PTHREAD_ENV)
658 * Attach volumes in vice partitions
660 * @param[in] pt calling program type
663 * @note This is the original, non-threaded version of attach parititions.
665 * @post VInit state is 2
668 VInitAttachVolumes(ProgramType pt)
670 osi_Assert(VInit==1);
671 if (pt == fileServer) {
672 struct DiskPartition64 *diskP;
673 /* Attach all the volumes in this partition */
674 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
675 int nAttached = 0, nUnattached = 0;
676 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
680 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
681 LWP_NoYieldSignal(VInitAttachVolumes);
685 #endif /* !AFS_PTHREAD_ENV */
687 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
689 * Attach volumes in vice partitions
691 * @param[in] pt calling program type
694 * @note Threaded version of attach parititions.
696 * @post VInit state is 2
699 VInitAttachVolumes(ProgramType pt)
701 osi_Assert(VInit==1);
702 if (pt == fileServer) {
703 struct DiskPartition64 *diskP;
704 struct vinitvolumepackage_thread_t params;
705 struct diskpartition_queue_t * dpq;
706 int i, threads, parts;
708 pthread_attr_t attrs;
710 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
712 params.n_threads_complete = 0;
714 /* create partition work queue */
715 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
716 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
717 osi_Assert(dpq != NULL);
719 queue_Append(¶ms,dpq);
722 threads = MIN(parts, vol_attach_threads);
725 /* spawn off a bunch of initialization threads */
726 osi_Assert(pthread_attr_init(&attrs) == 0);
727 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
729 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
730 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
734 for (i=0; i < threads; i++) {
737 osi_Assert(pthread_create
738 (&tid, &attrs, &VInitVolumePackageThread,
740 AFS_SIGSET_RESTORE();
743 while(params.n_threads_complete < threads) {
744 VOL_CV_WAIT(¶ms.thread_done_cv);
748 osi_Assert(pthread_attr_destroy(&attrs) == 0);
750 /* if we're only going to run one init thread, don't bother creating
752 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
753 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
756 VInitVolumePackageThread(¶ms);
759 CV_DESTROY(¶ms.thread_done_cv);
762 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
763 CV_BROADCAST(&vol_init_attach_cond);
769 VInitVolumePackageThread(void * args) {
771 struct DiskPartition64 *diskP;
772 struct vinitvolumepackage_thread_t * params;
773 struct diskpartition_queue_t * dpq;
775 params = (vinitvolumepackage_thread_t *) args;
779 /* Attach all the volumes in this partition */
780 while (queue_IsNotEmpty(params)) {
781 int nAttached = 0, nUnattached = 0;
783 if (vinit_attach_abort) {
784 Log("Aborting initialization\n");
788 dpq = queue_First(params,diskpartition_queue_t);
794 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
800 params->n_threads_complete++;
801 CV_SIGNAL(¶ms->thread_done_cv);
805 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
807 #if defined(AFS_DEMAND_ATTACH_FS)
809 * Attach volumes in vice partitions
811 * @param[in] pt calling program type
814 * @note Threaded version of attach partitions.
816 * @post VInit state is 2
819 VInitAttachVolumes(ProgramType pt)
821 osi_Assert(VInit==1);
822 if (pt == fileServer) {
824 struct DiskPartition64 *diskP;
825 struct partition_queue pq;
826 struct volume_init_queue vq;
828 int i, threads, parts;
830 pthread_attr_t attrs;
832 /* create partition work queue */
834 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
835 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
836 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
837 struct diskpartition_queue_t *dp;
838 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
839 osi_Assert(dp != NULL);
841 queue_Append(&pq, dp);
844 /* number of worker threads; at least one, not to exceed the number of partitions */
845 threads = MIN(parts, vol_attach_threads);
847 /* create volume work queue */
849 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
850 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
852 osi_Assert(pthread_attr_init(&attrs) == 0);
853 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
855 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
856 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
859 /* create threads to scan disk partitions. */
860 for (i=0; i < threads; i++) {
861 struct vinitvolumepackage_thread_param *params;
864 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
868 params->nthreads = threads;
869 params->thread = i+1;
872 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
873 AFS_SIGSET_RESTORE();
876 VInitPreAttachVolumes(threads, &vq);
878 osi_Assert(pthread_attr_destroy(&attrs) == 0);
880 MUTEX_DESTROY(&pq.mutex);
882 MUTEX_DESTROY(&vq.mutex);
886 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
887 CV_BROADCAST(&vol_init_attach_cond);
894 * Volume package initialization worker thread. Scan partitions for volume
895 * header files. Gather batches of volume ids and dispatch them to
896 * the main thread to be preattached. The volume preattachement is done
897 * in the main thread to avoid global volume lock contention.
900 VInitVolumePackageThread(void *args)
902 struct vinitvolumepackage_thread_param *params;
903 struct DiskPartition64 *partition;
904 struct partition_queue *pq;
905 struct volume_init_queue *vq;
906 struct volume_init_batch *vb;
909 params = (struct vinitvolumepackage_thread_param *)args;
915 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
917 vb->thread = params->thread;
921 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
922 while((partition = VInitNextPartition(pq))) {
926 Log("Partition %s: pre-attaching volumes\n", partition->name);
927 dirp = opendir(VPartitionPath(partition));
929 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
932 while ((vid = VInitNextVolumeId(dirp))) {
933 Volume *vp = (Volume*)malloc(sizeof(Volume));
935 memset(vp, 0, sizeof(Volume));
936 vp->device = partition->device;
937 vp->partition = partition;
939 queue_Init(&vp->vnode_list);
940 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
942 vb->batch[vb->size++] = vp;
943 if (vb->size == VINIT_BATCH_MAX_SIZE) {
944 MUTEX_ENTER(&vq->mutex);
945 queue_Append(vq, vb);
946 CV_BROADCAST(&vq->cv);
947 MUTEX_EXIT(&vq->mutex);
949 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
951 vb->thread = params->thread;
960 MUTEX_ENTER(&vq->mutex);
961 queue_Append(vq, vb);
962 CV_BROADCAST(&vq->cv);
963 MUTEX_EXIT(&vq->mutex);
965 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
971 * Read next element from the pre-populated partition list.
973 static struct DiskPartition64*
974 VInitNextPartition(struct partition_queue *pq)
976 struct DiskPartition64 *partition;
977 struct diskpartition_queue_t *dp; /* queue element */
979 if (vinit_attach_abort) {
980 Log("Aborting volume preattach thread.\n");
984 /* get next partition to scan */
985 MUTEX_ENTER(&pq->mutex);
986 if (queue_IsEmpty(pq)) {
987 MUTEX_EXIT(&pq->mutex);
990 dp = queue_First(pq, diskpartition_queue_t);
992 MUTEX_EXIT(&pq->mutex);
995 osi_Assert(dp->diskP);
997 partition = dp->diskP;
1003 * Find next volume id on the partition.
1006 VInitNextVolumeId(DIR *dirp)
1012 while((d = readdir(dirp))) {
1013 if (vinit_attach_abort) {
1014 Log("Aborting volume preattach thread.\n");
1017 ext = strrchr(d->d_name, '.');
1018 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1019 vid = VolumeNumber(d->d_name);
1023 Log("Warning: bogus volume header file: %s\n", d->d_name);
1030 * Preattach volumes in batches to avoid lock contention.
1033 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1035 struct volume_init_batch *vb;
1039 /* dequeue next volume */
1040 MUTEX_ENTER(&vq->mutex);
1041 if (queue_IsEmpty(vq)) {
1042 CV_WAIT(&vq->cv, &vq->mutex);
1044 vb = queue_First(vq, volume_init_batch);
1046 MUTEX_EXIT(&vq->mutex);
1050 for (i = 0; i<vb->size; i++) {
1056 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1058 Log("Error looking up volume, code=%d\n", ec);
1061 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1064 /* put pre-attached volume onto the hash table
1065 * and bring it up to the pre-attached state */
1066 AddVolumeToHashTable(vp, vp->hashid);
1067 AddVolumeToVByPList_r(vp);
1068 VLRU_Init_Node_r(vp);
1069 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1082 #endif /* AFS_DEMAND_ATTACH_FS */
1084 #if !defined(AFS_DEMAND_ATTACH_FS)
1086 * attach all volumes on a given disk partition
1089 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1095 Log("Partition %s: attaching volumes\n", diskP->name);
1096 dirp = opendir(VPartitionPath(diskP));
1098 Log("opendir on Partition %s failed!\n", diskP->name);
1102 while ((dp = readdir(dirp))) {
1104 p = strrchr(dp->d_name, '.');
1106 if (vinit_attach_abort) {
1107 Log("Partition %s: abort attach volumes\n", diskP->name);
1111 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1114 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1116 (*(vp ? nAttached : nUnattached))++;
1117 if (error == VOFFLINE)
1118 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1119 else if (LogLevel >= 5) {
1120 Log("Partition %s: attached volume %d (%s)\n",
1121 diskP->name, VolumeNumber(dp->d_name),
1130 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1135 #endif /* !AFS_DEMAND_ATTACH_FS */
1137 /***************************************************/
1138 /* Shutdown routines */
1139 /***************************************************/
1143 * highly multithreaded volume package shutdown
1145 * with the demand attach fileserver extensions,
1146 * VShutdown has been modified to be multithreaded.
1147 * In order to achieve optimal use of many threads,
1148 * the shutdown code involves one control thread and
1149 * n shutdown worker threads. The control thread
1150 * periodically examines the number of volumes available
1151 * for shutdown on each partition, and produces a worker
1152 * thread allocation schedule. The idea is to eliminate
1153 * redundant scheduling computation on the workers by
1154 * having a single master scheduler.
1156 * The scheduler's objectives are:
1158 * each partition with volumes remaining gets allocated
1159 * at least 1 thread (assuming sufficient threads)
1161 * threads are allocated proportional to the number of
1162 * volumes remaining to be offlined. This ensures that
1163 * the OS I/O scheduler has many requests to elevator
1164 * seek on partitions that will (presumably) take the
1165 * longest amount of time (from now) to finish shutdown
1166 * (3) keep threads busy
1167 * when there are extra threads, they are assigned to
1168 * partitions using a simple round-robin algorithm
1170 * In the future, we may wish to add the ability to adapt
1171 * to the relative performance patterns of each disk
1176 * multi-step shutdown process
1178 * demand attach shutdown is a four-step process. Each
1179 * shutdown "pass" shuts down increasingly more difficult
1180 * volumes. The main purpose is to achieve better cache
1181 * utilization during shutdown.
1184 * shutdown volumes in the unattached, pre-attached
1187 * shutdown attached volumes with cached volume headers
1189 * shutdown all volumes in non-exclusive states
1191 * shutdown all remaining volumes
1194 #ifdef AFS_DEMAND_ATTACH_FS
1200 struct DiskPartition64 * diskP;
1201 struct diskpartition_queue_t * dpq;
1202 vshutdown_thread_t params;
1204 pthread_attr_t attrs;
1206 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1209 Log("VShutdown: aborting attach volumes\n");
1210 vinit_attach_abort = 1;
1211 VOL_CV_WAIT(&vol_init_attach_cond);
1214 for (params.n_parts=0, diskP = DiskPartitionList;
1215 diskP; diskP = diskP->next, params.n_parts++);
1217 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1218 params.n_parts, params.n_parts > 1 ? "s" : "");
1220 if (vol_attach_threads > 1) {
1221 /* prepare for parallel shutdown */
1222 params.n_threads = vol_attach_threads;
1223 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1224 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1225 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1226 osi_Assert(pthread_attr_init(&attrs) == 0);
1227 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1228 queue_Init(¶ms);
1230 /* setup the basic partition information structures for
1231 * parallel shutdown */
1232 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1234 struct rx_queue * qp, * nqp;
1238 VVByPListWait_r(diskP);
1239 VVByPListBeginExclusive_r(diskP);
1242 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1243 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1247 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1248 VPartitionPath(diskP), count);
1251 /* build up the pass 0 shutdown work queue */
1252 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1253 osi_Assert(dpq != NULL);
1255 queue_Prepend(¶ms, dpq);
1257 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1260 Log("VShutdown: beginning parallel fileserver shutdown\n");
1261 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1262 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1264 /* do pass 0 shutdown */
1265 MUTEX_ENTER(¶ms.lock);
1266 for (i=0; i < params.n_threads; i++) {
1267 osi_Assert(pthread_create
1268 (&tid, &attrs, &VShutdownThread,
1272 /* wait for all the pass 0 shutdowns to complete */
1273 while (params.n_threads_complete < params.n_threads) {
1274 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1276 params.n_threads_complete = 0;
1278 CV_BROADCAST(¶ms.cv);
1279 MUTEX_EXIT(¶ms.lock);
1281 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1282 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1284 /* run the parallel shutdown scheduler. it will drop the glock internally */
1285 ShutdownController(¶ms);
1287 /* wait for all the workers to finish pass 3 and terminate */
1288 while (params.pass < 4) {
1289 VOL_CV_WAIT(¶ms.cv);
1292 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1293 CV_DESTROY(¶ms.cv);
1294 CV_DESTROY(¶ms.master_cv);
1295 MUTEX_DESTROY(¶ms.lock);
1297 /* drop the VByPList exclusive reservations */
1298 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1299 VVByPListEndExclusive_r(diskP);
1300 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1301 VPartitionPath(diskP),
1302 params.stats[0][diskP->index],
1303 params.stats[1][diskP->index],
1304 params.stats[2][diskP->index],
1305 params.stats[3][diskP->index]);
1308 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1310 /* if we're only going to run one shutdown thread, don't bother creating
1312 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1314 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1315 VShutdownByPartition_r(diskP);
1319 Log("VShutdown: complete.\n");
1322 #else /* AFS_DEMAND_ATTACH_FS */
1332 Log("VShutdown: aborting attach volumes\n");
1333 vinit_attach_abort = 1;
1334 #ifdef AFS_PTHREAD_ENV
1335 VOL_CV_WAIT(&vol_init_attach_cond);
1337 LWP_WaitProcess(VInitAttachVolumes);
1338 #endif /* AFS_PTHREAD_ENV */
1341 Log("VShutdown: shutting down on-line volumes...\n");
1342 for (i = 0; i < VolumeHashTable.Size; i++) {
1343 /* try to hold first volume in the hash table */
1344 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1348 Log("VShutdown: Attempting to take volume %u offline.\n",
1351 /* next, take the volume offline (drops reference count) */
1352 VOffline_r(vp, "File server was shut down");
1356 Log("VShutdown: complete.\n");
1358 #endif /* AFS_DEMAND_ATTACH_FS */
1364 osi_Assert(VInit>0);
1371 * stop new activity (e.g. SALVSYNC) from occurring
1373 * Use this to make the volume package less busy; for example, during
1374 * shutdown. This doesn't actually shutdown/detach anything in the
1375 * volume package, but prevents certain processes from ocurring. For
1376 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1377 * could also use this to prevent new volume attachment, or prevent
1378 * other programs from checking out volumes, etc.
1383 #ifdef AFS_DEMAND_ATTACH_FS
1384 /* make sure we don't try to contact the salvageserver, since it may
1385 * not be around anymore */
1386 vol_disallow_salvsync = 1;
1390 #ifdef AFS_DEMAND_ATTACH_FS
1393 * shutdown control thread
1396 ShutdownController(vshutdown_thread_t * params)
1399 struct DiskPartition64 * diskP;
1401 vshutdown_thread_t shadow;
1403 ShutdownCreateSchedule(params);
1405 while ((params->pass < 4) &&
1406 (params->n_threads_complete < params->n_threads)) {
1407 /* recompute schedule once per second */
1409 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1413 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1414 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1415 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1416 shadow.n_threads_complete, shadow.n_parts_done_pass);
1417 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1419 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1421 diskP->vol_list.len,
1422 shadow.part_thread_target[id],
1423 shadow.part_done_pass[id],
1424 shadow.part_pass_head[id]);
1430 ShutdownCreateSchedule(params);
1434 /* create the shutdown thread work schedule.
1435 * this scheduler tries to implement fairness
1436 * by allocating at least 1 thread to each
1437 * partition with volumes to be shutdown,
1438 * and then it attempts to allocate remaining
1439 * threads based upon the amount of work left
1442 ShutdownCreateSchedule(vshutdown_thread_t * params)
1444 struct DiskPartition64 * diskP;
1445 int sum, thr_workload, thr_left;
1446 int part_residue[VOLMAXPARTS+1];
1449 /* compute the total number of outstanding volumes */
1451 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1452 sum += diskP->vol_list.len;
1455 params->schedule_version++;
1456 params->vol_remaining = sum;
1461 /* compute average per-thread workload */
1462 thr_workload = sum / params->n_threads;
1463 if (sum % params->n_threads)
1466 thr_left = params->n_threads;
1467 memset(&part_residue, 0, sizeof(part_residue));
1469 /* for fairness, give every partition with volumes remaining
1470 * at least one thread */
1471 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1473 if (diskP->vol_list.len) {
1474 params->part_thread_target[id] = 1;
1477 params->part_thread_target[id] = 0;
1481 if (thr_left && thr_workload) {
1482 /* compute length-weighted workloads */
1485 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1487 delta = (diskP->vol_list.len / thr_workload) -
1488 params->part_thread_target[id];
1492 if (delta < thr_left) {
1493 params->part_thread_target[id] += delta;
1496 params->part_thread_target[id] += thr_left;
1504 /* try to assign any leftover threads to partitions that
1505 * had volume lengths closer to needing thread_target+1 */
1506 int max_residue, max_id = 0;
1508 /* compute the residues */
1509 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1511 part_residue[id] = diskP->vol_list.len -
1512 (params->part_thread_target[id] * thr_workload);
1515 /* now try to allocate remaining threads to partitions with the
1516 * highest residues */
1519 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1521 if (part_residue[id] > max_residue) {
1522 max_residue = part_residue[id];
1531 params->part_thread_target[max_id]++;
1533 part_residue[max_id] = 0;
1538 /* punt and give any remaining threads equally to each partition */
1540 if (thr_left >= params->n_parts) {
1541 alloc = thr_left / params->n_parts;
1542 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1544 params->part_thread_target[id] += alloc;
1549 /* finish off the last of the threads */
1550 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1552 params->part_thread_target[id]++;
1558 /* worker thread for parallel shutdown */
1560 VShutdownThread(void * args)
1562 vshutdown_thread_t * params;
1563 int found, pass, schedule_version_save, count;
1564 struct DiskPartition64 *diskP;
1565 struct diskpartition_queue_t * dpq;
1568 params = (vshutdown_thread_t *) args;
1570 /* acquire the shutdown pass 0 lock */
1571 MUTEX_ENTER(¶ms->lock);
1573 /* if there's still pass 0 work to be done,
1574 * get a work entry, and do a pass 0 shutdown */
1575 if (queue_IsNotEmpty(params)) {
1576 dpq = queue_First(params, diskpartition_queue_t);
1578 MUTEX_EXIT(¶ms->lock);
1584 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1586 params->stats[0][diskP->index] = count;
1587 MUTEX_ENTER(¶ms->lock);
1590 params->n_threads_complete++;
1591 if (params->n_threads_complete == params->n_threads) {
1592 /* notify control thread that all workers have completed pass 0 */
1593 CV_SIGNAL(¶ms->master_cv);
1595 while (params->pass == 0) {
1596 CV_WAIT(¶ms->cv, ¶ms->lock);
1600 MUTEX_EXIT(¶ms->lock);
1603 pass = params->pass;
1604 osi_Assert(pass > 0);
1606 /* now escalate through the more complicated shutdowns */
1608 schedule_version_save = params->schedule_version;
1610 /* find a disk partition to work on */
1611 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1613 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1614 params->part_thread_target[id]--;
1621 /* hmm. for some reason the controller thread couldn't find anything for
1622 * us to do. let's see if there's anything we can do */
1623 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1625 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1628 } else if (!params->part_done_pass[id]) {
1629 params->part_done_pass[id] = 1;
1630 params->n_parts_done_pass++;
1632 Log("VShutdown: done shutting down volumes on partition %s.\n",
1633 VPartitionPath(diskP));
1639 /* do work on this partition until either the controller
1640 * creates a new schedule, or we run out of things to do
1641 * on this partition */
1644 while (!params->part_done_pass[id] &&
1645 (schedule_version_save == params->schedule_version)) {
1646 /* ShutdownVolumeWalk_r will drop the glock internally */
1647 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1648 if (!params->part_done_pass[id]) {
1649 params->part_done_pass[id] = 1;
1650 params->n_parts_done_pass++;
1652 Log("VShutdown: done shutting down volumes on partition %s.\n",
1653 VPartitionPath(diskP));
1661 params->stats[pass][id] += count;
1663 /* ok, everyone is done this pass, proceed */
1666 params->n_threads_complete++;
1667 while (params->pass == pass) {
1668 if (params->n_threads_complete == params->n_threads) {
1669 /* we are the last thread to complete, so we will
1670 * reinitialize worker pool state for the next pass */
1671 params->n_threads_complete = 0;
1672 params->n_parts_done_pass = 0;
1674 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1676 params->part_done_pass[id] = 0;
1677 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1680 /* compute a new thread schedule before releasing all the workers */
1681 ShutdownCreateSchedule(params);
1683 /* wake up all the workers */
1684 CV_BROADCAST(¶ms->cv);
1687 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1688 pass, params->n_threads, params->n_parts);
1691 VOL_CV_WAIT(¶ms->cv);
1694 pass = params->pass;
1708 /* shut down all volumes on a given disk partition
1710 * note that this function will not allow mp-fast
1711 * shutdown of a partition */
1713 VShutdownByPartition_r(struct DiskPartition64 * dp)
1719 /* wait for other exclusive ops to finish */
1720 VVByPListWait_r(dp);
1722 /* begin exclusive access */
1723 VVByPListBeginExclusive_r(dp);
1725 /* pick the low-hanging fruit first,
1726 * then do the complicated ones last
1727 * (has the advantage of keeping
1728 * in-use volumes up until the bitter end) */
1729 for (pass = 0, total=0; pass < 4; pass++) {
1730 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1731 total += pass_stats[pass];
1734 /* end exclusive access */
1735 VVByPListEndExclusive_r(dp);
1737 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1738 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1743 /* internal shutdown functionality
1745 * for multi-pass shutdown:
1746 * 0 to only "shutdown" {pre,un}attached and error state volumes
1747 * 1 to also shutdown attached volumes w/ volume header loaded
1748 * 2 to also shutdown attached volumes w/o volume header loaded
1749 * 3 to also shutdown exclusive state volumes
1751 * caller MUST hold exclusive access on the hash chain
1752 * because we drop vol_glock_mutex internally
1754 * this function is reentrant for passes 1--3
1755 * (e.g. multiple threads can cooperate to
1756 * shutdown a partition mp-fast)
1758 * pass 0 is not scaleable because the volume state data is
1759 * synchronized by vol_glock mutex, and the locking overhead
1760 * is too high to drop the lock long enough to do linked list
1764 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1766 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1769 while (ShutdownVolumeWalk_r(dp, pass, &q))
1775 /* conditionally shutdown one volume on partition dp
1776 * returns 1 if a volume was shutdown in this pass,
1779 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1780 struct rx_queue ** idx)
1782 struct rx_queue *qp, *nqp;
1787 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1788 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1792 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1793 (V_attachState(vp) != VOL_STATE_ERROR) &&
1794 (V_attachState(vp) != VOL_STATE_DELETED) &&
1795 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1799 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1800 (vp->header == NULL)) {
1804 if (VIsExclusiveState(V_attachState(vp))) {
1809 DeleteVolumeFromVByPList_r(vp);
1810 VShutdownVolume_r(vp);
1820 * shutdown a specific volume
1822 /* caller MUST NOT hold a heavyweight ref on vp */
1824 VShutdownVolume_r(Volume * vp)
1828 VCreateReservation_r(vp);
1830 if (LogLevel >= 5) {
1831 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1832 vp->hashid, vp->partition->device, V_attachState(vp));
1835 /* wait for other blocking ops to finish */
1836 VWaitExclusiveState_r(vp);
1838 osi_Assert(VIsValidState(V_attachState(vp)));
1840 switch(V_attachState(vp)) {
1841 case VOL_STATE_SALVAGING:
1842 /* Leave salvaging volumes alone. Any in-progress salvages will
1843 * continue working after viced shuts down. This is intentional.
1846 case VOL_STATE_PREATTACHED:
1847 case VOL_STATE_ERROR:
1848 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1849 case VOL_STATE_UNATTACHED:
1850 case VOL_STATE_DELETED:
1852 case VOL_STATE_GOING_OFFLINE:
1853 case VOL_STATE_SHUTTING_DOWN:
1854 case VOL_STATE_ATTACHED:
1858 Log("VShutdown: Attempting to take volume %u offline.\n",
1861 /* take the volume offline (drops reference count) */
1862 VOffline_r(vp, "File server was shut down");
1869 VCancelReservation_r(vp);
1873 #endif /* AFS_DEMAND_ATTACH_FS */
1876 /***************************************************/
1877 /* Header I/O routines */
1878 /***************************************************/
1880 /* open a descriptor for the inode (h),
1881 * read in an on-disk structure into buffer (to) of size (size),
1882 * verify versionstamp in structure has magic (magic) and
1883 * optionally verify version (version) if (version) is nonzero
1886 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1889 struct versionStamp *vsn;
1904 vsn = (struct versionStamp *)to;
1905 if (FDH_PREAD(fdP, to, size, 0) != size || vsn->magic != magic) {
1907 FDH_REALLYCLOSE(fdP);
1912 /* Check is conditional, in case caller wants to inspect version himself */
1913 if (version && vsn->version != version) {
1919 WriteVolumeHeader_r(Error * ec, Volume * vp)
1921 IHandle_t *h = V_diskDataHandle(vp);
1931 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1932 != sizeof(V_disk(vp))) {
1934 FDH_REALLYCLOSE(fdP);
1940 /* VolumeHeaderToDisk
1941 * Allows for storing 64 bit inode numbers in on-disk volume header
1944 /* convert in-memory representation of a volume header to the
1945 * on-disk representation of a volume header */
1947 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1950 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1951 dh->stamp = h->stamp;
1953 dh->parent = h->parent;
1955 #ifdef AFS_64BIT_IOPS_ENV
1956 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1957 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1958 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1959 dh->smallVnodeIndex_hi =
1960 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1961 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1962 dh->largeVnodeIndex_hi =
1963 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1964 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1965 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1967 dh->volumeInfo_lo = h->volumeInfo;
1968 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1969 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1970 dh->linkTable_lo = h->linkTable;
1974 /* DiskToVolumeHeader
1975 * Converts an on-disk representation of a volume header to
1976 * the in-memory representation of a volume header.
1978 * Makes the assumption that AFS has *always*
1979 * zero'd the volume header file so that high parts of inode
1980 * numbers are 0 in older (SGI EFS) volume header files.
1983 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1985 memset(h, 0, sizeof(VolumeHeader_t));
1986 h->stamp = dh->stamp;
1988 h->parent = dh->parent;
1990 #ifdef AFS_64BIT_IOPS_ENV
1992 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1994 h->smallVnodeIndex =
1995 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1996 smallVnodeIndex_hi << 32);
1998 h->largeVnodeIndex =
1999 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2000 largeVnodeIndex_hi << 32);
2002 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2004 h->volumeInfo = dh->volumeInfo_lo;
2005 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2006 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2007 h->linkTable = dh->linkTable_lo;
2012 /***************************************************/
2013 /* Volume Attachment routines */
2014 /***************************************************/
2016 #ifdef AFS_DEMAND_ATTACH_FS
2018 * pre-attach a volume given its path.
2020 * @param[out] ec outbound error code
2021 * @param[in] partition partition path string
2022 * @param[in] name volume id string
2024 * @return volume object pointer
2026 * @note A pre-attached volume will only have its partition
2027 * and hashid fields initialized. At first call to
2028 * VGetVolume, the volume will be fully attached.
2032 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2036 vp = VPreAttachVolumeByName_r(ec, partition, name);
2042 * pre-attach a volume given its path.
2044 * @param[out] ec outbound error code
2045 * @param[in] partition path to vice partition
2046 * @param[in] name volume id string
2048 * @return volume object pointer
2050 * @pre VOL_LOCK held
2052 * @internal volume package internal use only.
2055 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2057 return VPreAttachVolumeById_r(ec,
2059 VolumeNumber(name));
2063 * pre-attach a volume given its path and numeric volume id.
2065 * @param[out] ec error code return
2066 * @param[in] partition path to vice partition
2067 * @param[in] volumeId numeric volume id
2069 * @return volume object pointer
2071 * @pre VOL_LOCK held
2073 * @internal volume package internal use only.
2076 VPreAttachVolumeById_r(Error * ec,
2081 struct DiskPartition64 *partp;
2085 osi_Assert(programType == fileServer);
2087 if (!(partp = VGetPartition_r(partition, 0))) {
2089 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2093 vp = VLookupVolume_r(ec, volumeId, NULL);
2098 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2102 * preattach a volume.
2104 * @param[out] ec outbound error code
2105 * @param[in] partp pointer to partition object
2106 * @param[in] vp pointer to volume object
2107 * @param[in] vid volume id
2109 * @return volume object pointer
2111 * @pre VOL_LOCK is held.
2113 * @warning Returned volume object pointer does not have to
2114 * equal the pointer passed in as argument vp. There
2115 * are potential race conditions which can result in
2116 * the pointers having different values. It is up to
2117 * the caller to make sure that references are handled
2118 * properly in this case.
2120 * @note If there is already a volume object registered with
2121 * the same volume id, its pointer MUST be passed as
2122 * argument vp. Failure to do so will result in a silent
2123 * failure to preattach.
2125 * @internal volume package internal use only.
2128 VPreAttachVolumeByVp_r(Error * ec,
2129 struct DiskPartition64 * partp,
2137 /* check to see if pre-attach already happened */
2139 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2140 (V_attachState(vp) != VOL_STATE_DELETED) &&
2141 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2142 !VIsErrorState(V_attachState(vp))) {
2144 * pre-attach is a no-op in all but the following cases:
2146 * - volume is unattached
2147 * - volume is in an error state
2148 * - volume is pre-attached
2150 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2153 /* we're re-attaching a volume; clear out some old state */
2154 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2156 if (V_partition(vp) != partp) {
2157 /* XXX potential race */
2158 DeleteVolumeFromVByPList_r(vp);
2161 /* if we need to allocate a new Volume struct,
2162 * go ahead and drop the vol glock, otherwise
2163 * do the basic setup synchronised, as it's
2164 * probably not worth dropping the lock */
2167 /* allocate the volume structure */
2168 vp = nvp = (Volume *) malloc(sizeof(Volume));
2169 osi_Assert(vp != NULL);
2170 memset(vp, 0, sizeof(Volume));
2171 queue_Init(&vp->vnode_list);
2172 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2175 /* link the volume with its associated vice partition */
2176 vp->device = partp->device;
2177 vp->partition = partp;
2180 vp->specialStatus = 0;
2182 /* if we dropped the lock, reacquire the lock,
2183 * check for pre-attach races, and then add
2184 * the volume to the hash table */
2187 nvp = VLookupVolume_r(ec, vid, NULL);
2192 } else if (nvp) { /* race detected */
2197 /* hack to make up for VChangeState_r() decrementing
2198 * the old state counter */
2199 VStats.state_levels[0]++;
2203 /* put pre-attached volume onto the hash table
2204 * and bring it up to the pre-attached state */
2205 AddVolumeToHashTable(vp, vp->hashid);
2206 AddVolumeToVByPList_r(vp);
2207 VLRU_Init_Node_r(vp);
2208 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2211 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2219 #endif /* AFS_DEMAND_ATTACH_FS */
2221 /* Attach an existing volume, given its pathname, and return a
2222 pointer to the volume header information. The volume also
2223 normally goes online at this time. An offline volume
2224 must be reattached to make it go online */
2226 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2230 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2236 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2239 struct DiskPartition64 *partp;
2244 #ifdef AFS_DEMAND_ATTACH_FS
2245 VolumeStats stats_save;
2247 #endif /* AFS_DEMAND_ATTACH_FS */
2251 volumeId = VolumeNumber(name);
2253 if (!(partp = VGetPartition_r(partition, 0))) {
2255 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2259 if (VRequiresPartLock()) {
2260 osi_Assert(VInit == 3);
2261 VLockPartition_r(partition);
2262 } else if (programType == fileServer) {
2263 #ifdef AFS_DEMAND_ATTACH_FS
2264 /* lookup the volume in the hash table */
2265 vp = VLookupVolume_r(ec, volumeId, NULL);
2271 /* save any counters that are supposed to
2272 * be monotonically increasing over the
2273 * lifetime of the fileserver */
2274 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2276 memset(&stats_save, 0, sizeof(VolumeStats));
2279 /* if there's something in the hash table, and it's not
2280 * in the pre-attach state, then we may need to detach
2281 * it before proceeding */
2282 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2283 VCreateReservation_r(vp);
2284 VWaitExclusiveState_r(vp);
2286 /* at this point state must be one of:
2296 if (vp->specialStatus == VBUSY)
2299 /* if it's already attached, see if we can return it */
2300 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2301 VGetVolumeByVp_r(ec, vp);
2302 if (V_inUse(vp) == fileServer) {
2303 VCancelReservation_r(vp);
2307 /* otherwise, we need to detach, and attempt to re-attach */
2308 VDetachVolume_r(ec, vp);
2310 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2313 /* if it isn't fully attached, delete from the hash tables,
2314 and let the refcounter handle the rest */
2315 DeleteVolumeFromHashTable(vp);
2316 DeleteVolumeFromVByPList_r(vp);
2319 VCancelReservation_r(vp);
2323 /* pre-attach volume if it hasn't been done yet */
2325 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2326 (V_attachState(vp) == VOL_STATE_DELETED) ||
2327 (V_attachState(vp) == VOL_STATE_ERROR)) {
2329 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2335 osi_Assert(vp != NULL);
2337 /* handle pre-attach races
2339 * multiple threads can race to pre-attach a volume,
2340 * but we can't let them race beyond that
2342 * our solution is to let the first thread to bring
2343 * the volume into an exclusive state win; the other
2344 * threads just wait until it finishes bringing the
2345 * volume online, and then they do a vgetvolumebyvp
2347 if (svp && (svp != vp)) {
2348 /* wait for other exclusive ops to finish */
2349 VCreateReservation_r(vp);
2350 VWaitExclusiveState_r(vp);
2352 /* get a heavyweight ref, kill the lightweight ref, and return */
2353 VGetVolumeByVp_r(ec, vp);
2354 VCancelReservation_r(vp);
2358 /* at this point, we are chosen as the thread to do
2359 * demand attachment for this volume. all other threads
2360 * doing a getvolume on vp->hashid will block until we finish */
2362 /* make sure any old header cache entries are invalidated
2363 * before proceeding */
2364 FreeVolumeHeader(vp);
2366 VChangeState_r(vp, VOL_STATE_ATTACHING);
2368 /* restore any saved counters */
2369 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2370 #else /* AFS_DEMAND_ATTACH_FS */
2371 vp = VGetVolume_r(ec, volumeId);
2373 if (V_inUse(vp) == fileServer)
2375 if (vp->specialStatus == VBUSY)
2377 VDetachVolume_r(ec, vp);
2379 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2383 #endif /* AFS_DEMAND_ATTACH_FS */
2387 strcpy(path, VPartitionPath(partp));
2395 vp = (Volume *) calloc(1, sizeof(Volume));
2396 osi_Assert(vp != NULL);
2397 vp->hashid = volumeId;
2398 vp->device = partp->device;
2399 vp->partition = partp;
2400 queue_Init(&vp->vnode_list);
2401 #ifdef AFS_DEMAND_ATTACH_FS
2402 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2403 #endif /* AFS_DEMAND_ATTACH_FS */
2406 /* attach2 is entered without any locks, and returns
2407 * with vol_glock_mutex held */
2408 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2410 if (VCanUseFSSYNC() && vp) {
2411 #ifdef AFS_DEMAND_ATTACH_FS
2412 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2413 /* mark volume header as in use so that volser crashes lead to a
2414 * salvage attempt */
2415 VUpdateVolume_r(ec, vp, 0);
2417 /* for dafs, we should tell the fileserver, except for V_PEEK
2418 * where we know it is not necessary */
2419 if (mode == V_PEEK) {
2420 vp->needsPutBack = 0;
2422 vp->needsPutBack = VOL_PUTBACK;
2424 #else /* !AFS_DEMAND_ATTACH_FS */
2425 /* duplicate computation in fssync.c about whether the server
2426 * takes the volume offline or not. If the volume isn't
2427 * offline, we must not return it when we detach the volume,
2428 * or the server will abort */
2429 if (mode == V_READONLY || mode == V_PEEK
2430 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2431 vp->needsPutBack = 0;
2433 vp->needsPutBack = VOL_PUTBACK;
2434 #endif /* !AFS_DEMAND_ATTACH_FS */
2436 #ifdef FSSYNC_BUILD_CLIENT
2437 /* Only give back the vol to the fileserver if we checked it out; attach2
2438 * will set checkedOut only if we successfully checked it out from the
2440 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2442 #ifdef AFS_DEMAND_ATTACH_FS
2443 /* If we couldn't attach but we scheduled a salvage, we already
2444 * notified the fileserver; don't online it now */
2445 if (*ec != VSALVAGING)
2446 #endif /* AFS_DEMAND_ATTACH_FS */
2447 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2450 if (programType == fileServer && vp) {
2451 #ifdef AFS_DEMAND_ATTACH_FS
2453 * we can get here in cases where we don't "own"
2454 * the volume (e.g. volume owned by a utility).
2455 * short circuit around potential disk header races.
2457 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2461 VUpdateVolume_r(ec, vp, 0);
2463 Log("VAttachVolume: Error updating volume\n");
2468 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2469 #ifndef AFS_DEMAND_ATTACH_FS
2470 /* This is a hack: by temporarily setting the incore
2471 * dontSalvage flag ON, the volume will be put back on the
2472 * Update list (with dontSalvage OFF again). It will then
2473 * come back in N minutes with DONT_SALVAGE eventually
2474 * set. This is the way that volumes that have never had
2475 * it set get it set; or that volumes that have been
2476 * offline without DONT SALVAGE having been set also
2477 * eventually get it set */
2478 V_dontSalvage(vp) = DONT_SALVAGE;
2479 #endif /* !AFS_DEMAND_ATTACH_FS */
2480 VAddToVolumeUpdateList_r(ec, vp);
2482 Log("VAttachVolume: Error adding volume to update list\n");
2489 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2494 if (VRequiresPartLock()) {
2495 VUnlockPartition_r(partition);
2498 #ifdef AFS_DEMAND_ATTACH_FS
2499 /* attach failed; make sure we're in error state */
2500 if (vp && !VIsErrorState(V_attachState(vp))) {
2501 VChangeState_r(vp, VOL_STATE_ERROR);
2503 #endif /* AFS_DEMAND_ATTACH_FS */
2510 #ifdef AFS_DEMAND_ATTACH_FS
2511 /* VAttachVolumeByVp_r
2513 * finish attaching a volume that is
2514 * in a less than fully attached state
2516 /* caller MUST hold a ref count on vp */
2518 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2520 char name[VMAXPATHLEN];
2522 struct DiskPartition64 *partp;
2526 Volume * nvp = NULL;
2527 VolumeStats stats_save;
2531 /* volume utility should never call AttachByVp */
2532 osi_Assert(programType == fileServer);
2534 volumeId = vp->hashid;
2535 partp = vp->partition;
2536 VolumeExternalName_r(volumeId, name, sizeof(name));
2539 /* if another thread is performing a blocking op, wait */
2540 VWaitExclusiveState_r(vp);
2542 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2544 /* if it's already attached, see if we can return it */
2545 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2546 VGetVolumeByVp_r(ec, vp);
2547 if (V_inUse(vp) == fileServer) {
2550 if (vp->specialStatus == VBUSY)
2552 VDetachVolume_r(ec, vp);
2554 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2560 /* pre-attach volume if it hasn't been done yet */
2562 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2563 (V_attachState(vp) == VOL_STATE_DELETED) ||
2564 (V_attachState(vp) == VOL_STATE_ERROR)) {
2565 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2571 VCreateReservation_r(nvp);
2576 osi_Assert(vp != NULL);
2577 VChangeState_r(vp, VOL_STATE_ATTACHING);
2579 /* restore monotonically increasing stats */
2580 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2584 /* compute path to disk header */
2585 strcpy(path, VPartitionPath(partp));
2594 * NOTE: attach2 is entered without any locks, and returns
2595 * with vol_glock_mutex held */
2596 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2599 * the event that an error was encountered, or
2600 * the volume was not brought to an attached state
2601 * for any reason, skip to the end. We cannot
2602 * safely call VUpdateVolume unless we "own" it.
2606 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2610 VUpdateVolume_r(ec, vp, 0);
2612 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2616 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2617 #ifndef AFS_DEMAND_ATTACH_FS
2618 /* This is a hack: by temporarily setting the incore
2619 * dontSalvage flag ON, the volume will be put back on the
2620 * Update list (with dontSalvage OFF again). It will then
2621 * come back in N minutes with DONT_SALVAGE eventually
2622 * set. This is the way that volumes that have never had
2623 * it set get it set; or that volumes that have been
2624 * offline without DONT SALVAGE having been set also
2625 * eventually get it set */
2626 V_dontSalvage(vp) = DONT_SALVAGE;
2627 #endif /* !AFS_DEMAND_ATTACH_FS */
2628 VAddToVolumeUpdateList_r(ec, vp);
2630 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2637 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2641 VCancelReservation_r(nvp);
2644 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2645 if (vp && !VIsErrorState(V_attachState(vp))) {
2646 VChangeState_r(vp, VOL_STATE_ERROR);
2655 * lock a volume on disk (non-blocking).
2657 * @param[in] vp The volume to lock
2658 * @param[in] locktype READ_LOCK or WRITE_LOCK
2660 * @return operation status
2661 * @retval 0 success, lock was obtained
2662 * @retval EBUSY a conflicting lock was held by another process
2663 * @retval EIO error acquiring lock
2665 * @pre If we're in the fileserver, vp is in an exclusive state
2667 * @pre vp is not already locked
2670 VLockVolumeNB(Volume *vp, int locktype)
2674 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2675 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2677 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2679 V_attachFlags(vp) |= VOL_LOCKED;
2686 * unlock a volume on disk that was locked with VLockVolumeNB.
2688 * @param[in] vp volume to unlock
2690 * @pre If we're in the fileserver, vp is in an exclusive state
2692 * @pre vp has already been locked
2695 VUnlockVolume(Volume *vp)
2697 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2698 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2700 VUnlockVolumeById(vp->hashid, vp->partition);
2702 V_attachFlags(vp) &= ~VOL_LOCKED;
2704 #endif /* AFS_DEMAND_ATTACH_FS */
2707 * read in a vol header, possibly lock the vol header, and possibly check out
2708 * the vol header from the fileserver, as part of volume attachment.
2710 * @param[out] ec error code
2711 * @param[in] vp volume pointer object
2712 * @param[in] partp disk partition object of the attaching partition
2713 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2715 * @param[in] peek 1 to just try to read in the volume header and make sure
2716 * we don't try to lock the vol, or check it out from
2717 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2719 * @param[out] acheckedOut If we successfully checked-out the volume from
2720 * the fileserver (if we needed to), this is set
2721 * to 1, otherwise it is untouched.
2723 * @note As part of DAFS volume attachment, the volume header may be either
2724 * read- or write-locked to ensure mutual exclusion of certain volume
2725 * operations. In some cases in order to determine whether we need to
2726 * read- or write-lock the header, we need to read in the header to see
2727 * if the volume is RW or not. So, if we read in the header under a
2728 * read-lock and determine that we actually need a write-lock on the
2729 * volume header, this function will drop the read lock, acquire a write
2730 * lock, and read the header in again.
2733 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2734 int mode, int peek, int *acheckedOut)
2736 struct VolumeDiskHeader diskHeader;
2737 struct VolumeHeader header;
2740 int lock_tries = 0, checkout_tries = 0;
2742 VolumeId volid = vp->hashid;
2743 #ifdef FSSYNC_BUILD_CLIENT
2744 int checkout, done_checkout = 0;
2745 #endif /* FSSYNC_BUILD_CLIENT */
2746 #ifdef AFS_DEMAND_ATTACH_FS
2747 int locktype = 0, use_locktype = -1;
2748 #endif /* AFS_DEMAND_ATTACH_FS */
2754 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2755 Log("VAttachVolume: retried too many times trying to lock header for "
2756 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2757 VPartitionPath(partp));
2761 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2762 Log("VAttachVolume: retried too many times trying to checkout "
2763 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2764 VPartitionPath(partp));
2769 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2770 /* short-circuit the 'volume does not exist' case */
2775 #ifdef FSSYNC_BUILD_CLIENT
2776 checkout = !done_checkout;
2778 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2780 memset(&res, 0, sizeof(res));
2782 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2785 if (res.hdr.reason == FSYNC_SALVAGE) {
2786 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2787 afs_printable_uint32_lu(volid));
2790 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2791 afs_printable_uint32_lu(volid));
2792 *ec = VNOVOL; /* XXXX */
2800 #ifdef AFS_DEMAND_ATTACH_FS
2801 if (use_locktype < 0) {
2802 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2803 * if it turns out to be RW */
2804 locktype = VVolLockType(mode, 0);
2807 /* a previous try says we should use use_locktype to lock the volume,
2809 locktype = use_locktype;
2812 if (!peek && locktype) {
2813 code = VLockVolumeNB(vp, locktype);
2815 if (code == EBUSY) {
2816 Log("VAttachVolume: another program has vol %lu locked\n",
2817 afs_printable_uint32_lu(volid));
2819 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2820 code, afs_printable_uint32_lu(volid));
2827 #endif /* AFS_DEMAND_ATTACH_FS */
2829 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2839 DiskToVolumeHeader(&header, &diskHeader);
2841 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2842 header.largeVnodeIndex);
2843 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2844 header.smallVnodeIndex);
2845 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2847 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2850 /* only need to do this once */
2852 GetVolumeHeader(vp);
2856 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2857 /* demand attach changes the V_PEEK mechanism
2859 * we can now suck the current disk data structure over
2860 * the fssync interface without going to disk
2862 * (technically, we don't need to restrict this feature
2863 * to demand attach fileservers. However, I'm trying
2864 * to limit the number of common code changes)
2866 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2868 res.payload.len = sizeof(VolumeDiskData);
2869 res.payload.buf = &vp->header->diskstuff;
2871 if (FSYNC_VolOp(vp->hashid,
2873 FSYNC_VOL_QUERY_HDR,
2876 goto disk_header_loaded;
2879 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2880 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2881 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2883 #ifdef AFS_DEMAND_ATTACH_FS
2886 IncUInt64(&VStats.hdr_loads);
2887 IncUInt64(&vp->stats.hdr_loads);
2889 #endif /* AFS_DEMAND_ATTACH_FS */
2892 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2893 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2897 #ifdef AFS_DEMAND_ATTACH_FS
2898 # ifdef FSSYNC_BUILD_CLIENT
2900 # endif /* FSSYNC_BUILD_CLIENT */
2902 /* if the lock type we actually used to lock the volume is different than
2903 * the lock type we should have used, retry with the lock type we should
2905 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2906 if (locktype != use_locktype) {
2910 #endif /* AFS_DEMAND_ATTACH_FS */
2915 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2916 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2918 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2920 if (code == SYNC_DENIED) {
2921 /* must retry checkout; fileserver no longer thinks we have
2927 } else if (code != SYNC_OK) {
2931 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2934 /* either we are going to be called again for a second pass, or we
2935 * encountered an error; clean up in either case */
2937 #ifdef AFS_DEMAND_ATTACH_FS
2938 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2941 #endif /* AFS_DEMAND_ATTACH_FS */
2942 if (vp->linkHandle) {
2943 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2944 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2945 IH_RELEASE(vp->diskDataHandle);
2946 IH_RELEASE(vp->linkHandle);
2959 #ifdef AFS_DEMAND_ATTACH_FS
2961 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2962 Volume *vp, int *acheckedOut)
2966 if (vp->pending_vol_op) {
2970 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
2972 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
2974 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2975 } else if (code == 0) {
2976 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2979 /* we need the vol header to determine if the volume can be
2980 * left online for the vop, so... get the header */
2984 /* attach header with peek=1 to avoid checking out the volume
2985 * or locking it; we just want the header info, we're not
2986 * messing with the volume itself at all */
2987 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
2994 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2995 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2997 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3000 /* make sure we grab a new vol header and re-open stuff on
3001 * actual attachment; we can't keep the data we grabbed, since
3002 * it was not done under a lock and thus not safe */
3003 FreeVolumeHeader(vp);
3004 VReleaseVolumeHandles_r(vp);
3007 /* see if the pending volume op requires exclusive access */
3008 switch (vp->pending_vol_op->vol_op_state) {
3009 case FSSYNC_VolOpPending:
3010 /* this should never happen */
3011 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3014 case FSSYNC_VolOpRunningUnknown:
3015 /* this should never happen; we resolved 'unknown' above */
3016 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3019 case FSSYNC_VolOpRunningOffline:
3020 /* mark the volume down */
3022 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3024 /* do not set V_offlineMessage here; we don't have ownership of
3025 * the volume (and probably do not have the header loaded), so we
3026 * can't alter the disk header */
3028 /* check to see if we should set the specialStatus flag */
3029 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3030 vp->specialStatus = VBUSY;
3041 #endif /* AFS_DEMAND_ATTACH_FS */
3044 * volume attachment helper function.
3046 * @param[out] ec error code
3047 * @param[in] volumeId volume ID of the attaching volume
3048 * @param[in] path full path to the volume header .vol file
3049 * @param[in] partp disk partition object for the attaching partition
3050 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3051 * vp->vnode_list, and V_attachCV (for DAFS) should already
3053 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3054 * if there is a volume operation running for this volume
3055 * that should set the volume to VBUSY during its run. 0
3056 * otherwise. (see VVolOpSetVBusy_r)
3057 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3059 * @param[out] acheckedOut If we successfully checked-out the volume from
3060 * the fileserver (if we needed to), this is set
3061 * to 1, otherwise it is 0.
3063 * @return pointer to the semi-attached volume pointer
3064 * @retval NULL an error occurred (check value of *ec)
3065 * @retval vp volume successfully attaching
3067 * @pre no locks held
3069 * @post VOL_LOCK held
3072 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3073 Volume * vp, int isbusy, int mode, int *acheckedOut)
3075 /* have we read in the header successfully? */
3076 int read_header = 0;
3078 #ifdef AFS_DEMAND_ATTACH_FS
3079 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3083 /* in the case of an error, to what state should the volume be
3085 VolState error_state = VOL_STATE_ERROR;
3086 #endif /* AFS_DEMAND_ATTACH_FS */
3090 vp->vnodeIndex[vLarge].handle = NULL;
3091 vp->vnodeIndex[vSmall].handle = NULL;
3092 vp->diskDataHandle = NULL;
3093 vp->linkHandle = NULL;
3097 #ifdef AFS_DEMAND_ATTACH_FS
3098 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3100 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3103 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3104 #endif /* !AFS_DEMAND_ATTACH_FS */
3106 if (*ec == VNOVOL) {
3107 /* if the volume doesn't exist, skip straight to 'error' so we don't
3108 * request a salvage */
3109 goto unlocked_error;
3115 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3116 vp->shuttingDown = 0;
3117 vp->goingOffline = 0;
3119 #ifdef AFS_DEMAND_ATTACH_FS
3120 vp->stats.last_attach = FT_ApproxTime();
3121 vp->stats.attaches++;
3125 IncUInt64(&VStats.attaches);
3126 vp->cacheCheck = ++VolumeCacheCheck;
3127 /* just in case this ever rolls over */
3128 if (!vp->cacheCheck)
3129 vp->cacheCheck = ++VolumeCacheCheck;
3132 #ifdef AFS_DEMAND_ATTACH_FS
3133 V_attachFlags(vp) |= VOL_HDR_LOADED;
3134 vp->stats.last_hdr_load = vp->stats.last_attach;
3135 #endif /* AFS_DEMAND_ATTACH_FS */
3139 struct IndexFileHeader iHead;
3141 #if OPENAFS_VOL_STATS
3143 * We just read in the diskstuff part of the header. If the detailed
3144 * volume stats area has not yet been initialized, we should bzero the
3145 * area and mark it as initialized.
3147 if (!(V_stat_initialized(vp))) {
3148 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3149 V_stat_initialized(vp) = 1;
3151 #endif /* OPENAFS_VOL_STATS */
3153 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3154 (char *)&iHead, sizeof(iHead),
3155 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3158 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3163 struct IndexFileHeader iHead;
3165 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3166 (char *)&iHead, sizeof(iHead),
3167 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3170 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3174 #ifdef AFS_NAMEI_ENV
3176 struct versionStamp stamp;
3178 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3179 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3182 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3185 #endif /* AFS_NAMEI_ENV */
3187 #if defined(AFS_DEMAND_ATTACH_FS)
3188 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3190 if (!VCanScheduleSalvage()) {
3191 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3193 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3194 VOL_SALVAGE_NO_OFFLINE);
3199 /* volume operation in progress */
3200 goto unlocked_error;
3202 #else /* AFS_DEMAND_ATTACH_FS */
3204 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3205 goto unlocked_error;
3207 #endif /* AFS_DEMAND_ATTACH_FS */
3209 if (V_needsSalvaged(vp)) {
3210 if (vp->specialStatus)
3211 vp->specialStatus = 0;
3213 #if defined(AFS_DEMAND_ATTACH_FS)
3214 if (!VCanScheduleSalvage()) {
3215 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3217 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3218 VOL_SALVAGE_NO_OFFLINE);
3221 #else /* AFS_DEMAND_ATTACH_FS */
3223 #endif /* AFS_DEMAND_ATTACH_FS */
3229 vp->nextVnodeUnique = V_uniquifier(vp);
3231 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3232 if (!V_needsSalvaged(vp)) {
3233 V_needsSalvaged(vp) = 1;
3234 VUpdateVolume_r(ec, vp, 0);
3236 #if defined(AFS_DEMAND_ATTACH_FS)
3237 if (!VCanScheduleSalvage()) {
3238 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3240 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3241 VOL_SALVAGE_NO_OFFLINE);
3244 #else /* AFS_DEMAND_ATTACH_FS */
3245 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3247 #endif /* AFS_DEMAND_ATTACH_FS */
3252 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3253 /* Only check destroyMe if we are the fileserver, since the
3254 * volserver et al sometimes need to work with volumes with
3255 * destroyMe set. Examples are 'temporary' volumes the
3256 * volserver creates, and when we create a volume (destroyMe
3257 * is set on creation; sometimes a separate volserver
3258 * transaction is created to clear destroyMe).
3261 #if defined(AFS_DEMAND_ATTACH_FS)
3262 /* schedule a salvage so the volume goes away on disk */
3263 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3264 VOL_SALVAGE_NO_OFFLINE);
3265 VChangeState_r(vp, VOL_STATE_ERROR);
3268 #endif /* AFS_DEMAND_ATTACH_FS */
3269 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3274 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3275 #ifndef BITMAP_LATER
3276 if (programType == fileServer && VolumeWriteable(vp)) {
3278 for (i = 0; i < nVNODECLASSES; i++) {
3279 VGetBitmap_r(ec, vp, i);
3281 #ifdef AFS_DEMAND_ATTACH_FS
3282 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3283 VOL_SALVAGE_NO_OFFLINE);
3285 #endif /* AFS_DEMAND_ATTACH_FS */
3286 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3292 #endif /* BITMAP_LATER */
3294 if (VInit >= 2 && V_needsCallback(vp)) {
3295 if (V_BreakVolumeCallbacks) {
3296 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3297 afs_printable_uint32_lu(V_id(vp)));
3298 V_needsCallback(vp) = 0;
3300 (*V_BreakVolumeCallbacks) (V_id(vp));
3303 VUpdateVolume_r(ec, vp, 0);
3305 #ifdef FSSYNC_BUILD_CLIENT
3306 else if (VCanUseFSSYNC()) {
3307 afs_int32 fsync_code;
3309 V_needsCallback(vp) = 0;
3311 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3315 V_needsCallback(vp) = 1;
3316 Log("Error trying to tell the fileserver to break callbacks for "
3317 "changed volume %lu; error code %ld\n",
3318 afs_printable_uint32_lu(V_id(vp)),
3319 afs_printable_int32_ld(fsync_code));
3321 VUpdateVolume_r(ec, vp, 0);
3324 #endif /* FSSYNC_BUILD_CLIENT */
3327 Log("VAttachVolume: error %d clearing needsCallback on volume "
3328 "%lu; needs salvage\n", (int)*ec,
3329 afs_printable_uint32_lu(V_id(vp)));
3330 #ifdef AFS_DEMAND_ATTACH_FS
3331 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3332 VOL_SALVAGE_NO_OFFLINE);
3334 #else /* !AFS_DEMAND_ATTACH_FS */
3336 #endif /* !AFS_DEMAND_ATTACh_FS */
3341 if (programType == fileServer) {
3342 if (vp->specialStatus)
3343 vp->specialStatus = 0;
3344 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3345 V_inUse(vp) = fileServer;
3346 V_offlineMessage(vp)[0] = '\0';
3350 #ifdef AFS_DEMAND_ATTACH_FS
3351 /* Put the vol into PREATTACHED state, so if someone tries to
3352 * access it again, we try to attach, see that we're not blessed,
3353 * and give a VNOVOL error again. Putting it into UNATTACHED state
3354 * would result in a VOFFLINE error instead. */
3355 error_state = VOL_STATE_PREATTACHED;
3356 #endif /* AFS_DEMAND_ATTACH_FS */
3358 /* mimic e.g. GetVolume errors */
3359 if (!V_blessed(vp)) {
3360 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3361 FreeVolumeHeader(vp);
3362 } else if (!V_inService(vp)) {
3363 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3364 FreeVolumeHeader(vp);
3366 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3368 #ifdef AFS_DEMAND_ATTACH_FS
3369 error_state = VOL_STATE_ERROR;
3370 /* see if we can recover */
3371 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3374 #ifdef AFS_DEMAND_ATTACH_FS
3380 #ifdef AFS_DEMAND_ATTACH_FS
3381 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3382 V_inUse(vp) = programType;
3383 #endif /* AFS_DEMAND_ATTACH_FS */
3384 V_checkoutMode(vp) = mode;
3387 AddVolumeToHashTable(vp, V_id(vp));
3388 #ifdef AFS_DEMAND_ATTACH_FS
3389 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3392 if ((programType != fileServer) ||
3393 (V_inUse(vp) == fileServer)) {
3394 AddVolumeToVByPList_r(vp);
3396 VChangeState_r(vp, VOL_STATE_ATTACHED);
3398 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3407 #ifdef AFS_DEMAND_ATTACH_FS
3408 if (!VIsErrorState(V_attachState(vp))) {
3409 VChangeState_r(vp, error_state);
3411 #endif /* AFS_DEMAND_ATTACH_FS */
3414 VReleaseVolumeHandles_r(vp);
3417 #ifdef AFS_DEMAND_ATTACH_FS
3424 #else /* !AFS_DEMAND_ATTACH_FS */
3426 #endif /* !AFS_DEMAND_ATTACH_FS */
3430 /* Attach an existing volume.
3431 The volume also normally goes online at this time.
3432 An offline volume must be reattached to make it go online.
3436 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3440 retVal = VAttachVolume_r(ec, volumeId, mode);
3446 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3449 VGetVolumePath(ec, volumeId, &part, &name);
3453 vp = VGetVolume_r(&error, volumeId);
3455 osi_Assert(V_inUse(vp) == 0);
3456 VDetachVolume_r(ec, vp);
3460 return VAttachVolumeByName_r(ec, part, name, mode);
3463 /* Increment a reference count to a volume, sans context swaps. Requires
3464 * possibly reading the volume header in from the disk, since there's
3465 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3467 * N.B. This call can fail if we can't read in the header!! In this case
3468 * we still guarantee we won't context swap, but the ref count won't be
3469 * incremented (otherwise we'd violate the invariant).
3471 /* NOTE: with the demand attach fileserver extensions, the global lock
3472 * is dropped within VHold */
3473 #ifdef AFS_DEMAND_ATTACH_FS
3475 VHold_r(Volume * vp)
3479 VCreateReservation_r(vp);
3480 VWaitExclusiveState_r(vp);
3482 LoadVolumeHeader(&error, vp);
3484 VCancelReservation_r(vp);
3488 VCancelReservation_r(vp);
3491 #else /* AFS_DEMAND_ATTACH_FS */
3493 VHold_r(Volume * vp)
3497 LoadVolumeHeader(&error, vp);
3503 #endif /* AFS_DEMAND_ATTACH_FS */
3505 /**** volume timeout-related stuff ****/
3507 #ifdef AFS_PTHREAD_ENV
3510 VTimedOut(const struct timespec *ts)
3515 if (ts->tv_sec == 0) {
3516 /* short-circuit; this will have always timed out */
3520 code = gettimeofday(&tv, NULL);
3522 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3523 /* assume no timeout; failure mode is we just wait longer than normal
3524 * instead of returning errors when we shouldn't */
3528 if (tv.tv_sec < ts->tv_sec ||
3529 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3537 #else /* AFS_PTHREAD_ENV */
3539 /* Waiting a certain amount of time for offlining volumes is not supported
3540 * for LWP due to a lack of primitives. So, we never time out */
3541 # define VTimedOut(x) (0)
3543 #endif /* !AFS_PTHREAD_ENV */
3551 retVal = VHold_r(vp);
3558 /***************************************************/
3559 /* get and put volume routines */
3560 /***************************************************/
3563 * put back a heavyweight reference to a volume object.
3565 * @param[in] vp volume object pointer
3567 * @pre VOL_LOCK held
3569 * @post heavyweight volume reference put back.
3570 * depending on state, volume may have been taken offline,
3571 * detached, salvaged, freed, etc.
3573 * @internal volume package internal use only
3576 VPutVolume_r(Volume * vp)
3578 osi_Assert(--vp->nUsers >= 0);
3579 if (vp->nUsers == 0) {
3581 ReleaseVolumeHeader(vp->header);
3582 #ifdef AFS_DEMAND_ATTACH_FS
3583 if (!VCheckDetach(vp)) {
3587 #else /* AFS_DEMAND_ATTACH_FS */
3589 #endif /* AFS_DEMAND_ATTACH_FS */
3594 VPutVolume(Volume * vp)
3602 /* Get a pointer to an attached volume. The pointer is returned regardless
3603 of whether or not the volume is in service or on/off line. An error
3604 code, however, is returned with an indication of the volume's status */
3606 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3610 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3615 /* same as VGetVolume, but if a volume is waiting to go offline, we only wait
3616 * until time ts. If we have waited longer than that, we return that it is
3617 * actually offline, instead of waiting for it to go offline */
3619 VGetVolumeTimed(Error * ec, Error * client_ec, VolId volumeId,
3620 const struct timespec *ts)
3624 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3630 VGetVolume_r(Error * ec, VolId volumeId)
3632 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3635 /* try to get a volume we've previously looked up */
3636 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3638 VGetVolumeByVp_r(Error * ec, Volume * vp)
3640 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3644 * private interface for getting a volume handle
3646 * @param[out] ec error code (0 if no error)
3647 * @param[out] client_ec wire error code to be given to clients
3648 * @param[in] volumeId ID of the volume we want
3649 * @param[in] hint optional hint for hash lookups, or NULL
3650 * @param[in] timeout absolute deadline for waiting for the volume to go
3651 * offline, if it is going offline. NULL to wait forever.
3653 * @return a volume handle for the specified volume
3654 * @retval NULL an error occurred, or the volume is in such a state that
3655 * we cannot load a header or return any volume struct
3657 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3659 * @note 'timeout' is only checked if the volume is actually going offline; so
3660 * if you pass timeout->tv_sec = 0, this will exhibit typical
3661 * nonblocking behavior.
3663 * @note for LWP builds, 'timeout' must be NULL
3666 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3667 const struct timespec *timeout)
3670 /* pull this profiling/debugging code out of regular builds */
3672 #define VGET_CTR_INC(x) x++
3673 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3674 0, V7 = 0, V8 = 0, V9 = 0;
3675 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3677 #define VGET_CTR_INC(x)
3679 #ifdef AFS_DEMAND_ATTACH_FS
3680 Volume *avp, * rvp = hint;
3684 * if VInit is zero, the volume package dynamic
3685 * data structures have not been initialized yet,
3686 * and we must immediately return an error
3692 *client_ec = VOFFLINE;
3697 #ifdef AFS_DEMAND_ATTACH_FS
3699 VCreateReservation_r(rvp);
3701 #endif /* AFS_DEMAND_ATTACH_FS */
3709 vp = VLookupVolume_r(ec, volumeId, vp);
3715 #ifdef AFS_DEMAND_ATTACH_FS
3716 if (rvp && (rvp != vp)) {
3717 /* break reservation on old vp */
3718 VCancelReservation_r(rvp);
3721 #endif /* AFS_DEMAND_ATTACH_FS */
3727 /* Until we have reached an initialization level of 2
3728 * we don't know whether this volume exists or not.
3729 * We can't sleep and retry later because before a volume
3730 * is attached, the caller tries to get it first. Just
3731 * return VOFFLINE and the caller can choose whether to
3732 * retry the command or not. */
3742 IncUInt64(&VStats.hdr_gets);
3744 #ifdef AFS_DEMAND_ATTACH_FS
3745 /* block if someone else is performing an exclusive op on this volume */
3748 VCreateReservation_r(rvp);
3750 VWaitExclusiveState_r(vp);
3752 /* short circuit with VNOVOL in the following circumstances:
3755 * - VOL_STATE_SHUTTING_DOWN
3757 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3758 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3759 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
3766 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
3767 * VNOVOL for VOL_STATE_DELETED
3769 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
3770 (V_attachState(vp) == VOL_STATE_DELETED)) {
3771 if (vp->specialStatus) {
3772 *ec = vp->specialStatus;
3773 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
3782 /* allowable states:
3789 if (vp->salvage.requested) {
3790 VUpdateSalvagePriority_r(vp);
3793 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
3794 avp = VAttachVolumeByVp_r(ec, vp, 0);
3797 /* VAttachVolumeByVp_r can return a pointer
3798 * != the vp passed to it under certain
3799 * conditions; make sure we don't leak
3800 * reservations if that happens */