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>
29 #ifdef HAVE_SYS_FILE_H
34 #include <afs/afsint.h>
37 #if !defined(AFS_SGI_ENV)
40 #else /* AFS_OSF_ENV */
41 #ifdef AFS_VFSINCL_ENV
44 #include <sys/fs/ufs_fs.h>
46 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
47 #include <ufs/ufs/dinode.h>
48 #include <ufs/ffs/fs.h>
53 #else /* AFS_VFSINCL_ENV */
54 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_ARM_DARWIN_ENV)
57 #endif /* AFS_VFSINCL_ENV */
58 #endif /* AFS_OSF_ENV */
59 #endif /* AFS_SGI_ENV */
60 #endif /* !AFS_NT40_ENV */
68 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
70 #include <sys/mnttab.h>
71 #include <sys/mntent.h>
77 #if defined(AFS_SGI_ENV)
80 #ifndef AFS_LINUX20_ENV
81 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
84 #endif /* AFS_SGI_ENV */
86 #endif /* AFS_HPUX_ENV */
90 #include <afs/errors.h>
93 #include <afs/afssyscalls.h>
95 #include <afs/afsutil.h>
96 #include "daemon_com.h"
101 #include "partition.h"
102 #include "volume_inline.h"
104 #include "afs/afs_assert.h"
108 #ifdef AFS_PTHREAD_ENV
109 pthread_mutex_t vol_glock_mutex;
110 pthread_mutex_t vol_trans_mutex;
111 pthread_cond_t vol_put_volume_cond;
112 pthread_cond_t vol_sleep_cond;
113 pthread_cond_t vol_init_attach_cond;
114 pthread_cond_t vol_vinit_cond;
115 int vol_attach_threads = 1;
116 #endif /* AFS_PTHREAD_ENV */
118 /* start-time configurable I/O parameters */
119 ih_init_params vol_io_params;
121 #ifdef AFS_DEMAND_ATTACH_FS
122 pthread_mutex_t vol_salvsync_mutex;
125 * Set this to 1 to disallow SALVSYNC communication in all threads; used
126 * during shutdown, since the salvageserver may have gone away.
128 static volatile sig_atomic_t vol_disallow_salvsync = 0;
129 #endif /* AFS_DEMAND_ATTACH_FS */
132 * has VShutdown_r been called / is VShutdown_r running?
134 static int vol_shutting_down = 0;
137 extern void *calloc(), *realloc();
140 /* Forward declarations */
141 static Volume *attach2(Error * ec, VolId volumeId, char *path,
142 struct DiskPartition64 *partp, Volume * vp,
143 int isbusy, int mode, int *acheckedOut);
144 static void ReallyFreeVolume(Volume * vp);
145 #ifdef AFS_DEMAND_ATTACH_FS
146 static void FreeVolume(Volume * vp);
147 #else /* !AFS_DEMAND_ATTACH_FS */
148 #define FreeVolume(vp) ReallyFreeVolume(vp)
149 static void VScanUpdateList(void);
150 #endif /* !AFS_DEMAND_ATTACH_FS */
151 static void VInitVolumeHeaderCache(afs_uint32 howMany);
152 static int GetVolumeHeader(Volume * vp);
153 static void ReleaseVolumeHeader(struct volHeader *hd);
154 static void FreeVolumeHeader(Volume * vp);
155 static void AddVolumeToHashTable(Volume * vp, int hashid);
156 static void DeleteVolumeFromHashTable(Volume * vp);
158 static int VHold(Volume * vp);
160 static int VHold_r(Volume * vp);
161 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
162 static void VReleaseVolumeHandles_r(Volume * vp);
163 static void VCloseVolumeHandles_r(Volume * vp);
164 static void LoadVolumeHeader(Error * ec, Volume * vp);
165 static int VCheckOffline(Volume * vp);
166 static int VCheckDetach(Volume * vp);
167 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
168 Volume * hint, const struct timespec *ts);
170 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
171 * defined when not linked with vice, XXXX */
172 ProgramType programType; /* The type of program using the package */
173 static VolumePackageOptions vol_opts;
175 /* extended volume package statistics */
178 #ifdef VOL_LOCK_DEBUG
179 pthread_t vol_glock_holder = 0;
183 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
184 /* Must be a multiple of 4 (1 word) !! */
186 /* this parameter needs to be tunable at runtime.
187 * 128 was really inadequate for largish servers -- at 16384 volumes this
188 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
189 * talk about bad spatial locality...
191 * an AVL or splay tree might work a lot better, but we'll just increase
192 * the default hash table size for now
194 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
195 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
196 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
199 * turn volume hash chains into partially ordered lists.
200 * when the threshold is exceeded between two adjacent elements,
201 * perform a chain rebalancing operation.
203 * keep the threshold high in order to keep cache line invalidates
204 * low "enough" on SMPs
206 #define VOLUME_HASH_REORDER_THRESHOLD 200
209 * when possible, don't just reorder single elements, but reorder
210 * entire chains of elements at once. a chain of elements that
211 * exceed the element previous to the pivot by at least CHAIN_THRESH
212 * accesses are moved in front of the chain whose elements have at
213 * least CHAIN_THRESH less accesses than the pivot element
215 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
217 #include "rx/rx_queue.h"
220 VolumeHashTable_t VolumeHashTable = {
221 DEFAULT_VOLUME_HASH_SIZE,
222 DEFAULT_VOLUME_HASH_MASK,
227 static void VInitVolumeHash(void);
231 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
235 afs_int32 ffs_tmp = x;
239 for (ffs_i = 1;; ffs_i++) {
246 #endif /* !AFS_HAVE_FFS */
248 #ifdef AFS_PTHREAD_ENV
250 * disk partition queue element
252 typedef struct diskpartition_queue_t {
253 struct rx_queue queue; /**< queue header */
254 struct DiskPartition64 *diskP; /**< disk partition table entry */
255 } diskpartition_queue_t;
257 #ifndef AFS_DEMAND_ATTACH_FS
259 typedef struct vinitvolumepackage_thread_t {
260 struct rx_queue queue;
261 pthread_cond_t thread_done_cv;
262 int n_threads_complete;
263 } vinitvolumepackage_thread_t;
264 static void * VInitVolumePackageThread(void * args);
266 #else /* !AFS_DEMAND_ATTTACH_FS */
267 #define VINIT_BATCH_MAX_SIZE 512
270 * disk partition work queue
272 struct partition_queue {
273 struct rx_queue head; /**< diskpartition_queue_t queue */
274 pthread_mutex_t mutex;
279 * volumes parameters for preattach
281 struct volume_init_batch {
282 struct rx_queue queue; /**< queue header */
283 int thread; /**< posting worker thread */
284 int last; /**< indicates thread is done */
285 int size; /**< number of volume ids in batch */
286 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
290 * volume parameters work queue
292 struct volume_init_queue {
293 struct rx_queue head; /**< volume_init_batch queue */
294 pthread_mutex_t mutex;
299 * volume init worker thread parameters
301 struct vinitvolumepackage_thread_param {
302 int nthreads; /**< total number of worker threads */
303 int thread; /**< thread number for this worker thread */
304 struct partition_queue *pq; /**< queue partitions to scan */
305 struct volume_init_queue *vq; /**< queue of volume to preattach */
308 static void *VInitVolumePackageThread(void *args);
309 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
310 static VolId VInitNextVolumeId(DIR *dirp);
311 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
313 #endif /* !AFS_DEMAND_ATTACH_FS */
314 #endif /* AFS_PTHREAD_ENV */
316 #ifndef AFS_DEMAND_ATTACH_FS
317 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
318 int * nAttached, int * nUnattached);
319 #endif /* AFS_DEMAND_ATTACH_FS */
322 #ifdef AFS_DEMAND_ATTACH_FS
323 /* demand attach fileserver extensions */
326 * in the future we will support serialization of VLRU state into the fs_state
329 * these structures are the beginning of that effort
331 struct VLRU_DiskHeader {
332 struct versionStamp stamp; /* magic and structure version number */
333 afs_uint32 mtime; /* time of dump to disk */
334 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
337 struct VLRU_DiskEntry {
338 afs_uint32 vid; /* volume ID */
339 afs_uint32 idx; /* generation */
340 afs_uint32 last_get; /* timestamp of last get */
343 struct VLRU_StartupQueue {
344 struct VLRU_DiskEntry * entry;
349 typedef struct vshutdown_thread_t {
351 pthread_mutex_t lock;
353 pthread_cond_t master_cv;
355 int n_threads_complete;
357 int schedule_version;
360 byte n_parts_done_pass;
361 byte part_thread_target[VOLMAXPARTS+1];
362 byte part_done_pass[VOLMAXPARTS+1];
363 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
364 int stats[4][VOLMAXPARTS+1];
365 } vshutdown_thread_t;
366 static void * VShutdownThread(void * args);
369 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
370 static int VCheckFree(Volume * vp);
373 static void AddVolumeToVByPList_r(Volume * vp);
374 static void DeleteVolumeFromVByPList_r(Volume * vp);
375 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
376 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
377 static void VVByPListWait_r(struct DiskPartition64 * dp);
379 /* online salvager */
380 static int VCheckSalvage(Volume * vp);
381 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
382 static int VScheduleSalvage_r(Volume * vp);
385 /* Volume hash table */
386 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
387 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
388 static void VHashEndExclusive_r(VolumeHashChainHead * head);
389 static void VHashWait_r(VolumeHashChainHead * head);
392 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
393 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
394 struct rx_queue ** idx);
395 static void ShutdownController(vshutdown_thread_t * params);
396 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
399 static void VLRU_ComputeConstants(void);
400 static void VInitVLRU(void);
401 static void VLRU_Init_Node_r(Volume * vp);
402 static void VLRU_Add_r(Volume * vp);
403 static void VLRU_Delete_r(Volume * vp);
404 static void VLRU_UpdateAccess_r(Volume * vp);
405 static void * VLRU_ScannerThread(void * args);
406 static void VLRU_Scan_r(int idx);
407 static void VLRU_Promote_r(int idx);
408 static void VLRU_Demote_r(int idx);
409 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
412 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
413 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
414 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
417 pthread_key_t VThread_key;
418 VThreadOptions_t VThread_defaults = {
419 0 /**< allow salvsync */
421 #endif /* AFS_DEMAND_ATTACH_FS */
424 struct Lock vol_listLock; /* Lock obtained when listing volumes:
425 * prevents a volume from being missed
426 * if the volume is attached during a
430 /* Common message used when the volume goes off line */
431 char *VSalvageMessage =
432 "Files in this volume are currently unavailable; call operations";
434 int VInit; /* 0 - uninitialized,
435 * 1 - initialized but not all volumes have been attached,
436 * 2 - initialized and all volumes have been attached,
437 * 3 - initialized, all volumes have been attached, and
438 * VConnectFS() has completed. */
440 static int vinit_attach_abort = 0;
442 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
443 * used to stamp volume headers and in-core
444 * vnodes. When the volume goes on-line the
445 * vnode will be invalidated
446 * access only with VOL_LOCK held */
451 /***************************************************/
452 /* Startup routines */
453 /***************************************************/
455 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
456 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
457 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
461 * assign default values to a VolumePackageOptions struct.
463 * Always call this on a VolumePackageOptions struct first, then set any
464 * specific options you want, then call VInitVolumePackage2.
466 * @param[in] pt caller's program type
467 * @param[out] opts volume package options
470 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
472 opts->nLargeVnodes = opts->nSmallVnodes = 5;
475 opts->canScheduleSalvage = 0;
476 opts->canUseFSSYNC = 0;
477 opts->canUseSALVSYNC = 0;
479 opts->interrupt_rxcall = NULL;
480 opts->offline_timeout = -1;
481 opts->offline_shutdown_timeout = -1;
484 opts->unsafe_attach = 1;
485 #else /* !FAST_RESTART */
486 opts->unsafe_attach = 0;
487 #endif /* !FAST_RESTART */
491 opts->canScheduleSalvage = 1;
492 opts->canUseSALVSYNC = 1;
496 opts->canUseFSSYNC = 1;
500 opts->nLargeVnodes = 0;
501 opts->nSmallVnodes = 0;
503 opts->canScheduleSalvage = 1;
504 opts->canUseFSSYNC = 1;
514 * Set VInit to a certain value, and signal waiters.
516 * @param[in] value the value to set VInit to
521 VSetVInit_r(int value)
524 CV_BROADCAST(&vol_vinit_cond);
528 VLogOfflineTimeout(const char *type, afs_int32 timeout)
534 Log("VInitVolumePackage: Interrupting clients accessing %s "
535 "immediately\n", type);
537 Log("VInitVolumePackage: Interrupting clients accessing %s "
538 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
543 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
545 int errors = 0; /* Number of errors while finding vice partitions. */
550 #ifndef AFS_PTHREAD_ENV
551 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
552 Log("VInitVolumePackage: offline_timeout and/or "
553 "offline_shutdown_timeout was specified, but the volume package "
554 "does not support these for LWP builds\n");
558 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
559 VLogOfflineTimeout("volumes going offline during shutdown",
560 opts->offline_shutdown_timeout);
562 memset(&VStats, 0, sizeof(VStats));
563 VStats.hdr_cache_size = 200;
565 VInitPartitionPackage();
567 #ifdef AFS_DEMAND_ATTACH_FS
568 if (programType == fileServer) {
571 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
573 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
576 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
577 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
578 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
579 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
580 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
581 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
582 #ifndef AFS_PTHREAD_ENV
584 #endif /* AFS_PTHREAD_ENV */
585 Lock_Init(&vol_listLock);
587 srandom(time(0)); /* For VGetVolumeInfo */
589 #ifdef AFS_DEMAND_ATTACH_FS
590 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
591 #endif /* AFS_DEMAND_ATTACH_FS */
593 /* Ok, we have done enough initialization that fileserver can
594 * start accepting calls, even though the volumes may not be
595 * available just yet.
599 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
600 if (programType == salvageServer) {
603 #endif /* AFS_DEMAND_ATTACH_FS */
604 #ifdef FSSYNC_BUILD_SERVER
605 if (programType == fileServer) {
609 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
610 if (VCanUseSALVSYNC()) {
611 /* establish a connection to the salvager at this point */
612 osi_Assert(VConnectSALV() != 0);
614 #endif /* AFS_DEMAND_ATTACH_FS */
616 if (opts->volcache > VStats.hdr_cache_size)
617 VStats.hdr_cache_size = opts->volcache;
618 VInitVolumeHeaderCache(VStats.hdr_cache_size);
620 VInitVnodes(vLarge, opts->nLargeVnodes);
621 VInitVnodes(vSmall, opts->nSmallVnodes);
624 errors = VAttachPartitions();
628 if (programType != fileServer) {
629 errors = VInitAttachVolumes(programType);
635 #ifdef FSSYNC_BUILD_CLIENT
636 if (VCanUseFSSYNC()) {
638 #ifdef AFS_DEMAND_ATTACH_FS
639 if (programType == salvageServer) {
640 Log("Unable to connect to file server; aborted\n");
643 #endif /* AFS_DEMAND_ATTACH_FS */
644 Log("Unable to connect to file server; will retry at need\n");
647 #endif /* FSSYNC_BUILD_CLIENT */
652 #if !defined(AFS_PTHREAD_ENV)
654 * Attach volumes in vice partitions
656 * @param[in] pt calling program type
659 * @note This is the original, non-threaded version of attach parititions.
661 * @post VInit state is 2
664 VInitAttachVolumes(ProgramType pt)
666 osi_Assert(VInit==1);
667 if (pt == fileServer) {
668 struct DiskPartition64 *diskP;
669 /* Attach all the volumes in this partition */
670 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
671 int nAttached = 0, nUnattached = 0;
672 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
676 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
677 LWP_NoYieldSignal(VInitAttachVolumes);
681 #endif /* !AFS_PTHREAD_ENV */
683 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
685 * Attach volumes in vice partitions
687 * @param[in] pt calling program type
690 * @note Threaded version of attach parititions.
692 * @post VInit state is 2
695 VInitAttachVolumes(ProgramType pt)
697 osi_Assert(VInit==1);
698 if (pt == fileServer) {
699 struct DiskPartition64 *diskP;
700 struct vinitvolumepackage_thread_t params;
701 struct diskpartition_queue_t * dpq;
702 int i, threads, parts;
704 pthread_attr_t attrs;
706 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
708 params.n_threads_complete = 0;
710 /* create partition work queue */
711 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
712 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
713 osi_Assert(dpq != NULL);
715 queue_Append(¶ms,dpq);
718 threads = MIN(parts, vol_attach_threads);
721 /* spawn off a bunch of initialization threads */
722 osi_Assert(pthread_attr_init(&attrs) == 0);
723 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
725 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
726 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
730 for (i=0; i < threads; i++) {
733 osi_Assert(pthread_create
734 (&tid, &attrs, &VInitVolumePackageThread,
736 AFS_SIGSET_RESTORE();
739 while(params.n_threads_complete < threads) {
740 VOL_CV_WAIT(¶ms.thread_done_cv);
744 osi_Assert(pthread_attr_destroy(&attrs) == 0);
746 /* if we're only going to run one init thread, don't bother creating
748 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
749 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
752 VInitVolumePackageThread(¶ms);
755 CV_DESTROY(¶ms.thread_done_cv);
758 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
759 CV_BROADCAST(&vol_init_attach_cond);
765 VInitVolumePackageThread(void * args) {
767 struct DiskPartition64 *diskP;
768 struct vinitvolumepackage_thread_t * params;
769 struct diskpartition_queue_t * dpq;
771 params = (vinitvolumepackage_thread_t *) args;
775 /* Attach all the volumes in this partition */
776 while (queue_IsNotEmpty(params)) {
777 int nAttached = 0, nUnattached = 0;
779 if (vinit_attach_abort) {
780 Log("Aborting initialization\n");
784 dpq = queue_First(params,diskpartition_queue_t);
790 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
796 params->n_threads_complete++;
797 CV_SIGNAL(¶ms->thread_done_cv);
801 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
803 #if defined(AFS_DEMAND_ATTACH_FS)
805 * Attach volumes in vice partitions
807 * @param[in] pt calling program type
810 * @note Threaded version of attach partitions.
812 * @post VInit state is 2
815 VInitAttachVolumes(ProgramType pt)
817 osi_Assert(VInit==1);
818 if (pt == fileServer) {
820 struct DiskPartition64 *diskP;
821 struct partition_queue pq;
822 struct volume_init_queue vq;
824 int i, threads, parts;
826 pthread_attr_t attrs;
828 /* create partition work queue */
830 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
831 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
832 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
833 struct diskpartition_queue_t *dp;
834 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
835 osi_Assert(dp != NULL);
837 queue_Append(&pq, dp);
840 /* number of worker threads; at least one, not to exceed the number of partitions */
841 threads = MIN(parts, vol_attach_threads);
843 /* create volume work queue */
845 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
846 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
848 osi_Assert(pthread_attr_init(&attrs) == 0);
849 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
851 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
852 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
855 /* create threads to scan disk partitions. */
856 for (i=0; i < threads; i++) {
857 struct vinitvolumepackage_thread_param *params;
860 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
864 params->nthreads = threads;
865 params->thread = i+1;
868 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
869 AFS_SIGSET_RESTORE();
872 VInitPreAttachVolumes(threads, &vq);
874 osi_Assert(pthread_attr_destroy(&attrs) == 0);
876 MUTEX_DESTROY(&pq.mutex);
878 MUTEX_DESTROY(&vq.mutex);
882 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
883 CV_BROADCAST(&vol_init_attach_cond);
890 * Volume package initialization worker thread. Scan partitions for volume
891 * header files. Gather batches of volume ids and dispatch them to
892 * the main thread to be preattached. The volume preattachement is done
893 * in the main thread to avoid global volume lock contention.
896 VInitVolumePackageThread(void *args)
898 struct vinitvolumepackage_thread_param *params;
899 struct DiskPartition64 *partition;
900 struct partition_queue *pq;
901 struct volume_init_queue *vq;
902 struct volume_init_batch *vb;
905 params = (struct vinitvolumepackage_thread_param *)args;
911 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
913 vb->thread = params->thread;
917 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
918 while((partition = VInitNextPartition(pq))) {
922 Log("Partition %s: pre-attaching volumes\n", partition->name);
923 dirp = opendir(VPartitionPath(partition));
925 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
928 while ((vid = VInitNextVolumeId(dirp))) {
929 Volume *vp = (Volume*)malloc(sizeof(Volume));
931 memset(vp, 0, sizeof(Volume));
932 vp->device = partition->device;
933 vp->partition = partition;
935 queue_Init(&vp->vnode_list);
936 queue_Init(&vp->rx_call_list);
937 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
939 vb->batch[vb->size++] = vp;
940 if (vb->size == VINIT_BATCH_MAX_SIZE) {
941 MUTEX_ENTER(&vq->mutex);
942 queue_Append(vq, vb);
943 CV_BROADCAST(&vq->cv);
944 MUTEX_EXIT(&vq->mutex);
946 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
948 vb->thread = params->thread;
957 MUTEX_ENTER(&vq->mutex);
958 queue_Append(vq, vb);
959 CV_BROADCAST(&vq->cv);
960 MUTEX_EXIT(&vq->mutex);
962 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
968 * Read next element from the pre-populated partition list.
970 static struct DiskPartition64*
971 VInitNextPartition(struct partition_queue *pq)
973 struct DiskPartition64 *partition;
974 struct diskpartition_queue_t *dp; /* queue element */
976 if (vinit_attach_abort) {
977 Log("Aborting volume preattach thread.\n");
981 /* get next partition to scan */
982 MUTEX_ENTER(&pq->mutex);
983 if (queue_IsEmpty(pq)) {
984 MUTEX_EXIT(&pq->mutex);
987 dp = queue_First(pq, diskpartition_queue_t);
989 MUTEX_EXIT(&pq->mutex);
992 osi_Assert(dp->diskP);
994 partition = dp->diskP;
1000 * Find next volume id on the partition.
1003 VInitNextVolumeId(DIR *dirp)
1009 while((d = readdir(dirp))) {
1010 if (vinit_attach_abort) {
1011 Log("Aborting volume preattach thread.\n");
1014 ext = strrchr(d->d_name, '.');
1015 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1016 vid = VolumeNumber(d->d_name);
1020 Log("Warning: bogus volume header file: %s\n", d->d_name);
1027 * Preattach volumes in batches to avoid lock contention.
1030 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1032 struct volume_init_batch *vb;
1036 /* dequeue next volume */
1037 MUTEX_ENTER(&vq->mutex);
1038 if (queue_IsEmpty(vq)) {
1039 CV_WAIT(&vq->cv, &vq->mutex);
1041 vb = queue_First(vq, volume_init_batch);
1043 MUTEX_EXIT(&vq->mutex);
1047 for (i = 0; i<vb->size; i++) {
1053 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1055 Log("Error looking up volume, code=%d\n", ec);
1058 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1061 /* put pre-attached volume onto the hash table
1062 * and bring it up to the pre-attached state */
1063 AddVolumeToHashTable(vp, vp->hashid);
1064 AddVolumeToVByPList_r(vp);
1065 VLRU_Init_Node_r(vp);
1066 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1079 #endif /* AFS_DEMAND_ATTACH_FS */
1081 #if !defined(AFS_DEMAND_ATTACH_FS)
1083 * attach all volumes on a given disk partition
1086 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1092 Log("Partition %s: attaching volumes\n", diskP->name);
1093 dirp = opendir(VPartitionPath(diskP));
1095 Log("opendir on Partition %s failed!\n", diskP->name);
1099 while ((dp = readdir(dirp))) {
1101 p = strrchr(dp->d_name, '.');
1103 if (vinit_attach_abort) {
1104 Log("Partition %s: abort attach volumes\n", diskP->name);
1108 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1111 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1113 (*(vp ? nAttached : nUnattached))++;
1114 if (error == VOFFLINE)
1115 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1116 else if (LogLevel >= 5) {
1117 Log("Partition %s: attached volume %d (%s)\n",
1118 diskP->name, VolumeNumber(dp->d_name),
1127 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1132 #endif /* !AFS_DEMAND_ATTACH_FS */
1134 /***************************************************/
1135 /* Shutdown routines */
1136 /***************************************************/
1140 * highly multithreaded volume package shutdown
1142 * with the demand attach fileserver extensions,
1143 * VShutdown has been modified to be multithreaded.
1144 * In order to achieve optimal use of many threads,
1145 * the shutdown code involves one control thread and
1146 * n shutdown worker threads. The control thread
1147 * periodically examines the number of volumes available
1148 * for shutdown on each partition, and produces a worker
1149 * thread allocation schedule. The idea is to eliminate
1150 * redundant scheduling computation on the workers by
1151 * having a single master scheduler.
1153 * The scheduler's objectives are:
1155 * each partition with volumes remaining gets allocated
1156 * at least 1 thread (assuming sufficient threads)
1158 * threads are allocated proportional to the number of
1159 * volumes remaining to be offlined. This ensures that
1160 * the OS I/O scheduler has many requests to elevator
1161 * seek on partitions that will (presumably) take the
1162 * longest amount of time (from now) to finish shutdown
1163 * (3) keep threads busy
1164 * when there are extra threads, they are assigned to
1165 * partitions using a simple round-robin algorithm
1167 * In the future, we may wish to add the ability to adapt
1168 * to the relative performance patterns of each disk
1173 * multi-step shutdown process
1175 * demand attach shutdown is a four-step process. Each
1176 * shutdown "pass" shuts down increasingly more difficult
1177 * volumes. The main purpose is to achieve better cache
1178 * utilization during shutdown.
1181 * shutdown volumes in the unattached, pre-attached
1184 * shutdown attached volumes with cached volume headers
1186 * shutdown all volumes in non-exclusive states
1188 * shutdown all remaining volumes
1191 #ifdef AFS_DEMAND_ATTACH_FS
1197 struct DiskPartition64 * diskP;
1198 struct diskpartition_queue_t * dpq;
1199 vshutdown_thread_t params;
1201 pthread_attr_t attrs;
1203 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1206 Log("VShutdown: aborting attach volumes\n");
1207 vinit_attach_abort = 1;
1208 VOL_CV_WAIT(&vol_init_attach_cond);
1211 for (params.n_parts=0, diskP = DiskPartitionList;
1212 diskP; diskP = diskP->next, params.n_parts++);
1214 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1215 params.n_parts, params.n_parts > 1 ? "s" : "");
1217 vol_shutting_down = 1;
1219 if (vol_attach_threads > 1) {
1220 /* prepare for parallel shutdown */
1221 params.n_threads = vol_attach_threads;
1222 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1223 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1224 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1225 osi_Assert(pthread_attr_init(&attrs) == 0);
1226 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1227 queue_Init(¶ms);
1229 /* setup the basic partition information structures for
1230 * parallel shutdown */
1231 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1233 struct rx_queue * qp, * nqp;
1237 VVByPListWait_r(diskP);
1238 VVByPListBeginExclusive_r(diskP);
1241 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1242 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1246 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1247 VPartitionPath(diskP), count);
1250 /* build up the pass 0 shutdown work queue */
1251 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1252 osi_Assert(dpq != NULL);
1254 queue_Prepend(¶ms, dpq);
1256 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1259 Log("VShutdown: beginning parallel fileserver shutdown\n");
1260 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1261 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1263 /* do pass 0 shutdown */
1264 MUTEX_ENTER(¶ms.lock);
1265 for (i=0; i < params.n_threads; i++) {
1266 osi_Assert(pthread_create
1267 (&tid, &attrs, &VShutdownThread,
1271 /* wait for all the pass 0 shutdowns to complete */
1272 while (params.n_threads_complete < params.n_threads) {
1273 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1275 params.n_threads_complete = 0;
1277 CV_BROADCAST(¶ms.cv);
1278 MUTEX_EXIT(¶ms.lock);
1280 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1281 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1283 /* run the parallel shutdown scheduler. it will drop the glock internally */
1284 ShutdownController(¶ms);
1286 /* wait for all the workers to finish pass 3 and terminate */
1287 while (params.pass < 4) {
1288 VOL_CV_WAIT(¶ms.cv);
1291 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1292 CV_DESTROY(¶ms.cv);
1293 CV_DESTROY(¶ms.master_cv);
1294 MUTEX_DESTROY(¶ms.lock);
1296 /* drop the VByPList exclusive reservations */
1297 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1298 VVByPListEndExclusive_r(diskP);
1299 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1300 VPartitionPath(diskP),
1301 params.stats[0][diskP->index],
1302 params.stats[1][diskP->index],
1303 params.stats[2][diskP->index],
1304 params.stats[3][diskP->index]);
1307 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1309 /* if we're only going to run one shutdown thread, don't bother creating
1311 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1313 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1314 VShutdownByPartition_r(diskP);
1318 Log("VShutdown: complete.\n");
1321 #else /* AFS_DEMAND_ATTACH_FS */
1331 Log("VShutdown: aborting attach volumes\n");
1332 vinit_attach_abort = 1;
1333 #ifdef AFS_PTHREAD_ENV
1334 VOL_CV_WAIT(&vol_init_attach_cond);
1336 LWP_WaitProcess(VInitAttachVolumes);
1337 #endif /* AFS_PTHREAD_ENV */
1340 Log("VShutdown: shutting down on-line volumes...\n");
1341 vol_shutting_down = 1;
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 queue_Init(&vp->rx_call_list);
2173 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2176 /* link the volume with its associated vice partition */
2177 vp->device = partp->device;
2178 vp->partition = partp;
2181 vp->specialStatus = 0;
2183 /* if we dropped the lock, reacquire the lock,
2184 * check for pre-attach races, and then add
2185 * the volume to the hash table */
2188 nvp = VLookupVolume_r(ec, vid, NULL);
2193 } else if (nvp) { /* race detected */
2198 /* hack to make up for VChangeState_r() decrementing
2199 * the old state counter */
2200 VStats.state_levels[0]++;
2204 /* put pre-attached volume onto the hash table
2205 * and bring it up to the pre-attached state */
2206 AddVolumeToHashTable(vp, vp->hashid);
2207 AddVolumeToVByPList_r(vp);
2208 VLRU_Init_Node_r(vp);
2209 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2212 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2220 #endif /* AFS_DEMAND_ATTACH_FS */
2222 /* Attach an existing volume, given its pathname, and return a
2223 pointer to the volume header information. The volume also
2224 normally goes online at this time. An offline volume
2225 must be reattached to make it go online */
2227 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2231 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2237 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2240 struct DiskPartition64 *partp;
2245 #ifdef AFS_DEMAND_ATTACH_FS
2246 VolumeStats stats_save;
2248 #endif /* AFS_DEMAND_ATTACH_FS */
2252 volumeId = VolumeNumber(name);
2254 if (!(partp = VGetPartition_r(partition, 0))) {
2256 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2260 if (VRequiresPartLock()) {
2261 osi_Assert(VInit == 3);
2262 VLockPartition_r(partition);
2263 } else if (programType == fileServer) {
2264 #ifdef AFS_DEMAND_ATTACH_FS
2265 /* lookup the volume in the hash table */
2266 vp = VLookupVolume_r(ec, volumeId, NULL);
2272 /* save any counters that are supposed to
2273 * be monotonically increasing over the
2274 * lifetime of the fileserver */
2275 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2277 memset(&stats_save, 0, sizeof(VolumeStats));
2280 /* if there's something in the hash table, and it's not
2281 * in the pre-attach state, then we may need to detach
2282 * it before proceeding */
2283 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2284 VCreateReservation_r(vp);
2285 VWaitExclusiveState_r(vp);
2287 /* at this point state must be one of:
2297 if (vp->specialStatus == VBUSY)
2300 /* if it's already attached, see if we can return it */
2301 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2302 VGetVolumeByVp_r(ec, vp);
2303 if (V_inUse(vp) == fileServer) {
2304 VCancelReservation_r(vp);
2308 /* otherwise, we need to detach, and attempt to re-attach */
2309 VDetachVolume_r(ec, vp);
2311 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2314 /* if it isn't fully attached, delete from the hash tables,
2315 and let the refcounter handle the rest */
2316 DeleteVolumeFromHashTable(vp);
2317 DeleteVolumeFromVByPList_r(vp);
2320 VCancelReservation_r(vp);
2324 /* pre-attach volume if it hasn't been done yet */
2326 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2327 (V_attachState(vp) == VOL_STATE_DELETED) ||
2328 (V_attachState(vp) == VOL_STATE_ERROR)) {
2330 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2336 osi_Assert(vp != NULL);
2338 /* handle pre-attach races
2340 * multiple threads can race to pre-attach a volume,
2341 * but we can't let them race beyond that
2343 * our solution is to let the first thread to bring
2344 * the volume into an exclusive state win; the other
2345 * threads just wait until it finishes bringing the
2346 * volume online, and then they do a vgetvolumebyvp
2348 if (svp && (svp != vp)) {
2349 /* wait for other exclusive ops to finish */
2350 VCreateReservation_r(vp);
2351 VWaitExclusiveState_r(vp);
2353 /* get a heavyweight ref, kill the lightweight ref, and return */
2354 VGetVolumeByVp_r(ec, vp);
2355 VCancelReservation_r(vp);
2359 /* at this point, we are chosen as the thread to do
2360 * demand attachment for this volume. all other threads
2361 * doing a getvolume on vp->hashid will block until we finish */
2363 /* make sure any old header cache entries are invalidated
2364 * before proceeding */
2365 FreeVolumeHeader(vp);
2367 VChangeState_r(vp, VOL_STATE_ATTACHING);
2369 /* restore any saved counters */
2370 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2371 #else /* AFS_DEMAND_ATTACH_FS */
2372 vp = VGetVolume_r(ec, volumeId);
2374 if (V_inUse(vp) == fileServer)
2376 if (vp->specialStatus == VBUSY)
2378 VDetachVolume_r(ec, vp);
2380 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2384 #endif /* AFS_DEMAND_ATTACH_FS */
2388 strcpy(path, VPartitionPath(partp));
2392 strcat(path, OS_DIRSEP);
2396 vp = (Volume *) calloc(1, sizeof(Volume));
2397 osi_Assert(vp != NULL);
2398 vp->hashid = volumeId;
2399 vp->device = partp->device;
2400 vp->partition = partp;
2401 queue_Init(&vp->vnode_list);
2402 queue_Init(&vp->rx_call_list);
2403 #ifdef AFS_DEMAND_ATTACH_FS
2404 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2405 #endif /* AFS_DEMAND_ATTACH_FS */
2408 /* attach2 is entered without any locks, and returns
2409 * with vol_glock_mutex held */
2410 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2412 if (VCanUseFSSYNC() && vp) {
2413 #ifdef AFS_DEMAND_ATTACH_FS
2414 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2415 /* mark volume header as in use so that volser crashes lead to a
2416 * salvage attempt */
2417 VUpdateVolume_r(ec, vp, 0);
2419 /* for dafs, we should tell the fileserver, except for V_PEEK
2420 * where we know it is not necessary */
2421 if (mode == V_PEEK) {
2422 vp->needsPutBack = 0;
2424 vp->needsPutBack = VOL_PUTBACK;
2426 #else /* !AFS_DEMAND_ATTACH_FS */
2427 /* duplicate computation in fssync.c about whether the server
2428 * takes the volume offline or not. If the volume isn't
2429 * offline, we must not return it when we detach the volume,
2430 * or the server will abort */
2431 if (mode == V_READONLY || mode == V_PEEK
2432 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2433 vp->needsPutBack = 0;
2435 vp->needsPutBack = VOL_PUTBACK;
2436 #endif /* !AFS_DEMAND_ATTACH_FS */
2438 #ifdef FSSYNC_BUILD_CLIENT
2439 /* Only give back the vol to the fileserver if we checked it out; attach2
2440 * will set checkedOut only if we successfully checked it out from the
2442 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2444 #ifdef AFS_DEMAND_ATTACH_FS
2445 /* If we couldn't attach but we scheduled a salvage, we already
2446 * notified the fileserver; don't online it now */
2447 if (*ec != VSALVAGING)
2448 #endif /* AFS_DEMAND_ATTACH_FS */
2449 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2452 if (programType == fileServer && vp) {
2453 #ifdef AFS_DEMAND_ATTACH_FS
2455 * we can get here in cases where we don't "own"
2456 * the volume (e.g. volume owned by a utility).
2457 * short circuit around potential disk header races.
2459 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2463 VUpdateVolume_r(ec, vp, 0);
2465 Log("VAttachVolume: Error updating volume\n");
2470 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2471 #ifndef AFS_DEMAND_ATTACH_FS
2472 /* This is a hack: by temporarily setting the incore
2473 * dontSalvage flag ON, the volume will be put back on the
2474 * Update list (with dontSalvage OFF again). It will then
2475 * come back in N minutes with DONT_SALVAGE eventually
2476 * set. This is the way that volumes that have never had
2477 * it set get it set; or that volumes that have been
2478 * offline without DONT SALVAGE having been set also
2479 * eventually get it set */
2480 V_dontSalvage(vp) = DONT_SALVAGE;
2481 #endif /* !AFS_DEMAND_ATTACH_FS */
2482 VAddToVolumeUpdateList_r(ec, vp);
2484 Log("VAttachVolume: Error adding volume to update list\n");
2491 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2496 if (VRequiresPartLock()) {
2497 VUnlockPartition_r(partition);
2500 #ifdef AFS_DEMAND_ATTACH_FS
2501 /* attach failed; make sure we're in error state */
2502 if (vp && !VIsErrorState(V_attachState(vp))) {
2503 VChangeState_r(vp, VOL_STATE_ERROR);
2505 #endif /* AFS_DEMAND_ATTACH_FS */
2512 #ifdef AFS_DEMAND_ATTACH_FS
2513 /* VAttachVolumeByVp_r
2515 * finish attaching a volume that is
2516 * in a less than fully attached state
2518 /* caller MUST hold a ref count on vp */
2520 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2522 char name[VMAXPATHLEN];
2524 struct DiskPartition64 *partp;
2528 Volume * nvp = NULL;
2529 VolumeStats stats_save;
2533 /* volume utility should never call AttachByVp */
2534 osi_Assert(programType == fileServer);
2536 volumeId = vp->hashid;
2537 partp = vp->partition;
2538 VolumeExternalName_r(volumeId, name, sizeof(name));
2541 /* if another thread is performing a blocking op, wait */
2542 VWaitExclusiveState_r(vp);
2544 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2546 /* if it's already attached, see if we can return it */
2547 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2548 VGetVolumeByVp_r(ec, vp);
2549 if (V_inUse(vp) == fileServer) {
2552 if (vp->specialStatus == VBUSY)
2554 VDetachVolume_r(ec, vp);
2556 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2562 /* pre-attach volume if it hasn't been done yet */
2564 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2565 (V_attachState(vp) == VOL_STATE_DELETED) ||
2566 (V_attachState(vp) == VOL_STATE_ERROR)) {
2567 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2573 VCreateReservation_r(nvp);
2578 osi_Assert(vp != NULL);
2579 VChangeState_r(vp, VOL_STATE_ATTACHING);
2581 /* restore monotonically increasing stats */
2582 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2586 /* compute path to disk header */
2587 strcpy(path, VPartitionPath(partp));
2591 strcat(path, OS_DIRSEP);
2596 * NOTE: attach2 is entered without any locks, and returns
2597 * with vol_glock_mutex held */
2598 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2601 * the event that an error was encountered, or
2602 * the volume was not brought to an attached state
2603 * for any reason, skip to the end. We cannot
2604 * safely call VUpdateVolume unless we "own" it.
2608 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2612 VUpdateVolume_r(ec, vp, 0);
2614 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2618 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2619 #ifndef AFS_DEMAND_ATTACH_FS
2620 /* This is a hack: by temporarily setting the incore
2621 * dontSalvage flag ON, the volume will be put back on the
2622 * Update list (with dontSalvage OFF again). It will then
2623 * come back in N minutes with DONT_SALVAGE eventually
2624 * set. This is the way that volumes that have never had
2625 * it set get it set; or that volumes that have been
2626 * offline without DONT SALVAGE having been set also
2627 * eventually get it set */
2628 V_dontSalvage(vp) = DONT_SALVAGE;
2629 #endif /* !AFS_DEMAND_ATTACH_FS */
2630 VAddToVolumeUpdateList_r(ec, vp);
2632 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2639 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2643 VCancelReservation_r(nvp);
2646 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2647 if (vp && !VIsErrorState(V_attachState(vp))) {
2648 VChangeState_r(vp, VOL_STATE_ERROR);
2657 * lock a volume on disk (non-blocking).
2659 * @param[in] vp The volume to lock
2660 * @param[in] locktype READ_LOCK or WRITE_LOCK
2662 * @return operation status
2663 * @retval 0 success, lock was obtained
2664 * @retval EBUSY a conflicting lock was held by another process
2665 * @retval EIO error acquiring lock
2667 * @pre If we're in the fileserver, vp is in an exclusive state
2669 * @pre vp is not already locked
2672 VLockVolumeNB(Volume *vp, int locktype)
2676 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2677 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2679 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2681 V_attachFlags(vp) |= VOL_LOCKED;
2688 * unlock a volume on disk that was locked with VLockVolumeNB.
2690 * @param[in] vp volume to unlock
2692 * @pre If we're in the fileserver, vp is in an exclusive state
2694 * @pre vp has already been locked
2697 VUnlockVolume(Volume *vp)
2699 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2700 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2702 VUnlockVolumeById(vp->hashid, vp->partition);
2704 V_attachFlags(vp) &= ~VOL_LOCKED;
2706 #endif /* AFS_DEMAND_ATTACH_FS */
2709 * read in a vol header, possibly lock the vol header, and possibly check out
2710 * the vol header from the fileserver, as part of volume attachment.
2712 * @param[out] ec error code
2713 * @param[in] vp volume pointer object
2714 * @param[in] partp disk partition object of the attaching partition
2715 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2717 * @param[in] peek 1 to just try to read in the volume header and make sure
2718 * we don't try to lock the vol, or check it out from
2719 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2721 * @param[out] acheckedOut If we successfully checked-out the volume from
2722 * the fileserver (if we needed to), this is set
2723 * to 1, otherwise it is untouched.
2725 * @note As part of DAFS volume attachment, the volume header may be either
2726 * read- or write-locked to ensure mutual exclusion of certain volume
2727 * operations. In some cases in order to determine whether we need to
2728 * read- or write-lock the header, we need to read in the header to see
2729 * if the volume is RW or not. So, if we read in the header under a
2730 * read-lock and determine that we actually need a write-lock on the
2731 * volume header, this function will drop the read lock, acquire a write
2732 * lock, and read the header in again.
2735 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2736 int mode, int peek, int *acheckedOut)
2738 struct VolumeDiskHeader diskHeader;
2739 struct VolumeHeader header;
2742 int lock_tries = 0, checkout_tries = 0;
2744 VolumeId volid = vp->hashid;
2745 #ifdef FSSYNC_BUILD_CLIENT
2746 int checkout, done_checkout = 0;
2747 #endif /* FSSYNC_BUILD_CLIENT */
2748 #ifdef AFS_DEMAND_ATTACH_FS
2749 int locktype = 0, use_locktype = -1;
2750 #endif /* AFS_DEMAND_ATTACH_FS */
2756 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2757 Log("VAttachVolume: retried too many times trying to lock header for "
2758 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2759 VPartitionPath(partp));
2763 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2764 Log("VAttachVolume: retried too many times trying to checkout "
2765 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2766 VPartitionPath(partp));
2771 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2772 /* short-circuit the 'volume does not exist' case */
2777 #ifdef FSSYNC_BUILD_CLIENT
2778 checkout = !done_checkout;
2780 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2782 memset(&res, 0, sizeof(res));
2784 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2787 if (res.hdr.reason == FSYNC_SALVAGE) {
2788 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2789 afs_printable_uint32_lu(volid));
2792 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2793 afs_printable_uint32_lu(volid));
2794 *ec = VNOVOL; /* XXXX */
2802 #ifdef AFS_DEMAND_ATTACH_FS
2803 if (use_locktype < 0) {
2804 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2805 * if it turns out to be RW */
2806 locktype = VVolLockType(mode, 0);
2809 /* a previous try says we should use use_locktype to lock the volume,
2811 locktype = use_locktype;
2814 if (!peek && locktype) {
2815 code = VLockVolumeNB(vp, locktype);
2817 if (code == EBUSY) {
2818 Log("VAttachVolume: another program has vol %lu locked\n",
2819 afs_printable_uint32_lu(volid));
2821 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2822 code, afs_printable_uint32_lu(volid));
2829 #endif /* AFS_DEMAND_ATTACH_FS */
2831 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2841 DiskToVolumeHeader(&header, &diskHeader);
2843 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2844 header.largeVnodeIndex);
2845 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2846 header.smallVnodeIndex);
2847 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2849 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2852 /* only need to do this once */
2854 GetVolumeHeader(vp);
2858 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2859 /* demand attach changes the V_PEEK mechanism
2861 * we can now suck the current disk data structure over
2862 * the fssync interface without going to disk
2864 * (technically, we don't need to restrict this feature
2865 * to demand attach fileservers. However, I'm trying
2866 * to limit the number of common code changes)
2868 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2870 res.payload.len = sizeof(VolumeDiskData);
2871 res.payload.buf = &vp->header->diskstuff;
2873 if (FSYNC_VolOp(vp->hashid,
2875 FSYNC_VOL_QUERY_HDR,
2878 goto disk_header_loaded;
2881 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2882 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2883 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2885 #ifdef AFS_DEMAND_ATTACH_FS
2888 IncUInt64(&VStats.hdr_loads);
2889 IncUInt64(&vp->stats.hdr_loads);
2891 #endif /* AFS_DEMAND_ATTACH_FS */
2894 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2895 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2899 #ifdef AFS_DEMAND_ATTACH_FS
2900 # ifdef FSSYNC_BUILD_CLIENT
2902 # endif /* FSSYNC_BUILD_CLIENT */
2904 /* if the lock type we actually used to lock the volume is different than
2905 * the lock type we should have used, retry with the lock type we should
2907 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2908 if (locktype != use_locktype) {
2912 #endif /* AFS_DEMAND_ATTACH_FS */
2917 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2918 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2920 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2922 if (code == SYNC_DENIED) {
2923 /* must retry checkout; fileserver no longer thinks we have
2929 } else if (code != SYNC_OK) {
2933 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2936 /* either we are going to be called again for a second pass, or we
2937 * encountered an error; clean up in either case */
2939 #ifdef AFS_DEMAND_ATTACH_FS
2940 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2943 #endif /* AFS_DEMAND_ATTACH_FS */
2944 if (vp->linkHandle) {
2945 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2946 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2947 IH_RELEASE(vp->diskDataHandle);
2948 IH_RELEASE(vp->linkHandle);
2961 #ifdef AFS_DEMAND_ATTACH_FS
2963 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2964 Volume *vp, int *acheckedOut)
2968 if (vp->pending_vol_op) {
2972 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
2974 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
2976 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2977 } else if (code == 0) {
2978 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2981 /* we need the vol header to determine if the volume can be
2982 * left online for the vop, so... get the header */
2986 /* attach header with peek=1 to avoid checking out the volume
2987 * or locking it; we just want the header info, we're not
2988 * messing with the volume itself at all */
2989 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
2996 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2997 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2999 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3002 /* make sure we grab a new vol header and re-open stuff on
3003 * actual attachment; we can't keep the data we grabbed, since
3004 * it was not done under a lock and thus not safe */
3005 FreeVolumeHeader(vp);
3006 VReleaseVolumeHandles_r(vp);
3009 /* see if the pending volume op requires exclusive access */
3010 switch (vp->pending_vol_op->vol_op_state) {
3011 case FSSYNC_VolOpPending:
3012 /* this should never happen */
3013 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3016 case FSSYNC_VolOpRunningUnknown:
3017 /* this should never happen; we resolved 'unknown' above */
3018 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3021 case FSSYNC_VolOpRunningOffline:
3022 /* mark the volume down */
3024 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3026 /* do not set V_offlineMessage here; we don't have ownership of
3027 * the volume (and probably do not have the header loaded), so we
3028 * can't alter the disk header */
3030 /* check to see if we should set the specialStatus flag */
3031 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3032 vp->specialStatus = VBUSY;
3043 #endif /* AFS_DEMAND_ATTACH_FS */
3046 * volume attachment helper function.
3048 * @param[out] ec error code
3049 * @param[in] volumeId volume ID of the attaching volume
3050 * @param[in] path full path to the volume header .vol file
3051 * @param[in] partp disk partition object for the attaching partition
3052 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3053 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3054 * DAFS) should already be initialized
3055 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3056 * if there is a volume operation running for this volume
3057 * that should set the volume to VBUSY during its run. 0
3058 * otherwise. (see VVolOpSetVBusy_r)
3059 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3061 * @param[out] acheckedOut If we successfully checked-out the volume from
3062 * the fileserver (if we needed to), this is set
3063 * to 1, otherwise it is 0.
3065 * @return pointer to the semi-attached volume pointer
3066 * @retval NULL an error occurred (check value of *ec)
3067 * @retval vp volume successfully attaching
3069 * @pre no locks held
3071 * @post VOL_LOCK held
3074 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3075 Volume * vp, int isbusy, int mode, int *acheckedOut)
3077 /* have we read in the header successfully? */
3078 int read_header = 0;
3080 #ifdef AFS_DEMAND_ATTACH_FS
3081 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3085 /* in the case of an error, to what state should the volume be
3087 VolState error_state = VOL_STATE_ERROR;
3088 #endif /* AFS_DEMAND_ATTACH_FS */
3092 vp->vnodeIndex[vLarge].handle = NULL;
3093 vp->vnodeIndex[vSmall].handle = NULL;
3094 vp->diskDataHandle = NULL;
3095 vp->linkHandle = NULL;
3099 #ifdef AFS_DEMAND_ATTACH_FS
3100 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3102 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3105 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3106 #endif /* !AFS_DEMAND_ATTACH_FS */
3108 if (*ec == VNOVOL) {
3109 /* if the volume doesn't exist, skip straight to 'error' so we don't
3110 * request a salvage */
3111 goto unlocked_error;
3117 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3118 vp->shuttingDown = 0;
3119 vp->goingOffline = 0;
3121 #ifdef AFS_DEMAND_ATTACH_FS
3122 vp->stats.last_attach = FT_ApproxTime();
3123 vp->stats.attaches++;
3127 IncUInt64(&VStats.attaches);
3128 vp->cacheCheck = ++VolumeCacheCheck;
3129 /* just in case this ever rolls over */
3130 if (!vp->cacheCheck)
3131 vp->cacheCheck = ++VolumeCacheCheck;
3134 #ifdef AFS_DEMAND_ATTACH_FS
3135 V_attachFlags(vp) |= VOL_HDR_LOADED;
3136 vp->stats.last_hdr_load = vp->stats.last_attach;
3137 #endif /* AFS_DEMAND_ATTACH_FS */
3141 struct IndexFileHeader iHead;
3143 #if OPENAFS_VOL_STATS
3145 * We just read in the diskstuff part of the header. If the detailed
3146 * volume stats area has not yet been initialized, we should bzero the
3147 * area and mark it as initialized.
3149 if (!(V_stat_initialized(vp))) {
3150 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3151 V_stat_initialized(vp) = 1;
3153 #endif /* OPENAFS_VOL_STATS */
3155 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3156 (char *)&iHead, sizeof(iHead),
3157 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3160 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3165 struct IndexFileHeader iHead;
3167 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3168 (char *)&iHead, sizeof(iHead),
3169 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3172 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3176 #ifdef AFS_NAMEI_ENV
3178 struct versionStamp stamp;
3180 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3181 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3184 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3187 #endif /* AFS_NAMEI_ENV */
3189 #if defined(AFS_DEMAND_ATTACH_FS)
3190 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3192 if (!VCanScheduleSalvage()) {
3193 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3195 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3196 VOL_SALVAGE_NO_OFFLINE);
3201 /* volume operation in progress */
3202 goto unlocked_error;
3204 #else /* AFS_DEMAND_ATTACH_FS */
3206 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3207 goto unlocked_error;
3209 #endif /* AFS_DEMAND_ATTACH_FS */
3211 if (V_needsSalvaged(vp)) {
3212 if (vp->specialStatus)
3213 vp->specialStatus = 0;
3215 #if defined(AFS_DEMAND_ATTACH_FS)
3216 if (!VCanScheduleSalvage()) {
3217 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3219 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3220 VOL_SALVAGE_NO_OFFLINE);
3223 #else /* AFS_DEMAND_ATTACH_FS */
3225 #endif /* AFS_DEMAND_ATTACH_FS */
3231 vp->nextVnodeUnique = V_uniquifier(vp);
3233 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3234 if (!V_needsSalvaged(vp)) {
3235 V_needsSalvaged(vp) = 1;
3236 VUpdateVolume_r(ec, vp, 0);
3238 #if defined(AFS_DEMAND_ATTACH_FS)
3239 if (!VCanScheduleSalvage()) {
3240 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3242 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3243 VOL_SALVAGE_NO_OFFLINE);
3246 #else /* AFS_DEMAND_ATTACH_FS */
3247 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3249 #endif /* AFS_DEMAND_ATTACH_FS */
3254 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3255 /* Only check destroyMe if we are the fileserver, since the
3256 * volserver et al sometimes need to work with volumes with
3257 * destroyMe set. Examples are 'temporary' volumes the
3258 * volserver creates, and when we create a volume (destroyMe
3259 * is set on creation; sometimes a separate volserver
3260 * transaction is created to clear destroyMe).
3263 #if defined(AFS_DEMAND_ATTACH_FS)
3264 /* schedule a salvage so the volume goes away on disk */
3265 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3266 VOL_SALVAGE_NO_OFFLINE);
3267 VChangeState_r(vp, VOL_STATE_ERROR);
3270 #endif /* AFS_DEMAND_ATTACH_FS */
3271 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3276 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3277 #ifndef BITMAP_LATER
3278 if (programType == fileServer && VolumeWriteable(vp)) {
3280 for (i = 0; i < nVNODECLASSES; i++) {
3281 VGetBitmap_r(ec, vp, i);
3283 #ifdef AFS_DEMAND_ATTACH_FS
3284 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3285 VOL_SALVAGE_NO_OFFLINE);
3287 #endif /* AFS_DEMAND_ATTACH_FS */
3288 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3294 #endif /* BITMAP_LATER */
3296 if (VInit >= 2 && V_needsCallback(vp)) {
3297 if (V_BreakVolumeCallbacks) {
3298 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3299 afs_printable_uint32_lu(V_id(vp)));
3300 V_needsCallback(vp) = 0;
3302 (*V_BreakVolumeCallbacks) (V_id(vp));
3305 VUpdateVolume_r(ec, vp, 0);
3307 #ifdef FSSYNC_BUILD_CLIENT
3308 else if (VCanUseFSSYNC()) {
3309 afs_int32 fsync_code;
3311 V_needsCallback(vp) = 0;
3313 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3317 V_needsCallback(vp) = 1;
3318 Log("Error trying to tell the fileserver to break callbacks for "
3319 "changed volume %lu; error code %ld\n",
3320 afs_printable_uint32_lu(V_id(vp)),
3321 afs_printable_int32_ld(fsync_code));
3323 VUpdateVolume_r(ec, vp, 0);
3326 #endif /* FSSYNC_BUILD_CLIENT */
3329 Log("VAttachVolume: error %d clearing needsCallback on volume "
3330 "%lu; needs salvage\n", (int)*ec,
3331 afs_printable_uint32_lu(V_id(vp)));
3332 #ifdef AFS_DEMAND_ATTACH_FS
3333 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3334 VOL_SALVAGE_NO_OFFLINE);
3336 #else /* !AFS_DEMAND_ATTACH_FS */
3338 #endif /* !AFS_DEMAND_ATTACh_FS */
3343 if (programType == fileServer) {
3344 if (vp->specialStatus)
3345 vp->specialStatus = 0;
3346 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3347 V_inUse(vp) = fileServer;
3348 V_offlineMessage(vp)[0] = '\0';
3352 #ifdef AFS_DEMAND_ATTACH_FS
3353 /* Put the vol into PREATTACHED state, so if someone tries to
3354 * access it again, we try to attach, see that we're not blessed,
3355 * and give a VNOVOL error again. Putting it into UNATTACHED state
3356 * would result in a VOFFLINE error instead. */
3357 error_state = VOL_STATE_PREATTACHED;
3358 #endif /* AFS_DEMAND_ATTACH_FS */
3360 /* mimic e.g. GetVolume errors */
3361 if (!V_blessed(vp)) {
3362 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3363 FreeVolumeHeader(vp);
3364 } else if (!V_inService(vp)) {
3365 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3366 FreeVolumeHeader(vp);
3368 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3370 #ifdef AFS_DEMAND_ATTACH_FS
3371 error_state = VOL_STATE_ERROR;
3372 /* see if we can recover */
3373 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3376 #ifdef AFS_DEMAND_ATTACH_FS
3382 #ifdef AFS_DEMAND_ATTACH_FS
3383 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3384 V_inUse(vp) = programType;
3385 #endif /* AFS_DEMAND_ATTACH_FS */
3386 V_checkoutMode(vp) = mode;
3389 AddVolumeToHashTable(vp, V_id(vp));
3390 #ifdef AFS_DEMAND_ATTACH_FS
3391 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3394 if ((programType != fileServer) ||
3395 (V_inUse(vp) == fileServer)) {
3396 AddVolumeToVByPList_r(vp);
3398 VChangeState_r(vp, VOL_STATE_ATTACHED);
3400 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3409 #ifdef AFS_DEMAND_ATTACH_FS
3410 if (!VIsErrorState(V_attachState(vp))) {
3411 VChangeState_r(vp, error_state);
3413 #endif /* AFS_DEMAND_ATTACH_FS */
3416 VReleaseVolumeHandles_r(vp);
3419 #ifdef AFS_DEMAND_ATTACH_FS
3426 #else /* !AFS_DEMAND_ATTACH_FS */
3428 #endif /* !AFS_DEMAND_ATTACH_FS */
3432 /* Attach an existing volume.
3433 The volume also normally goes online at this time.
3434 An offline volume must be reattached to make it go online.
3438 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3442 retVal = VAttachVolume_r(ec, volumeId, mode);
3448 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3451 VGetVolumePath(ec, volumeId, &part, &name);
3455 vp = VGetVolume_r(&error, volumeId);
3457 osi_Assert(V_inUse(vp) == 0);
3458 VDetachVolume_r(ec, vp);
3462 return VAttachVolumeByName_r(ec, part, name, mode);
3465 /* Increment a reference count to a volume, sans context swaps. Requires
3466 * possibly reading the volume header in from the disk, since there's
3467 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3469 * N.B. This call can fail if we can't read in the header!! In this case
3470 * we still guarantee we won't context swap, but the ref count won't be
3471 * incremented (otherwise we'd violate the invariant).
3473 /* NOTE: with the demand attach fileserver extensions, the global lock
3474 * is dropped within VHold */
3475 #ifdef AFS_DEMAND_ATTACH_FS
3477 VHold_r(Volume * vp)
3481 VCreateReservation_r(vp);
3482 VWaitExclusiveState_r(vp);
3484 LoadVolumeHeader(&error, vp);
3486 VCancelReservation_r(vp);
3490 VCancelReservation_r(vp);
3493 #else /* AFS_DEMAND_ATTACH_FS */
3495 VHold_r(Volume * vp)
3499 LoadVolumeHeader(&error, vp);
3505 #endif /* AFS_DEMAND_ATTACH_FS */
3507 /**** volume timeout-related stuff ****/
3509 #ifdef AFS_PTHREAD_ENV
3511 static struct timespec *shutdown_timeout;
3512 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3515 VTimedOut(const struct timespec *ts)
3520 if (ts->tv_sec == 0) {
3521 /* short-circuit; this will have always timed out */
3525 code = gettimeofday(&tv, NULL);
3527 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3528 /* assume no timeout; failure mode is we just wait longer than normal
3529 * instead of returning errors when we shouldn't */
3533 if (tv.tv_sec < ts->tv_sec ||
3534 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3543 * Calculate an absolute timeout.
3545 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3546 * NULL, the memory is not touched
3547 * @param[in] timeout How long the timeout should be from now
3549 * @return timeout to use
3550 * @retval NULL no timeout; wait forever
3551 * @retval non-NULL the given value for "ts"
3555 static struct timespec *
3556 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3566 ts->tv_sec = ts->tv_nsec = 0;
3570 code = gettimeofday(&now, NULL);
3572 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3576 ts->tv_sec = now.tv_sec + timeout;
3577 ts->tv_nsec = now.tv_usec * 1000;
3583 * Initialize the shutdown_timeout global.
3586 VShutdownTimeoutInit(void)
3588 struct timespec *ts;
3590 ts = malloc(sizeof(*ts));
3592 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3594 if (!shutdown_timeout) {
3600 * Figure out the timeout that should be used for waiting for offline volumes.
3602 * @param[out] ats Storage space for a local timeout value if needed
3604 * @return The timeout value that should be used
3605 * @retval NULL No timeout; wait forever for offlining volumes
3606 * @retval non-NULL A pointer to the absolute time that should be used as
3607 * the deadline for waiting for offlining volumes.
3609 * @note If we return non-NULL, the pointer we return may or may not be the
3612 static const struct timespec *
3613 VOfflineTimeout(struct timespec *ats)
3615 if (vol_shutting_down) {
3616 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3617 return shutdown_timeout;
3619 return VCalcTimeout(ats, vol_opts.offline_timeout);
3623 #else /* AFS_PTHREAD_ENV */
3625 /* Waiting a certain amount of time for offlining volumes is not supported
3626 * for LWP due to a lack of primitives. So, we never time out */
3627 # define VTimedOut(x) (0)
3628 # define VOfflineTimeout(x) (NULL)
3630 #endif /* !AFS_PTHREAD_ENV */
3638 retVal = VHold_r(vp);
3645 VIsGoingOffline_r(struct Volume *vp)
3649 if (vp->goingOffline) {
3650 if (vp->specialStatus) {
3651 code = vp->specialStatus;
3652 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3663 * Tell the caller if a volume is waiting to go offline.
3665 * @param[in] vp The volume we want to know about
3667 * @return volume status
3668 * @retval 0 volume is not waiting to go offline, go ahead and use it
3669 * @retval nonzero volume is waiting to offline, and give the returned code
3670 * as an error to anyone accessing the volume
3672 * @pre VOL_LOCK is NOT held
3673 * @pre caller holds a heavyweight reference on vp
3676 VIsGoingOffline(struct Volume *vp)
3681 code = VIsGoingOffline_r(vp);
3688 * Register an RX call with a volume.
3690 * @param[inout] ec Error code; if unset when passed in, may be set if
3691 * the volume starts going offline
3692 * @param[out] client_ec @see GetVolume
3693 * @param[in] vp Volume struct
3694 * @param[in] cbv VCallByVol struct containing the RX call to register
3696 * @pre VOL_LOCK held
3697 * @pre caller holds heavy ref on vp
3702 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3705 #ifdef AFS_DEMAND_ATTACH_FS
3707 /* just in case the volume started going offline after we got the
3708 * reference to it... otherwise, if the volume started going
3709 * offline right at the end of GetVolume(), we might race with the
3710 * RX call scanner, and return success and add our cbv to the
3711 * rx_call_list _after_ the scanner has scanned the list. */
3712 *ec = VIsGoingOffline_r(vp);
3718 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3719 VWaitStateChange_r(vp);
3721 #endif /* AFS_DEMAND_ATTACH_FS */
3723 queue_Prepend(&vp->rx_call_list, cbv);
3728 * Deregister an RX call with a volume.
3730 * @param[in] vp Volume struct
3731 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3733 * @pre VOL_LOCK held
3734 * @pre caller holds heavy ref on vp
3739 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3741 if (cbv && queue_IsOnQueue(cbv)) {
3742 #ifdef AFS_DEMAND_ATTACH_FS
3743 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3744 VWaitStateChange_r(vp);
3746 #endif /* AFS_DEMAND_ATTACH_FS */
3752 /***************************************************/
3753 /* get and put volume routines */
3754 /***************************************************/
3757 * put back a heavyweight reference to a volume object.
3759 * @param[in] vp volume object pointer
3761 * @pre VOL_LOCK held
3763 * @post heavyweight volume reference put back.
3764 * depending on state, volume may have been taken offline,
3765 * detached, salvaged, freed, etc.
3767 * @internal volume package internal use only
3770 VPutVolume_r(Volume * vp)
3772 osi_Assert(--vp->nUsers >= 0);
3773 if (vp->nUsers == 0) {
3775 ReleaseVolumeHeader(vp->header);
3776 #ifdef AFS_DEMAND_ATTACH_FS
3777 if (!VCheckDetach(vp)) {
3781 #else /* AFS_DEMAND_ATTACH_FS */
3783 #endif /* AFS_DEMAND_ATTACH_FS */
3788 VPutVolume(Volume * vp)
3796 * Puts a volume reference obtained with VGetVolumeWithCall.
3798 * @param[in] vp Volume struct
3799 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3801 * @pre VOL_LOCK is NOT held
3804 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3807 VDeregisterCall_r(vp, cbv);
3812 /* Get a pointer to an attached volume. The pointer is returned regardless
3813 of whether or not the volume is in service or on/off line. An error