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>
27 #include <afs/afsint.h>
31 #include <sys/param.h>
32 #if !defined(AFS_SGI_ENV)
35 #else /* AFS_OSF_ENV */
36 #ifdef AFS_VFSINCL_ENV
39 #include <sys/fs/ufs_fs.h>
41 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
42 #include <ufs/ufs/dinode.h>
43 #include <ufs/ffs/fs.h>
48 #else /* AFS_VFSINCL_ENV */
49 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_ARM_DARWIN_ENV)
52 #endif /* AFS_VFSINCL_ENV */
53 #endif /* AFS_OSF_ENV */
54 #endif /* AFS_SGI_ENV */
55 #endif /* AFS_NT40_ENV */
73 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
75 #include <sys/mnttab.h>
76 #include <sys/mntent.h>
82 #if defined(AFS_SGI_ENV)
87 #ifndef AFS_LINUX20_ENV
88 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
91 #endif /* AFS_SGI_ENV */
93 #endif /* AFS_HPUX_ENV */
97 #include <netinet/in.h>
101 #include <sys/time.h>
102 #endif /* ITIMER_REAL */
103 #endif /* AFS_NT40_ENV */
104 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
111 #include <afs/errors.h>
114 #include <afs/afssyscalls.h>
116 #include <afs/afsutil.h>
120 #include "daemon_com.h"
122 #include "salvsync.h"
125 #include "partition.h"
126 #include "volume_inline.h"
128 #include "afs/afs_assert.h"
135 #if !defined(offsetof)
140 #define afs_stat stat64
141 #define afs_fstat fstat64
142 #define afs_open open64
143 #else /* !O_LARGEFILE */
144 #define afs_stat stat
145 #define afs_fstat fstat
146 #define afs_open open
147 #endif /* !O_LARGEFILE */
149 #ifdef AFS_PTHREAD_ENV
150 pthread_mutex_t vol_glock_mutex;
151 pthread_mutex_t vol_trans_mutex;
152 pthread_cond_t vol_put_volume_cond;
153 pthread_cond_t vol_sleep_cond;
154 pthread_cond_t vol_init_attach_cond;
155 pthread_cond_t vol_vinit_cond;
156 int vol_attach_threads = 1;
157 #endif /* AFS_PTHREAD_ENV */
159 /* start-time configurable I/O parameters */
160 ih_init_params vol_io_params;
162 #ifdef AFS_DEMAND_ATTACH_FS
163 pthread_mutex_t vol_salvsync_mutex;
166 * Set this to 1 to disallow SALVSYNC communication in all threads; used
167 * during shutdown, since the salvageserver may have gone away.
169 static volatile sig_atomic_t vol_disallow_salvsync = 0;
170 #endif /* AFS_DEMAND_ATTACH_FS */
173 * has VShutdown_r been called / is VShutdown_r running?
175 static int vol_shutting_down = 0;
178 extern void *calloc(), *realloc();
181 /* Forward declarations */
182 static Volume *attach2(Error * ec, VolId volumeId, char *path,
183 struct DiskPartition64 *partp, Volume * vp,
184 int isbusy, int mode, int *acheckedOut);
185 static void ReallyFreeVolume(Volume * vp);
186 #ifdef AFS_DEMAND_ATTACH_FS
187 static void FreeVolume(Volume * vp);
188 #else /* !AFS_DEMAND_ATTACH_FS */
189 #define FreeVolume(vp) ReallyFreeVolume(vp)
190 static void VScanUpdateList(void);
191 #endif /* !AFS_DEMAND_ATTACH_FS */
192 static void VInitVolumeHeaderCache(afs_uint32 howMany);
193 static int GetVolumeHeader(Volume * vp);
194 static void ReleaseVolumeHeader(struct volHeader *hd);
195 static void FreeVolumeHeader(Volume * vp);
196 static void AddVolumeToHashTable(Volume * vp, int hashid);
197 static void DeleteVolumeFromHashTable(Volume * vp);
199 static int VHold(Volume * vp);
201 static int VHold_r(Volume * vp);
202 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
203 static void VReleaseVolumeHandles_r(Volume * vp);
204 static void VCloseVolumeHandles_r(Volume * vp);
205 static void LoadVolumeHeader(Error * ec, Volume * vp);
206 static int VCheckOffline(Volume * vp);
207 static int VCheckDetach(Volume * vp);
208 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
209 Volume * hint, const struct timespec *ts);
211 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
212 * defined when not linked with vice, XXXX */
213 ProgramType programType; /* The type of program using the package */
214 static VolumePackageOptions vol_opts;
216 /* extended volume package statistics */
219 #ifdef VOL_LOCK_DEBUG
220 pthread_t vol_glock_holder = 0;
224 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
225 /* Must be a multiple of 4 (1 word) !! */
227 /* this parameter needs to be tunable at runtime.
228 * 128 was really inadequate for largish servers -- at 16384 volumes this
229 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
230 * talk about bad spatial locality...
232 * an AVL or splay tree might work a lot better, but we'll just increase
233 * the default hash table size for now
235 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
236 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
237 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
240 * turn volume hash chains into partially ordered lists.
241 * when the threshold is exceeded between two adjacent elements,
242 * perform a chain rebalancing operation.
244 * keep the threshold high in order to keep cache line invalidates
245 * low "enough" on SMPs
247 #define VOLUME_HASH_REORDER_THRESHOLD 200
250 * when possible, don't just reorder single elements, but reorder
251 * entire chains of elements at once. a chain of elements that
252 * exceed the element previous to the pivot by at least CHAIN_THRESH
253 * accesses are moved in front of the chain whose elements have at
254 * least CHAIN_THRESH less accesses than the pivot element
256 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
258 #include "rx/rx_queue.h"
261 VolumeHashTable_t VolumeHashTable = {
262 DEFAULT_VOLUME_HASH_SIZE,
263 DEFAULT_VOLUME_HASH_MASK,
268 static void VInitVolumeHash(void);
272 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
276 afs_int32 ffs_tmp = x;
280 for (ffs_i = 1;; ffs_i++) {
287 #endif /* !AFS_HAVE_FFS */
289 #ifdef AFS_PTHREAD_ENV
291 * disk partition queue element
293 typedef struct diskpartition_queue_t {
294 struct rx_queue queue; /**< queue header */
295 struct DiskPartition64 *diskP; /**< disk partition table entry */
296 } diskpartition_queue_t;
298 #ifndef AFS_DEMAND_ATTACH_FS
300 typedef struct vinitvolumepackage_thread_t {
301 struct rx_queue queue;
302 pthread_cond_t thread_done_cv;
303 int n_threads_complete;
304 } vinitvolumepackage_thread_t;
305 static void * VInitVolumePackageThread(void * args);
307 #else /* !AFS_DEMAND_ATTTACH_FS */
308 #define VINIT_BATCH_MAX_SIZE 512
311 * disk partition work queue
313 struct partition_queue {
314 struct rx_queue head; /**< diskpartition_queue_t queue */
315 pthread_mutex_t mutex;
320 * volumes parameters for preattach
322 struct volume_init_batch {
323 struct rx_queue queue; /**< queue header */
324 int thread; /**< posting worker thread */
325 int last; /**< indicates thread is done */
326 int size; /**< number of volume ids in batch */
327 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
331 * volume parameters work queue
333 struct volume_init_queue {
334 struct rx_queue head; /**< volume_init_batch queue */
335 pthread_mutex_t mutex;
340 * volume init worker thread parameters
342 struct vinitvolumepackage_thread_param {
343 int nthreads; /**< total number of worker threads */
344 int thread; /**< thread number for this worker thread */
345 struct partition_queue *pq; /**< queue partitions to scan */
346 struct volume_init_queue *vq; /**< queue of volume to preattach */
349 static void *VInitVolumePackageThread(void *args);
350 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
351 static VolId VInitNextVolumeId(DIR *dirp);
352 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
354 #endif /* !AFS_DEMAND_ATTACH_FS */
355 #endif /* AFS_PTHREAD_ENV */
357 #ifndef AFS_DEMAND_ATTACH_FS
358 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
359 int * nAttached, int * nUnattached);
360 #endif /* AFS_DEMAND_ATTACH_FS */
363 #ifdef AFS_DEMAND_ATTACH_FS
364 /* demand attach fileserver extensions */
367 * in the future we will support serialization of VLRU state into the fs_state
370 * these structures are the beginning of that effort
372 struct VLRU_DiskHeader {
373 struct versionStamp stamp; /* magic and structure version number */
374 afs_uint32 mtime; /* time of dump to disk */
375 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
378 struct VLRU_DiskEntry {
379 afs_uint32 vid; /* volume ID */
380 afs_uint32 idx; /* generation */
381 afs_uint32 last_get; /* timestamp of last get */
384 struct VLRU_StartupQueue {
385 struct VLRU_DiskEntry * entry;
390 typedef struct vshutdown_thread_t {
392 pthread_mutex_t lock;
394 pthread_cond_t master_cv;
396 int n_threads_complete;
398 int schedule_version;
401 byte n_parts_done_pass;
402 byte part_thread_target[VOLMAXPARTS+1];
403 byte part_done_pass[VOLMAXPARTS+1];
404 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
405 int stats[4][VOLMAXPARTS+1];
406 } vshutdown_thread_t;
407 static void * VShutdownThread(void * args);
410 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
411 static int VCheckFree(Volume * vp);
414 static void AddVolumeToVByPList_r(Volume * vp);
415 static void DeleteVolumeFromVByPList_r(Volume * vp);
416 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
417 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
418 static void VVByPListWait_r(struct DiskPartition64 * dp);
420 /* online salvager */
421 static int VCheckSalvage(Volume * vp);
422 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
423 static int VScheduleSalvage_r(Volume * vp);
426 /* Volume hash table */
427 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
428 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
429 static void VHashEndExclusive_r(VolumeHashChainHead * head);
430 static void VHashWait_r(VolumeHashChainHead * head);
433 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
434 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
435 struct rx_queue ** idx);
436 static void ShutdownController(vshutdown_thread_t * params);
437 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
440 static void VLRU_ComputeConstants(void);
441 static void VInitVLRU(void);
442 static void VLRU_Init_Node_r(Volume * vp);
443 static void VLRU_Add_r(Volume * vp);
444 static void VLRU_Delete_r(Volume * vp);
445 static void VLRU_UpdateAccess_r(Volume * vp);
446 static void * VLRU_ScannerThread(void * args);
447 static void VLRU_Scan_r(int idx);
448 static void VLRU_Promote_r(int idx);
449 static void VLRU_Demote_r(int idx);
450 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
453 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
454 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
455 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
458 pthread_key_t VThread_key;
459 VThreadOptions_t VThread_defaults = {
460 0 /**< allow salvsync */
462 #endif /* AFS_DEMAND_ATTACH_FS */
465 struct Lock vol_listLock; /* Lock obtained when listing volumes:
466 * prevents a volume from being missed
467 * if the volume is attached during a
471 /* Common message used when the volume goes off line */
472 char *VSalvageMessage =
473 "Files in this volume are currently unavailable; call operations";
475 int VInit; /* 0 - uninitialized,
476 * 1 - initialized but not all volumes have been attached,
477 * 2 - initialized and all volumes have been attached,
478 * 3 - initialized, all volumes have been attached, and
479 * VConnectFS() has completed. */
481 static int vinit_attach_abort = 0;
483 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
484 * used to stamp volume headers and in-core
485 * vnodes. When the volume goes on-line the
486 * vnode will be invalidated
487 * access only with VOL_LOCK held */
492 /***************************************************/
493 /* Startup routines */
494 /***************************************************/
496 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
497 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
498 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
502 * assign default values to a VolumePackageOptions struct.
504 * Always call this on a VolumePackageOptions struct first, then set any
505 * specific options you want, then call VInitVolumePackage2.
507 * @param[in] pt caller's program type
508 * @param[out] opts volume package options
511 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
513 opts->nLargeVnodes = opts->nSmallVnodes = 5;
516 opts->canScheduleSalvage = 0;
517 opts->canUseFSSYNC = 0;
518 opts->canUseSALVSYNC = 0;
520 opts->interrupt_rxcall = NULL;
521 opts->offline_timeout = -1;
522 opts->offline_shutdown_timeout = -1;
525 opts->unsafe_attach = 1;
526 #else /* !FAST_RESTART */
527 opts->unsafe_attach = 0;
528 #endif /* !FAST_RESTART */
532 opts->canScheduleSalvage = 1;
533 opts->canUseSALVSYNC = 1;
537 opts->canUseFSSYNC = 1;
541 opts->nLargeVnodes = 0;
542 opts->nSmallVnodes = 0;
544 opts->canScheduleSalvage = 1;
545 opts->canUseFSSYNC = 1;
555 * Set VInit to a certain value, and signal waiters.
557 * @param[in] value the value to set VInit to
562 VSetVInit_r(int value)
565 CV_BROADCAST(&vol_vinit_cond);
569 VLogOfflineTimeout(const char *type, afs_int32 timeout)
575 Log("VInitVolumePackage: Interrupting clients accessing %s "
576 "immediately\n", type);
578 Log("VInitVolumePackage: Interrupting clients accessing %s "
579 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
584 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
586 int errors = 0; /* Number of errors while finding vice partitions. */
591 #ifndef AFS_PTHREAD_ENV
592 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
593 Log("VInitVolumePackage: offline_timeout and/or "
594 "offline_shutdown_timeout was specified, but the volume package "
595 "does not support these for LWP builds\n");
599 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
600 VLogOfflineTimeout("volumes going offline during shutdown",
601 opts->offline_shutdown_timeout);
603 memset(&VStats, 0, sizeof(VStats));
604 VStats.hdr_cache_size = 200;
606 VInitPartitionPackage();
608 #ifdef AFS_DEMAND_ATTACH_FS
609 if (programType == fileServer) {
612 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
614 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
617 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
618 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
619 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
620 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
621 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
622 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
623 #ifndef AFS_PTHREAD_ENV
625 #endif /* AFS_PTHREAD_ENV */
626 Lock_Init(&vol_listLock);
628 srandom(time(0)); /* For VGetVolumeInfo */
630 #ifdef AFS_DEMAND_ATTACH_FS
631 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
632 #endif /* AFS_DEMAND_ATTACH_FS */
634 /* Ok, we have done enough initialization that fileserver can
635 * start accepting calls, even though the volumes may not be
636 * available just yet.
640 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
641 if (programType == salvageServer) {
644 #endif /* AFS_DEMAND_ATTACH_FS */
645 #ifdef FSSYNC_BUILD_SERVER
646 if (programType == fileServer) {
650 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
651 if (VCanUseSALVSYNC()) {
652 /* establish a connection to the salvager at this point */
653 osi_Assert(VConnectSALV() != 0);
655 #endif /* AFS_DEMAND_ATTACH_FS */
657 if (opts->volcache > VStats.hdr_cache_size)
658 VStats.hdr_cache_size = opts->volcache;
659 VInitVolumeHeaderCache(VStats.hdr_cache_size);
661 VInitVnodes(vLarge, opts->nLargeVnodes);
662 VInitVnodes(vSmall, opts->nSmallVnodes);
665 errors = VAttachPartitions();
669 if (programType != fileServer) {
670 errors = VInitAttachVolumes(programType);
676 #ifdef FSSYNC_BUILD_CLIENT
677 if (VCanUseFSSYNC()) {
679 #ifdef AFS_DEMAND_ATTACH_FS
680 if (programType == salvageServer) {
681 Log("Unable to connect to file server; aborted\n");
684 #endif /* AFS_DEMAND_ATTACH_FS */
685 Log("Unable to connect to file server; will retry at need\n");
688 #endif /* FSSYNC_BUILD_CLIENT */
693 #if !defined(AFS_PTHREAD_ENV)
695 * Attach volumes in vice partitions
697 * @param[in] pt calling program type
700 * @note This is the original, non-threaded version of attach parititions.
702 * @post VInit state is 2
705 VInitAttachVolumes(ProgramType pt)
707 osi_Assert(VInit==1);
708 if (pt == fileServer) {
709 struct DiskPartition64 *diskP;
710 /* Attach all the volumes in this partition */
711 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
712 int nAttached = 0, nUnattached = 0;
713 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
717 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
718 LWP_NoYieldSignal(VInitAttachVolumes);
722 #endif /* !AFS_PTHREAD_ENV */
724 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
726 * Attach volumes in vice partitions
728 * @param[in] pt calling program type
731 * @note Threaded version of attach parititions.
733 * @post VInit state is 2
736 VInitAttachVolumes(ProgramType pt)
738 osi_Assert(VInit==1);
739 if (pt == fileServer) {
740 struct DiskPartition64 *diskP;
741 struct vinitvolumepackage_thread_t params;
742 struct diskpartition_queue_t * dpq;
743 int i, threads, parts;
745 pthread_attr_t attrs;
747 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
749 params.n_threads_complete = 0;
751 /* create partition work queue */
752 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
753 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
754 osi_Assert(dpq != NULL);
756 queue_Append(¶ms,dpq);
759 threads = MIN(parts, vol_attach_threads);
762 /* spawn off a bunch of initialization threads */
763 osi_Assert(pthread_attr_init(&attrs) == 0);
764 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
766 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
767 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
771 for (i=0; i < threads; i++) {
774 osi_Assert(pthread_create
775 (&tid, &attrs, &VInitVolumePackageThread,
777 AFS_SIGSET_RESTORE();
780 while(params.n_threads_complete < threads) {
781 VOL_CV_WAIT(¶ms.thread_done_cv);
785 osi_Assert(pthread_attr_destroy(&attrs) == 0);
787 /* if we're only going to run one init thread, don't bother creating
789 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
790 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
793 VInitVolumePackageThread(¶ms);
796 CV_DESTROY(¶ms.thread_done_cv);
799 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
800 CV_BROADCAST(&vol_init_attach_cond);
806 VInitVolumePackageThread(void * args) {
808 struct DiskPartition64 *diskP;
809 struct vinitvolumepackage_thread_t * params;
810 struct diskpartition_queue_t * dpq;
812 params = (vinitvolumepackage_thread_t *) args;
816 /* Attach all the volumes in this partition */
817 while (queue_IsNotEmpty(params)) {
818 int nAttached = 0, nUnattached = 0;
820 if (vinit_attach_abort) {
821 Log("Aborting initialization\n");
825 dpq = queue_First(params,diskpartition_queue_t);
831 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
837 params->n_threads_complete++;
838 CV_SIGNAL(¶ms->thread_done_cv);
842 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
844 #if defined(AFS_DEMAND_ATTACH_FS)
846 * Attach volumes in vice partitions
848 * @param[in] pt calling program type
851 * @note Threaded version of attach partitions.
853 * @post VInit state is 2
856 VInitAttachVolumes(ProgramType pt)
858 osi_Assert(VInit==1);
859 if (pt == fileServer) {
861 struct DiskPartition64 *diskP;
862 struct partition_queue pq;
863 struct volume_init_queue vq;
865 int i, threads, parts;
867 pthread_attr_t attrs;
869 /* create partition work queue */
871 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
872 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
873 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
874 struct diskpartition_queue_t *dp;
875 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
876 osi_Assert(dp != NULL);
878 queue_Append(&pq, dp);
881 /* number of worker threads; at least one, not to exceed the number of partitions */
882 threads = MIN(parts, vol_attach_threads);
884 /* create volume work queue */
886 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
887 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
889 osi_Assert(pthread_attr_init(&attrs) == 0);
890 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
892 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
893 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
896 /* create threads to scan disk partitions. */
897 for (i=0; i < threads; i++) {
898 struct vinitvolumepackage_thread_param *params;
901 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
905 params->nthreads = threads;
906 params->thread = i+1;
909 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
910 AFS_SIGSET_RESTORE();
913 VInitPreAttachVolumes(threads, &vq);
915 osi_Assert(pthread_attr_destroy(&attrs) == 0);
917 MUTEX_DESTROY(&pq.mutex);
919 MUTEX_DESTROY(&vq.mutex);
923 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
924 CV_BROADCAST(&vol_init_attach_cond);
931 * Volume package initialization worker thread. Scan partitions for volume
932 * header files. Gather batches of volume ids and dispatch them to
933 * the main thread to be preattached. The volume preattachement is done
934 * in the main thread to avoid global volume lock contention.
937 VInitVolumePackageThread(void *args)
939 struct vinitvolumepackage_thread_param *params;
940 struct DiskPartition64 *partition;
941 struct partition_queue *pq;
942 struct volume_init_queue *vq;
943 struct volume_init_batch *vb;
946 params = (struct vinitvolumepackage_thread_param *)args;
952 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
954 vb->thread = params->thread;
958 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
959 while((partition = VInitNextPartition(pq))) {
963 Log("Partition %s: pre-attaching volumes\n", partition->name);
964 dirp = opendir(VPartitionPath(partition));
966 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
969 while ((vid = VInitNextVolumeId(dirp))) {
970 Volume *vp = (Volume*)malloc(sizeof(Volume));
972 memset(vp, 0, sizeof(Volume));
973 vp->device = partition->device;
974 vp->partition = partition;
976 queue_Init(&vp->vnode_list);
977 queue_Init(&vp->rx_call_list);
978 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
980 vb->batch[vb->size++] = vp;
981 if (vb->size == VINIT_BATCH_MAX_SIZE) {
982 MUTEX_ENTER(&vq->mutex);
983 queue_Append(vq, vb);
984 CV_BROADCAST(&vq->cv);
985 MUTEX_EXIT(&vq->mutex);
987 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
989 vb->thread = params->thread;
998 MUTEX_ENTER(&vq->mutex);
999 queue_Append(vq, vb);
1000 CV_BROADCAST(&vq->cv);
1001 MUTEX_EXIT(&vq->mutex);
1003 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
1009 * Read next element from the pre-populated partition list.
1011 static struct DiskPartition64*
1012 VInitNextPartition(struct partition_queue *pq)
1014 struct DiskPartition64 *partition;
1015 struct diskpartition_queue_t *dp; /* queue element */
1017 if (vinit_attach_abort) {
1018 Log("Aborting volume preattach thread.\n");
1022 /* get next partition to scan */
1023 MUTEX_ENTER(&pq->mutex);
1024 if (queue_IsEmpty(pq)) {
1025 MUTEX_EXIT(&pq->mutex);
1028 dp = queue_First(pq, diskpartition_queue_t);
1030 MUTEX_EXIT(&pq->mutex);
1033 osi_Assert(dp->diskP);
1035 partition = dp->diskP;
1041 * Find next volume id on the partition.
1044 VInitNextVolumeId(DIR *dirp)
1050 while((d = readdir(dirp))) {
1051 if (vinit_attach_abort) {
1052 Log("Aborting volume preattach thread.\n");
1055 ext = strrchr(d->d_name, '.');
1056 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1057 vid = VolumeNumber(d->d_name);
1061 Log("Warning: bogus volume header file: %s\n", d->d_name);
1068 * Preattach volumes in batches to avoid lock contention.
1071 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1073 struct volume_init_batch *vb;
1077 /* dequeue next volume */
1078 MUTEX_ENTER(&vq->mutex);
1079 if (queue_IsEmpty(vq)) {
1080 CV_WAIT(&vq->cv, &vq->mutex);
1082 vb = queue_First(vq, volume_init_batch);
1084 MUTEX_EXIT(&vq->mutex);
1088 for (i = 0; i<vb->size; i++) {
1094 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1096 Log("Error looking up volume, code=%d\n", ec);
1099 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1102 /* put pre-attached volume onto the hash table
1103 * and bring it up to the pre-attached state */
1104 AddVolumeToHashTable(vp, vp->hashid);
1105 AddVolumeToVByPList_r(vp);
1106 VLRU_Init_Node_r(vp);
1107 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1120 #endif /* AFS_DEMAND_ATTACH_FS */
1122 #if !defined(AFS_DEMAND_ATTACH_FS)
1124 * attach all volumes on a given disk partition
1127 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1133 Log("Partition %s: attaching volumes\n", diskP->name);
1134 dirp = opendir(VPartitionPath(diskP));
1136 Log("opendir on Partition %s failed!\n", diskP->name);
1140 while ((dp = readdir(dirp))) {
1142 p = strrchr(dp->d_name, '.');
1144 if (vinit_attach_abort) {
1145 Log("Partition %s: abort attach volumes\n", diskP->name);
1149 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1152 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1154 (*(vp ? nAttached : nUnattached))++;
1155 if (error == VOFFLINE)
1156 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1157 else if (LogLevel >= 5) {
1158 Log("Partition %s: attached volume %d (%s)\n",
1159 diskP->name, VolumeNumber(dp->d_name),
1168 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1173 #endif /* !AFS_DEMAND_ATTACH_FS */
1175 /***************************************************/
1176 /* Shutdown routines */
1177 /***************************************************/
1181 * highly multithreaded volume package shutdown
1183 * with the demand attach fileserver extensions,
1184 * VShutdown has been modified to be multithreaded.
1185 * In order to achieve optimal use of many threads,
1186 * the shutdown code involves one control thread and
1187 * n shutdown worker threads. The control thread
1188 * periodically examines the number of volumes available
1189 * for shutdown on each partition, and produces a worker
1190 * thread allocation schedule. The idea is to eliminate
1191 * redundant scheduling computation on the workers by
1192 * having a single master scheduler.
1194 * The scheduler's objectives are:
1196 * each partition with volumes remaining gets allocated
1197 * at least 1 thread (assuming sufficient threads)
1199 * threads are allocated proportional to the number of
1200 * volumes remaining to be offlined. This ensures that
1201 * the OS I/O scheduler has many requests to elevator
1202 * seek on partitions that will (presumably) take the
1203 * longest amount of time (from now) to finish shutdown
1204 * (3) keep threads busy
1205 * when there are extra threads, they are assigned to
1206 * partitions using a simple round-robin algorithm
1208 * In the future, we may wish to add the ability to adapt
1209 * to the relative performance patterns of each disk
1214 * multi-step shutdown process
1216 * demand attach shutdown is a four-step process. Each
1217 * shutdown "pass" shuts down increasingly more difficult
1218 * volumes. The main purpose is to achieve better cache
1219 * utilization during shutdown.
1222 * shutdown volumes in the unattached, pre-attached
1225 * shutdown attached volumes with cached volume headers
1227 * shutdown all volumes in non-exclusive states
1229 * shutdown all remaining volumes
1232 #ifdef AFS_DEMAND_ATTACH_FS
1238 struct DiskPartition64 * diskP;
1239 struct diskpartition_queue_t * dpq;
1240 vshutdown_thread_t params;
1242 pthread_attr_t attrs;
1244 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1247 Log("VShutdown: aborting attach volumes\n");
1248 vinit_attach_abort = 1;
1249 VOL_CV_WAIT(&vol_init_attach_cond);
1252 for (params.n_parts=0, diskP = DiskPartitionList;
1253 diskP; diskP = diskP->next, params.n_parts++);
1255 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1256 params.n_parts, params.n_parts > 1 ? "s" : "");
1258 vol_shutting_down = 1;
1260 if (vol_attach_threads > 1) {
1261 /* prepare for parallel shutdown */
1262 params.n_threads = vol_attach_threads;
1263 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1264 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1265 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1266 osi_Assert(pthread_attr_init(&attrs) == 0);
1267 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1268 queue_Init(¶ms);
1270 /* setup the basic partition information structures for
1271 * parallel shutdown */
1272 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1274 struct rx_queue * qp, * nqp;
1278 VVByPListWait_r(diskP);
1279 VVByPListBeginExclusive_r(diskP);
1282 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1283 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1287 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1288 VPartitionPath(diskP), count);
1291 /* build up the pass 0 shutdown work queue */
1292 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1293 osi_Assert(dpq != NULL);
1295 queue_Prepend(¶ms, dpq);
1297 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1300 Log("VShutdown: beginning parallel fileserver shutdown\n");
1301 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1302 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1304 /* do pass 0 shutdown */
1305 MUTEX_ENTER(¶ms.lock);
1306 for (i=0; i < params.n_threads; i++) {
1307 osi_Assert(pthread_create
1308 (&tid, &attrs, &VShutdownThread,
1312 /* wait for all the pass 0 shutdowns to complete */
1313 while (params.n_threads_complete < params.n_threads) {
1314 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1316 params.n_threads_complete = 0;
1318 CV_BROADCAST(¶ms.cv);
1319 MUTEX_EXIT(¶ms.lock);
1321 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1322 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1324 /* run the parallel shutdown scheduler. it will drop the glock internally */
1325 ShutdownController(¶ms);
1327 /* wait for all the workers to finish pass 3 and terminate */
1328 while (params.pass < 4) {
1329 VOL_CV_WAIT(¶ms.cv);
1332 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1333 CV_DESTROY(¶ms.cv);
1334 CV_DESTROY(¶ms.master_cv);
1335 MUTEX_DESTROY(¶ms.lock);
1337 /* drop the VByPList exclusive reservations */
1338 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1339 VVByPListEndExclusive_r(diskP);
1340 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1341 VPartitionPath(diskP),
1342 params.stats[0][diskP->index],
1343 params.stats[1][diskP->index],
1344 params.stats[2][diskP->index],
1345 params.stats[3][diskP->index]);
1348 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1350 /* if we're only going to run one shutdown thread, don't bother creating
1352 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1354 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1355 VShutdownByPartition_r(diskP);
1359 Log("VShutdown: complete.\n");
1362 #else /* AFS_DEMAND_ATTACH_FS */
1372 Log("VShutdown: aborting attach volumes\n");
1373 vinit_attach_abort = 1;
1374 #ifdef AFS_PTHREAD_ENV
1375 VOL_CV_WAIT(&vol_init_attach_cond);
1377 LWP_WaitProcess(VInitAttachVolumes);
1378 #endif /* AFS_PTHREAD_ENV */
1381 Log("VShutdown: shutting down on-line volumes...\n");
1382 vol_shutting_down = 1;
1383 for (i = 0; i < VolumeHashTable.Size; i++) {
1384 /* try to hold first volume in the hash table */
1385 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1389 Log("VShutdown: Attempting to take volume %u offline.\n",
1392 /* next, take the volume offline (drops reference count) */
1393 VOffline_r(vp, "File server was shut down");
1397 Log("VShutdown: complete.\n");
1399 #endif /* AFS_DEMAND_ATTACH_FS */
1405 osi_Assert(VInit>0);
1412 * stop new activity (e.g. SALVSYNC) from occurring
1414 * Use this to make the volume package less busy; for example, during
1415 * shutdown. This doesn't actually shutdown/detach anything in the
1416 * volume package, but prevents certain processes from ocurring. For
1417 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1418 * could also use this to prevent new volume attachment, or prevent
1419 * other programs from checking out volumes, etc.
1424 #ifdef AFS_DEMAND_ATTACH_FS
1425 /* make sure we don't try to contact the salvageserver, since it may
1426 * not be around anymore */
1427 vol_disallow_salvsync = 1;
1431 #ifdef AFS_DEMAND_ATTACH_FS
1434 * shutdown control thread
1437 ShutdownController(vshutdown_thread_t * params)
1440 struct DiskPartition64 * diskP;
1442 vshutdown_thread_t shadow;
1444 ShutdownCreateSchedule(params);
1446 while ((params->pass < 4) &&
1447 (params->n_threads_complete < params->n_threads)) {
1448 /* recompute schedule once per second */
1450 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1454 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1455 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1456 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1457 shadow.n_threads_complete, shadow.n_parts_done_pass);
1458 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1460 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1462 diskP->vol_list.len,
1463 shadow.part_thread_target[id],
1464 shadow.part_done_pass[id],
1465 shadow.part_pass_head[id]);
1471 ShutdownCreateSchedule(params);
1475 /* create the shutdown thread work schedule.
1476 * this scheduler tries to implement fairness
1477 * by allocating at least 1 thread to each
1478 * partition with volumes to be shutdown,
1479 * and then it attempts to allocate remaining
1480 * threads based upon the amount of work left
1483 ShutdownCreateSchedule(vshutdown_thread_t * params)
1485 struct DiskPartition64 * diskP;
1486 int sum, thr_workload, thr_left;
1487 int part_residue[VOLMAXPARTS+1];
1490 /* compute the total number of outstanding volumes */
1492 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1493 sum += diskP->vol_list.len;
1496 params->schedule_version++;
1497 params->vol_remaining = sum;
1502 /* compute average per-thread workload */
1503 thr_workload = sum / params->n_threads;
1504 if (sum % params->n_threads)
1507 thr_left = params->n_threads;
1508 memset(&part_residue, 0, sizeof(part_residue));
1510 /* for fairness, give every partition with volumes remaining
1511 * at least one thread */
1512 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1514 if (diskP->vol_list.len) {
1515 params->part_thread_target[id] = 1;
1518 params->part_thread_target[id] = 0;
1522 if (thr_left && thr_workload) {
1523 /* compute length-weighted workloads */
1526 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1528 delta = (diskP->vol_list.len / thr_workload) -
1529 params->part_thread_target[id];
1533 if (delta < thr_left) {
1534 params->part_thread_target[id] += delta;
1537 params->part_thread_target[id] += thr_left;
1545 /* try to assign any leftover threads to partitions that
1546 * had volume lengths closer to needing thread_target+1 */
1547 int max_residue, max_id = 0;
1549 /* compute the residues */
1550 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1552 part_residue[id] = diskP->vol_list.len -
1553 (params->part_thread_target[id] * thr_workload);
1556 /* now try to allocate remaining threads to partitions with the
1557 * highest residues */
1560 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1562 if (part_residue[id] > max_residue) {
1563 max_residue = part_residue[id];
1572 params->part_thread_target[max_id]++;
1574 part_residue[max_id] = 0;
1579 /* punt and give any remaining threads equally to each partition */
1581 if (thr_left >= params->n_parts) {
1582 alloc = thr_left / params->n_parts;
1583 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1585 params->part_thread_target[id] += alloc;
1590 /* finish off the last of the threads */
1591 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1593 params->part_thread_target[id]++;
1599 /* worker thread for parallel shutdown */
1601 VShutdownThread(void * args)
1603 vshutdown_thread_t * params;
1604 int found, pass, schedule_version_save, count;
1605 struct DiskPartition64 *diskP;
1606 struct diskpartition_queue_t * dpq;
1609 params = (vshutdown_thread_t *) args;
1611 /* acquire the shutdown pass 0 lock */
1612 MUTEX_ENTER(¶ms->lock);
1614 /* if there's still pass 0 work to be done,
1615 * get a work entry, and do a pass 0 shutdown */
1616 if (queue_IsNotEmpty(params)) {
1617 dpq = queue_First(params, diskpartition_queue_t);
1619 MUTEX_EXIT(¶ms->lock);
1625 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1627 params->stats[0][diskP->index] = count;
1628 MUTEX_ENTER(¶ms->lock);
1631 params->n_threads_complete++;
1632 if (params->n_threads_complete == params->n_threads) {
1633 /* notify control thread that all workers have completed pass 0 */
1634 CV_SIGNAL(¶ms->master_cv);
1636 while (params->pass == 0) {
1637 CV_WAIT(¶ms->cv, ¶ms->lock);
1641 MUTEX_EXIT(¶ms->lock);
1644 pass = params->pass;
1645 osi_Assert(pass > 0);
1647 /* now escalate through the more complicated shutdowns */
1649 schedule_version_save = params->schedule_version;
1651 /* find a disk partition to work on */
1652 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1654 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1655 params->part_thread_target[id]--;
1662 /* hmm. for some reason the controller thread couldn't find anything for
1663 * us to do. let's see if there's anything we can do */
1664 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1666 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1669 } else if (!params->part_done_pass[id]) {
1670 params->part_done_pass[id] = 1;
1671 params->n_parts_done_pass++;
1673 Log("VShutdown: done shutting down volumes on partition %s.\n",
1674 VPartitionPath(diskP));
1680 /* do work on this partition until either the controller
1681 * creates a new schedule, or we run out of things to do
1682 * on this partition */
1685 while (!params->part_done_pass[id] &&
1686 (schedule_version_save == params->schedule_version)) {
1687 /* ShutdownVolumeWalk_r will drop the glock internally */
1688 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1689 if (!params->part_done_pass[id]) {
1690 params->part_done_pass[id] = 1;
1691 params->n_parts_done_pass++;
1693 Log("VShutdown: done shutting down volumes on partition %s.\n",
1694 VPartitionPath(diskP));
1702 params->stats[pass][id] += count;
1704 /* ok, everyone is done this pass, proceed */
1707 params->n_threads_complete++;
1708 while (params->pass == pass) {
1709 if (params->n_threads_complete == params->n_threads) {
1710 /* we are the last thread to complete, so we will
1711 * reinitialize worker pool state for the next pass */
1712 params->n_threads_complete = 0;
1713 params->n_parts_done_pass = 0;
1715 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1717 params->part_done_pass[id] = 0;
1718 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1721 /* compute a new thread schedule before releasing all the workers */
1722 ShutdownCreateSchedule(params);
1724 /* wake up all the workers */
1725 CV_BROADCAST(¶ms->cv);
1728 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1729 pass, params->n_threads, params->n_parts);
1732 VOL_CV_WAIT(¶ms->cv);
1735 pass = params->pass;
1749 /* shut down all volumes on a given disk partition
1751 * note that this function will not allow mp-fast
1752 * shutdown of a partition */
1754 VShutdownByPartition_r(struct DiskPartition64 * dp)
1760 /* wait for other exclusive ops to finish */
1761 VVByPListWait_r(dp);
1763 /* begin exclusive access */
1764 VVByPListBeginExclusive_r(dp);
1766 /* pick the low-hanging fruit first,
1767 * then do the complicated ones last
1768 * (has the advantage of keeping
1769 * in-use volumes up until the bitter end) */
1770 for (pass = 0, total=0; pass < 4; pass++) {
1771 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1772 total += pass_stats[pass];
1775 /* end exclusive access */
1776 VVByPListEndExclusive_r(dp);
1778 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1779 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1784 /* internal shutdown functionality
1786 * for multi-pass shutdown:
1787 * 0 to only "shutdown" {pre,un}attached and error state volumes
1788 * 1 to also shutdown attached volumes w/ volume header loaded
1789 * 2 to also shutdown attached volumes w/o volume header loaded
1790 * 3 to also shutdown exclusive state volumes
1792 * caller MUST hold exclusive access on the hash chain
1793 * because we drop vol_glock_mutex internally
1795 * this function is reentrant for passes 1--3
1796 * (e.g. multiple threads can cooperate to
1797 * shutdown a partition mp-fast)
1799 * pass 0 is not scaleable because the volume state data is
1800 * synchronized by vol_glock mutex, and the locking overhead
1801 * is too high to drop the lock long enough to do linked list
1805 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1807 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1810 while (ShutdownVolumeWalk_r(dp, pass, &q))
1816 /* conditionally shutdown one volume on partition dp
1817 * returns 1 if a volume was shutdown in this pass,
1820 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1821 struct rx_queue ** idx)
1823 struct rx_queue *qp, *nqp;
1828 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1829 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1833 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1834 (V_attachState(vp) != VOL_STATE_ERROR) &&
1835 (V_attachState(vp) != VOL_STATE_DELETED) &&
1836 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1840 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1841 (vp->header == NULL)) {
1845 if (VIsExclusiveState(V_attachState(vp))) {
1850 DeleteVolumeFromVByPList_r(vp);
1851 VShutdownVolume_r(vp);
1861 * shutdown a specific volume
1863 /* caller MUST NOT hold a heavyweight ref on vp */
1865 VShutdownVolume_r(Volume * vp)
1869 VCreateReservation_r(vp);
1871 if (LogLevel >= 5) {
1872 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1873 vp->hashid, vp->partition->device, V_attachState(vp));
1876 /* wait for other blocking ops to finish */
1877 VWaitExclusiveState_r(vp);
1879 osi_Assert(VIsValidState(V_attachState(vp)));
1881 switch(V_attachState(vp)) {
1882 case VOL_STATE_SALVAGING:
1883 /* Leave salvaging volumes alone. Any in-progress salvages will
1884 * continue working after viced shuts down. This is intentional.
1887 case VOL_STATE_PREATTACHED:
1888 case VOL_STATE_ERROR:
1889 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1890 case VOL_STATE_UNATTACHED:
1891 case VOL_STATE_DELETED:
1893 case VOL_STATE_GOING_OFFLINE:
1894 case VOL_STATE_SHUTTING_DOWN:
1895 case VOL_STATE_ATTACHED:
1899 Log("VShutdown: Attempting to take volume %u offline.\n",
1902 /* take the volume offline (drops reference count) */
1903 VOffline_r(vp, "File server was shut down");
1910 VCancelReservation_r(vp);
1914 #endif /* AFS_DEMAND_ATTACH_FS */
1917 /***************************************************/
1918 /* Header I/O routines */
1919 /***************************************************/
1921 /* open a descriptor for the inode (h),
1922 * read in an on-disk structure into buffer (to) of size (size),
1923 * verify versionstamp in structure has magic (magic) and
1924 * optionally verify version (version) if (version) is nonzero
1927 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1930 struct versionStamp *vsn;
1945 vsn = (struct versionStamp *)to;
1946 if (FDH_PREAD(fdP, to, size, 0) != size || vsn->magic != magic) {
1948 FDH_REALLYCLOSE(fdP);
1953 /* Check is conditional, in case caller wants to inspect version himself */
1954 if (version && vsn->version != version) {
1960 WriteVolumeHeader_r(Error * ec, Volume * vp)
1962 IHandle_t *h = V_diskDataHandle(vp);
1972 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1973 != sizeof(V_disk(vp))) {
1975 FDH_REALLYCLOSE(fdP);
1981 /* VolumeHeaderToDisk
1982 * Allows for storing 64 bit inode numbers in on-disk volume header
1985 /* convert in-memory representation of a volume header to the
1986 * on-disk representation of a volume header */
1988 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1991 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1992 dh->stamp = h->stamp;
1994 dh->parent = h->parent;
1996 #ifdef AFS_64BIT_IOPS_ENV
1997 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1998 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1999 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2000 dh->smallVnodeIndex_hi =
2001 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2002 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2003 dh->largeVnodeIndex_hi =
2004 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2005 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2006 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2008 dh->volumeInfo_lo = h->volumeInfo;
2009 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2010 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2011 dh->linkTable_lo = h->linkTable;
2015 /* DiskToVolumeHeader
2016 * Converts an on-disk representation of a volume header to
2017 * the in-memory representation of a volume header.
2019 * Makes the assumption that AFS has *always*
2020 * zero'd the volume header file so that high parts of inode
2021 * numbers are 0 in older (SGI EFS) volume header files.
2024 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2026 memset(h, 0, sizeof(VolumeHeader_t));
2027 h->stamp = dh->stamp;
2029 h->parent = dh->parent;
2031 #ifdef AFS_64BIT_IOPS_ENV
2033 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2035 h->smallVnodeIndex =
2036 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2037 smallVnodeIndex_hi << 32);
2039 h->largeVnodeIndex =
2040 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2041 largeVnodeIndex_hi << 32);
2043 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2045 h->volumeInfo = dh->volumeInfo_lo;
2046 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2047 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2048 h->linkTable = dh->linkTable_lo;
2053 /***************************************************/
2054 /* Volume Attachment routines */
2055 /***************************************************/
2057 #ifdef AFS_DEMAND_ATTACH_FS
2059 * pre-attach a volume given its path.
2061 * @param[out] ec outbound error code
2062 * @param[in] partition partition path string
2063 * @param[in] name volume id string
2065 * @return volume object pointer
2067 * @note A pre-attached volume will only have its partition
2068 * and hashid fields initialized. At first call to
2069 * VGetVolume, the volume will be fully attached.
2073 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2077 vp = VPreAttachVolumeByName_r(ec, partition, name);
2083 * pre-attach a volume given its path.
2085 * @param[out] ec outbound error code
2086 * @param[in] partition path to vice partition
2087 * @param[in] name volume id string
2089 * @return volume object pointer
2091 * @pre VOL_LOCK held
2093 * @internal volume package internal use only.
2096 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2098 return VPreAttachVolumeById_r(ec,
2100 VolumeNumber(name));
2104 * pre-attach a volume given its path and numeric volume id.
2106 * @param[out] ec error code return
2107 * @param[in] partition path to vice partition
2108 * @param[in] volumeId numeric volume id
2110 * @return volume object pointer
2112 * @pre VOL_LOCK held
2114 * @internal volume package internal use only.
2117 VPreAttachVolumeById_r(Error * ec,
2122 struct DiskPartition64 *partp;
2126 osi_Assert(programType == fileServer);
2128 if (!(partp = VGetPartition_r(partition, 0))) {
2130 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2134 vp = VLookupVolume_r(ec, volumeId, NULL);
2139 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2143 * preattach a volume.
2145 * @param[out] ec outbound error code
2146 * @param[in] partp pointer to partition object
2147 * @param[in] vp pointer to volume object
2148 * @param[in] vid volume id
2150 * @return volume object pointer
2152 * @pre VOL_LOCK is held.
2154 * @warning Returned volume object pointer does not have to
2155 * equal the pointer passed in as argument vp. There
2156 * are potential race conditions which can result in
2157 * the pointers having different values. It is up to
2158 * the caller to make sure that references are handled
2159 * properly in this case.
2161 * @note If there is already a volume object registered with
2162 * the same volume id, its pointer MUST be passed as
2163 * argument vp. Failure to do so will result in a silent
2164 * failure to preattach.
2166 * @internal volume package internal use only.
2169 VPreAttachVolumeByVp_r(Error * ec,
2170 struct DiskPartition64 * partp,
2178 /* check to see if pre-attach already happened */
2180 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2181 (V_attachState(vp) != VOL_STATE_DELETED) &&
2182 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2183 !VIsErrorState(V_attachState(vp))) {
2185 * pre-attach is a no-op in all but the following cases:
2187 * - volume is unattached
2188 * - volume is in an error state
2189 * - volume is pre-attached
2191 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2194 /* we're re-attaching a volume; clear out some old state */
2195 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2197 if (V_partition(vp) != partp) {
2198 /* XXX potential race */
2199 DeleteVolumeFromVByPList_r(vp);
2202 /* if we need to allocate a new Volume struct,
2203 * go ahead and drop the vol glock, otherwise
2204 * do the basic setup synchronised, as it's
2205 * probably not worth dropping the lock */
2208 /* allocate the volume structure */
2209 vp = nvp = (Volume *) malloc(sizeof(Volume));
2210 osi_Assert(vp != NULL);
2211 memset(vp, 0, sizeof(Volume));
2212 queue_Init(&vp->vnode_list);
2213 queue_Init(&vp->rx_call_list);
2214 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2217 /* link the volume with its associated vice partition */
2218 vp->device = partp->device;
2219 vp->partition = partp;
2222 vp->specialStatus = 0;
2224 /* if we dropped the lock, reacquire the lock,
2225 * check for pre-attach races, and then add
2226 * the volume to the hash table */
2229 nvp = VLookupVolume_r(ec, vid, NULL);
2234 } else if (nvp) { /* race detected */
2239 /* hack to make up for VChangeState_r() decrementing
2240 * the old state counter */
2241 VStats.state_levels[0]++;
2245 /* put pre-attached volume onto the hash table
2246 * and bring it up to the pre-attached state */
2247 AddVolumeToHashTable(vp, vp->hashid);
2248 AddVolumeToVByPList_r(vp);
2249 VLRU_Init_Node_r(vp);
2250 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2253 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2261 #endif /* AFS_DEMAND_ATTACH_FS */
2263 /* Attach an existing volume, given its pathname, and return a
2264 pointer to the volume header information. The volume also
2265 normally goes online at this time. An offline volume
2266 must be reattached to make it go online */
2268 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2272 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2278 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2281 struct DiskPartition64 *partp;
2286 #ifdef AFS_DEMAND_ATTACH_FS
2287 VolumeStats stats_save;
2289 #endif /* AFS_DEMAND_ATTACH_FS */
2293 volumeId = VolumeNumber(name);
2295 if (!(partp = VGetPartition_r(partition, 0))) {
2297 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2301 if (VRequiresPartLock()) {
2302 osi_Assert(VInit == 3);
2303 VLockPartition_r(partition);
2304 } else if (programType == fileServer) {
2305 #ifdef AFS_DEMAND_ATTACH_FS
2306 /* lookup the volume in the hash table */
2307 vp = VLookupVolume_r(ec, volumeId, NULL);
2313 /* save any counters that are supposed to
2314 * be monotonically increasing over the
2315 * lifetime of the fileserver */
2316 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2318 memset(&stats_save, 0, sizeof(VolumeStats));
2321 /* if there's something in the hash table, and it's not
2322 * in the pre-attach state, then we may need to detach
2323 * it before proceeding */
2324 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2325 VCreateReservation_r(vp);
2326 VWaitExclusiveState_r(vp);
2328 /* at this point state must be one of:
2338 if (vp->specialStatus == VBUSY)
2341 /* if it's already attached, see if we can return it */
2342 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2343 VGetVolumeByVp_r(ec, vp);
2344 if (V_inUse(vp) == fileServer) {
2345 VCancelReservation_r(vp);
2349 /* otherwise, we need to detach, and attempt to re-attach */
2350 VDetachVolume_r(ec, vp);
2352 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2355 /* if it isn't fully attached, delete from the hash tables,
2356 and let the refcounter handle the rest */
2357 DeleteVolumeFromHashTable(vp);
2358 DeleteVolumeFromVByPList_r(vp);
2361 VCancelReservation_r(vp);
2365 /* pre-attach volume if it hasn't been done yet */
2367 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2368 (V_attachState(vp) == VOL_STATE_DELETED) ||
2369 (V_attachState(vp) == VOL_STATE_ERROR)) {
2371 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2377 osi_Assert(vp != NULL);
2379 /* handle pre-attach races
2381 * multiple threads can race to pre-attach a volume,
2382 * but we can't let them race beyond that
2384 * our solution is to let the first thread to bring
2385 * the volume into an exclusive state win; the other
2386 * threads just wait until it finishes bringing the
2387 * volume online, and then they do a vgetvolumebyvp
2389 if (svp && (svp != vp)) {
2390 /* wait for other exclusive ops to finish */
2391 VCreateReservation_r(vp);
2392 VWaitExclusiveState_r(vp);
2394 /* get a heavyweight ref, kill the lightweight ref, and return */
2395 VGetVolumeByVp_r(ec, vp);
2396 VCancelReservation_r(vp);
2400 /* at this point, we are chosen as the thread to do
2401 * demand attachment for this volume. all other threads
2402 * doing a getvolume on vp->hashid will block until we finish */
2404 /* make sure any old header cache entries are invalidated
2405 * before proceeding */
2406 FreeVolumeHeader(vp);
2408 VChangeState_r(vp, VOL_STATE_ATTACHING);
2410 /* restore any saved counters */
2411 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2412 #else /* AFS_DEMAND_ATTACH_FS */
2413 vp = VGetVolume_r(ec, volumeId);
2415 if (V_inUse(vp) == fileServer)
2417 if (vp->specialStatus == VBUSY)
2419 VDetachVolume_r(ec, vp);
2421 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2425 #endif /* AFS_DEMAND_ATTACH_FS */
2429 strcpy(path, VPartitionPath(partp));
2433 strcat(path, OS_DIRSEP);
2437 vp = (Volume *) calloc(1, sizeof(Volume));
2438 osi_Assert(vp != NULL);
2439 vp->hashid = volumeId;
2440 vp->device = partp->device;
2441 vp->partition = partp;
2442 queue_Init(&vp->vnode_list);
2443 queue_Init(&vp->rx_call_list);
2444 #ifdef AFS_DEMAND_ATTACH_FS
2445 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2446 #endif /* AFS_DEMAND_ATTACH_FS */
2449 /* attach2 is entered without any locks, and returns
2450 * with vol_glock_mutex held */
2451 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2453 if (VCanUseFSSYNC() && vp) {
2454 #ifdef AFS_DEMAND_ATTACH_FS
2455 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2456 /* mark volume header as in use so that volser crashes lead to a
2457 * salvage attempt */
2458 VUpdateVolume_r(ec, vp, 0);
2460 /* for dafs, we should tell the fileserver, except for V_PEEK
2461 * where we know it is not necessary */
2462 if (mode == V_PEEK) {
2463 vp->needsPutBack = 0;
2465 vp->needsPutBack = VOL_PUTBACK;
2467 #else /* !AFS_DEMAND_ATTACH_FS */
2468 /* duplicate computation in fssync.c about whether the server
2469 * takes the volume offline or not. If the volume isn't
2470 * offline, we must not return it when we detach the volume,
2471 * or the server will abort */
2472 if (mode == V_READONLY || mode == V_PEEK
2473 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2474 vp->needsPutBack = 0;
2476 vp->needsPutBack = VOL_PUTBACK;
2477 #endif /* !AFS_DEMAND_ATTACH_FS */
2479 #ifdef FSSYNC_BUILD_CLIENT
2480 /* Only give back the vol to the fileserver if we checked it out; attach2
2481 * will set checkedOut only if we successfully checked it out from the
2483 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2485 #ifdef AFS_DEMAND_ATTACH_FS
2486 /* If we couldn't attach but we scheduled a salvage, we already
2487 * notified the fileserver; don't online it now */
2488 if (*ec != VSALVAGING)
2489 #endif /* AFS_DEMAND_ATTACH_FS */
2490 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2493 if (programType == fileServer && vp) {
2494 #ifdef AFS_DEMAND_ATTACH_FS
2496 * we can get here in cases where we don't "own"
2497 * the volume (e.g. volume owned by a utility).
2498 * short circuit around potential disk header races.
2500 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2504 VUpdateVolume_r(ec, vp, 0);
2506 Log("VAttachVolume: Error updating volume\n");
2511 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2512 #ifndef AFS_DEMAND_ATTACH_FS
2513 /* This is a hack: by temporarily setting the incore
2514 * dontSalvage flag ON, the volume will be put back on the
2515 * Update list (with dontSalvage OFF again). It will then
2516 * come back in N minutes with DONT_SALVAGE eventually
2517 * set. This is the way that volumes that have never had
2518 * it set get it set; or that volumes that have been
2519 * offline without DONT SALVAGE having been set also
2520 * eventually get it set */
2521 V_dontSalvage(vp) = DONT_SALVAGE;
2522 #endif /* !AFS_DEMAND_ATTACH_FS */
2523 VAddToVolumeUpdateList_r(ec, vp);
2525 Log("VAttachVolume: Error adding volume to update list\n");
2532 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2537 if (VRequiresPartLock()) {
2538 VUnlockPartition_r(partition);
2541 #ifdef AFS_DEMAND_ATTACH_FS
2542 /* attach failed; make sure we're in error state */
2543 if (vp && !VIsErrorState(V_attachState(vp))) {
2544 VChangeState_r(vp, VOL_STATE_ERROR);
2546 #endif /* AFS_DEMAND_ATTACH_FS */
2553 #ifdef AFS_DEMAND_ATTACH_FS
2554 /* VAttachVolumeByVp_r
2556 * finish attaching a volume that is
2557 * in a less than fully attached state
2559 /* caller MUST hold a ref count on vp */
2561 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2563 char name[VMAXPATHLEN];
2565 struct DiskPartition64 *partp;
2569 Volume * nvp = NULL;
2570 VolumeStats stats_save;
2574 /* volume utility should never call AttachByVp */
2575 osi_Assert(programType == fileServer);
2577 volumeId = vp->hashid;
2578 partp = vp->partition;
2579 VolumeExternalName_r(volumeId, name, sizeof(name));
2582 /* if another thread is performing a blocking op, wait */
2583 VWaitExclusiveState_r(vp);
2585 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2587 /* if it's already attached, see if we can return it */
2588 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2589 VGetVolumeByVp_r(ec, vp);
2590 if (V_inUse(vp) == fileServer) {
2593 if (vp->specialStatus == VBUSY)
2595 VDetachVolume_r(ec, vp);
2597 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2603 /* pre-attach volume if it hasn't been done yet */
2605 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2606 (V_attachState(vp) == VOL_STATE_DELETED) ||
2607 (V_attachState(vp) == VOL_STATE_ERROR)) {
2608 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2614 VCreateReservation_r(nvp);
2619 osi_Assert(vp != NULL);
2620 VChangeState_r(vp, VOL_STATE_ATTACHING);
2622 /* restore monotonically increasing stats */
2623 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2627 /* compute path to disk header */
2628 strcpy(path, VPartitionPath(partp));
2632 strcat(path, OS_DIRSEP);
2637 * NOTE: attach2 is entered without any locks, and returns
2638 * with vol_glock_mutex held */
2639 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2642 * the event that an error was encountered, or
2643 * the volume was not brought to an attached state
2644 * for any reason, skip to the end. We cannot
2645 * safely call VUpdateVolume unless we "own" it.
2649 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2653 VUpdateVolume_r(ec, vp, 0);
2655 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2659 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2660 #ifndef AFS_DEMAND_ATTACH_FS
2661 /* This is a hack: by temporarily setting the incore
2662 * dontSalvage flag ON, the volume will be put back on the
2663 * Update list (with dontSalvage OFF again). It will then
2664 * come back in N minutes with DONT_SALVAGE eventually
2665 * set. This is the way that volumes that have never had
2666 * it set get it set; or that volumes that have been
2667 * offline without DONT SALVAGE having been set also
2668 * eventually get it set */
2669 V_dontSalvage(vp) = DONT_SALVAGE;
2670 #endif /* !AFS_DEMAND_ATTACH_FS */
2671 VAddToVolumeUpdateList_r(ec, vp);
2673 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2680 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2684 VCancelReservation_r(nvp);
2687 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2688 if (vp && !VIsErrorState(V_attachState(vp))) {
2689 VChangeState_r(vp, VOL_STATE_ERROR);
2698 * lock a volume on disk (non-blocking).
2700 * @param[in] vp The volume to lock
2701 * @param[in] locktype READ_LOCK or WRITE_LOCK
2703 * @return operation status
2704 * @retval 0 success, lock was obtained
2705 * @retval EBUSY a conflicting lock was held by another process
2706 * @retval EIO error acquiring lock
2708 * @pre If we're in the fileserver, vp is in an exclusive state
2710 * @pre vp is not already locked
2713 VLockVolumeNB(Volume *vp, int locktype)
2717 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2718 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2720 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2722 V_attachFlags(vp) |= VOL_LOCKED;
2729 * unlock a volume on disk that was locked with VLockVolumeNB.
2731 * @param[in] vp volume to unlock
2733 * @pre If we're in the fileserver, vp is in an exclusive state
2735 * @pre vp has already been locked
2738 VUnlockVolume(Volume *vp)
2740 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2741 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2743 VUnlockVolumeById(vp->hashid, vp->partition);
2745 V_attachFlags(vp) &= ~VOL_LOCKED;
2747 #endif /* AFS_DEMAND_ATTACH_FS */
2750 * read in a vol header, possibly lock the vol header, and possibly check out
2751 * the vol header from the fileserver, as part of volume attachment.
2753 * @param[out] ec error code
2754 * @param[in] vp volume pointer object
2755 * @param[in] partp disk partition object of the attaching partition
2756 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2758 * @param[in] peek 1 to just try to read in the volume header and make sure
2759 * we don't try to lock the vol, or check it out from
2760 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2762 * @param[out] acheckedOut If we successfully checked-out the volume from
2763 * the fileserver (if we needed to), this is set
2764 * to 1, otherwise it is untouched.
2766 * @note As part of DAFS volume attachment, the volume header may be either
2767 * read- or write-locked to ensure mutual exclusion of certain volume
2768 * operations. In some cases in order to determine whether we need to
2769 * read- or write-lock the header, we need to read in the header to see
2770 * if the volume is RW or not. So, if we read in the header under a
2771 * read-lock and determine that we actually need a write-lock on the
2772 * volume header, this function will drop the read lock, acquire a write
2773 * lock, and read the header in again.
2776 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2777 int mode, int peek, int *acheckedOut)
2779 struct VolumeDiskHeader diskHeader;
2780 struct VolumeHeader header;
2783 int lock_tries = 0, checkout_tries = 0;
2785 VolumeId volid = vp->hashid;
2786 #ifdef FSSYNC_BUILD_CLIENT
2787 int checkout, done_checkout = 0;
2788 #endif /* FSSYNC_BUILD_CLIENT */
2789 #ifdef AFS_DEMAND_ATTACH_FS
2790 int locktype = 0, use_locktype = -1;
2791 #endif /* AFS_DEMAND_ATTACH_FS */
2797 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2798 Log("VAttachVolume: retried too many times trying to lock header for "
2799 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2800 VPartitionPath(partp));
2804 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2805 Log("VAttachVolume: retried too many times trying to checkout "
2806 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2807 VPartitionPath(partp));
2812 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2813 /* short-circuit the 'volume does not exist' case */
2818 #ifdef FSSYNC_BUILD_CLIENT
2819 checkout = !done_checkout;
2821 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2823 memset(&res, 0, sizeof(res));
2825 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2828 if (res.hdr.reason == FSYNC_SALVAGE) {
2829 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2830 afs_printable_uint32_lu(volid));
2833 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2834 afs_printable_uint32_lu(volid));
2835 *ec = VNOVOL; /* XXXX */
2843 #ifdef AFS_DEMAND_ATTACH_FS
2844 if (use_locktype < 0) {
2845 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2846 * if it turns out to be RW */
2847 locktype = VVolLockType(mode, 0);
2850 /* a previous try says we should use use_locktype to lock the volume,
2852 locktype = use_locktype;
2855 if (!peek && locktype) {
2856 code = VLockVolumeNB(vp, locktype);
2858 if (code == EBUSY) {
2859 Log("VAttachVolume: another program has vol %lu locked\n",
2860 afs_printable_uint32_lu(volid));
2862 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2863 code, afs_printable_uint32_lu(volid));
2870 #endif /* AFS_DEMAND_ATTACH_FS */
2872 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2882 DiskToVolumeHeader(&header, &diskHeader);
2884 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2885 header.largeVnodeIndex);
2886 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2887 header.smallVnodeIndex);
2888 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2890 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2893 /* only need to do this once */
2895 GetVolumeHeader(vp);
2899 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2900 /* demand attach changes the V_PEEK mechanism
2902 * we can now suck the current disk data structure over
2903 * the fssync interface without going to disk
2905 * (technically, we don't need to restrict this feature
2906 * to demand attach fileservers. However, I'm trying
2907 * to limit the number of common code changes)
2909 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2911 res.payload.len = sizeof(VolumeDiskData);
2912 res.payload.buf = &vp->header->diskstuff;
2914 if (FSYNC_VolOp(vp->hashid,
2916 FSYNC_VOL_QUERY_HDR,
2919 goto disk_header_loaded;
2922 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2923 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2924 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2926 #ifdef AFS_DEMAND_ATTACH_FS
2929 IncUInt64(&VStats.hdr_loads);
2930 IncUInt64(&vp->stats.hdr_loads);
2932 #endif /* AFS_DEMAND_ATTACH_FS */
2935 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2936 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2940 #ifdef AFS_DEMAND_ATTACH_FS
2941 # ifdef FSSYNC_BUILD_CLIENT
2943 # endif /* FSSYNC_BUILD_CLIENT */
2945 /* if the lock type we actually used to lock the volume is different than
2946 * the lock type we should have used, retry with the lock type we should
2948 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2949 if (locktype != use_locktype) {
2953 #endif /* AFS_DEMAND_ATTACH_FS */
2958 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2959 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2961 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2963 if (code == SYNC_DENIED) {
2964 /* must retry checkout; fileserver no longer thinks we have
2970 } else if (code != SYNC_OK) {
2974 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2977 /* either we are going to be called again for a second pass, or we
2978 * encountered an error; clean up in either case */
2980 #ifdef AFS_DEMAND_ATTACH_FS
2981 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2984 #endif /* AFS_DEMAND_ATTACH_FS */
2985 if (vp->linkHandle) {
2986 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2987 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2988 IH_RELEASE(vp->diskDataHandle);
2989 IH_RELEASE(vp->linkHandle);
3002 #ifdef AFS_DEMAND_ATTACH_FS
3004 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3005 Volume *vp, int *acheckedOut)
3009 if (vp->pending_vol_op) {
3013 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3015 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3017 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3018 } else if (code == 0) {
3019 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3022 /* we need the vol header to determine if the volume can be
3023 * left online for the vop, so... get the header */
3027 /* attach header with peek=1 to avoid checking out the volume
3028 * or locking it; we just want the header info, we're not
3029 * messing with the volume itself at all */
3030 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3037 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3038 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3040 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3043 /* make sure we grab a new vol header and re-open stuff on
3044 * actual attachment; we can't keep the data we grabbed, since
3045 * it was not done under a lock and thus not safe */
3046 FreeVolumeHeader(vp);
3047 VReleaseVolumeHandles_r(vp);
3050 /* see if the pending volume op requires exclusive access */
3051 switch (vp->pending_vol_op->vol_op_state) {
3052 case FSSYNC_VolOpPending:
3053 /* this should never happen */
3054 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3057 case FSSYNC_VolOpRunningUnknown:
3058 /* this should never happen; we resolved 'unknown' above */
3059 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3062 case FSSYNC_VolOpRunningOffline:
3063 /* mark the volume down */
3065 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3067 /* do not set V_offlineMessage here; we don't have ownership of
3068 * the volume (and probably do not have the header loaded), so we
3069 * can't alter the disk header */
3071 /* check to see if we should set the specialStatus flag */
3072 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3073 vp->specialStatus = VBUSY;
3084 #endif /* AFS_DEMAND_ATTACH_FS */
3087 * volume attachment helper function.
3089 * @param[out] ec error code
3090 * @param[in] volumeId volume ID of the attaching volume
3091 * @param[in] path full path to the volume header .vol file
3092 * @param[in] partp disk partition object for the attaching partition
3093 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3094 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3095 * DAFS) should already be initialized
3096 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3097 * if there is a volume operation running for this volume
3098 * that should set the volume to VBUSY during its run. 0
3099 * otherwise. (see VVolOpSetVBusy_r)
3100 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3102 * @param[out] acheckedOut If we successfully checked-out the volume from
3103 * the fileserver (if we needed to), this is set
3104 * to 1, otherwise it is 0.
3106 * @return pointer to the semi-attached volume pointer
3107 * @retval NULL an error occurred (check value of *ec)
3108 * @retval vp volume successfully attaching
3110 * @pre no locks held
3112 * @post VOL_LOCK held
3115 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3116 Volume * vp, int isbusy, int mode, int *acheckedOut)
3118 /* have we read in the header successfully? */
3119 int read_header = 0;
3121 #ifdef AFS_DEMAND_ATTACH_FS
3122 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3126 /* in the case of an error, to what state should the volume be
3128 VolState error_state = VOL_STATE_ERROR;
3129 #endif /* AFS_DEMAND_ATTACH_FS */
3133 vp->vnodeIndex[vLarge].handle = NULL;
3134 vp->vnodeIndex[vSmall].handle = NULL;
3135 vp->diskDataHandle = NULL;
3136 vp->linkHandle = NULL;
3140 #ifdef AFS_DEMAND_ATTACH_FS
3141 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3143 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3146 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3147 #endif /* !AFS_DEMAND_ATTACH_FS */
3149 if (*ec == VNOVOL) {
3150 /* if the volume doesn't exist, skip straight to 'error' so we don't
3151 * request a salvage */
3152 goto unlocked_error;
3158 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3159 vp->shuttingDown = 0;
3160 vp->goingOffline = 0;
3162 #ifdef AFS_DEMAND_ATTACH_FS
3163 vp->stats.last_attach = FT_ApproxTime();
3164 vp->stats.attaches++;
3168 IncUInt64(&VStats.attaches);
3169 vp->cacheCheck = ++VolumeCacheCheck;
3170 /* just in case this ever rolls over */
3171 if (!vp->cacheCheck)
3172 vp->cacheCheck = ++VolumeCacheCheck;
3175 #ifdef AFS_DEMAND_ATTACH_FS
3176 V_attachFlags(vp) |= VOL_HDR_LOADED;
3177 vp->stats.last_hdr_load = vp->stats.last_attach;
3178 #endif /* AFS_DEMAND_ATTACH_FS */
3182 struct IndexFileHeader iHead;
3184 #if OPENAFS_VOL_STATS
3186 * We just read in the diskstuff part of the header. If the detailed
3187 * volume stats area has not yet been initialized, we should bzero the
3188 * area and mark it as initialized.
3190 if (!(V_stat_initialized(vp))) {
3191 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3192 V_stat_initialized(vp) = 1;
3194 #endif /* OPENAFS_VOL_STATS */
3196 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3197 (char *)&iHead, sizeof(iHead),
3198 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3201 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3206 struct IndexFileHeader iHead;
3208 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3209 (char *)&iHead, sizeof(iHead),
3210 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3213 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3217 #ifdef AFS_NAMEI_ENV
3219 struct versionStamp stamp;
3221 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3222 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3225 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3228 #endif /* AFS_NAMEI_ENV */
3230 #if defined(AFS_DEMAND_ATTACH_FS)
3231 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3233 if (!VCanScheduleSalvage()) {
3234 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3236 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3237 VOL_SALVAGE_NO_OFFLINE);
3242 /* volume operation in progress */
3243 goto unlocked_error;
3245 #else /* AFS_DEMAND_ATTACH_FS */
3247 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3248 goto unlocked_error;
3250 #endif /* AFS_DEMAND_ATTACH_FS */
3252 if (V_needsSalvaged(vp)) {
3253 if (vp->specialStatus)
3254 vp->specialStatus = 0;
3256 #if defined(AFS_DEMAND_ATTACH_FS)
3257 if (!VCanScheduleSalvage()) {
3258 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3260 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3261 VOL_SALVAGE_NO_OFFLINE);
3264 #else /* AFS_DEMAND_ATTACH_FS */
3266 #endif /* AFS_DEMAND_ATTACH_FS */
3272 vp->nextVnodeUnique = V_uniquifier(vp);
3274 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3275 if (!V_needsSalvaged(vp)) {
3276 V_needsSalvaged(vp) = 1;
3277 VUpdateVolume_r(ec, vp, 0);
3279 #if defined(AFS_DEMAND_ATTACH_FS)
3280 if (!VCanScheduleSalvage()) {
3281 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3283 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3284 VOL_SALVAGE_NO_OFFLINE);
3287 #else /* AFS_DEMAND_ATTACH_FS */
3288 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3290 #endif /* AFS_DEMAND_ATTACH_FS */
3295 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3296 /* Only check destroyMe if we are the fileserver, since the
3297 * volserver et al sometimes need to work with volumes with
3298 * destroyMe set. Examples are 'temporary' volumes the
3299 * volserver creates, and when we create a volume (destroyMe
3300 * is set on creation; sometimes a separate volserver
3301 * transaction is created to clear destroyMe).
3304 #if defined(AFS_DEMAND_ATTACH_FS)
3305 /* schedule a salvage so the volume goes away on disk */
3306 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3307 VOL_SALVAGE_NO_OFFLINE);
3308 VChangeState_r(vp, VOL_STATE_ERROR);
3311 #endif /* AFS_DEMAND_ATTACH_FS */
3312 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3317 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3318 #ifndef BITMAP_LATER
3319 if (programType == fileServer && VolumeWriteable(vp)) {
3321 for (i = 0; i < nVNODECLASSES; i++) {
3322 VGetBitmap_r(ec, vp, i);
3324 #ifdef AFS_DEMAND_ATTACH_FS
3325 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3326 VOL_SALVAGE_NO_OFFLINE);
3328 #endif /* AFS_DEMAND_ATTACH_FS */
3329 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3335 #endif /* BITMAP_LATER */
3337 if (VInit >= 2 && V_needsCallback(vp)) {
3338 if (V_BreakVolumeCallbacks) {
3339 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3340 afs_printable_uint32_lu(V_id(vp)));
3341 V_needsCallback(vp) = 0;
3343 (*V_BreakVolumeCallbacks) (V_id(vp));
3346 VUpdateVolume_r(ec, vp, 0);
3348 #ifdef FSSYNC_BUILD_CLIENT
3349 else if (VCanUseFSSYNC()) {
3350 afs_int32 fsync_code;
3352 V_needsCallback(vp) = 0;
3354 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3358 V_needsCallback(vp) = 1;
3359 Log("Error trying to tell the fileserver to break callbacks for "
3360 "changed volume %lu; error code %ld\n",
3361 afs_printable_uint32_lu(V_id(vp)),
3362 afs_printable_int32_ld(fsync_code));
3364 VUpdateVolume_r(ec, vp, 0);
3367 #endif /* FSSYNC_BUILD_CLIENT */
3370 Log("VAttachVolume: error %d clearing needsCallback on volume "
3371 "%lu; needs salvage\n", (int)*ec,
3372 afs_printable_uint32_lu(V_id(vp)));
3373 #ifdef AFS_DEMAND_ATTACH_FS
3374 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3375 VOL_SALVAGE_NO_OFFLINE);
3377 #else /* !AFS_DEMAND_ATTACH_FS */
3379 #endif /* !AFS_DEMAND_ATTACh_FS */
3384 if (programType == fileServer) {
3385 if (vp->specialStatus)
3386 vp->specialStatus = 0;
3387 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3388 V_inUse(vp) = fileServer;
3389 V_offlineMessage(vp)[0] = '\0';
3393 #ifdef AFS_DEMAND_ATTACH_FS
3394 /* Put the vol into PREATTACHED state, so if someone tries to
3395 * access it again, we try to attach, see that we're not blessed,
3396 * and give a VNOVOL error again. Putting it into UNATTACHED state
3397 * would result in a VOFFLINE error instead. */
3398 error_state = VOL_STATE_PREATTACHED;
3399 #endif /* AFS_DEMAND_ATTACH_FS */
3401 /* mimic e.g. GetVolume errors */
3402 if (!V_blessed(vp)) {
3403 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3404 FreeVolumeHeader(vp);
3405 } else if (!V_inService(vp)) {
3406 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3407 FreeVolumeHeader(vp);
3409 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3411 #ifdef AFS_DEMAND_ATTACH_FS
3412 error_state = VOL_STATE_ERROR;
3413 /* see if we can recover */
3414 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3417 #ifdef AFS_DEMAND_ATTACH_FS
3423 #ifdef AFS_DEMAND_ATTACH_FS
3424 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3425 V_inUse(vp) = programType;
3426 #endif /* AFS_DEMAND_ATTACH_FS */
3427 V_checkoutMode(vp) = mode;
3430 AddVolumeToHashTable(vp, V_id(vp));
3431 #ifdef AFS_DEMAND_ATTACH_FS
3432 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3435 if ((programType != fileServer) ||
3436 (V_inUse(vp) == fileServer)) {
3437 AddVolumeToVByPList_r(vp);
3439 VChangeState_r(vp, VOL_STATE_ATTACHED);
3441 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3450 #ifdef AFS_DEMAND_ATTACH_FS
3451 if (!VIsErrorState(V_attachState(vp))) {
3452 VChangeState_r(vp, error_state);
3454 #endif /* AFS_DEMAND_ATTACH_FS */
3457 VReleaseVolumeHandles_r(vp);
3460 #ifdef AFS_DEMAND_ATTACH_FS
3467 #else /* !AFS_DEMAND_ATTACH_FS */
3469 #endif /* !AFS_DEMAND_ATTACH_FS */
3473 /* Attach an existing volume.
3474 The volume also normally goes online at this time.
3475 An offline volume must be reattached to make it go online.
3479 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3483 retVal = VAttachVolume_r(ec, volumeId, mode);
3489 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3492 VGetVolumePath(ec, volumeId, &part, &name);
3496 vp = VGetVolume_r(&error, volumeId);
3498 osi_Assert(V_inUse(vp) == 0);
3499 VDetachVolume_r(ec, vp);
3503 return VAttachVolumeByName_r(ec, part, name, mode);
3506 /* Increment a reference count to a volume, sans context swaps. Requires
3507 * possibly reading the volume header in from the disk, since there's
3508 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3510 * N.B. This call can fail if we can't read in the header!! In this case
3511 * we still guarantee we won't context swap, but the ref count won't be
3512 * incremented (otherwise we'd violate the invariant).
3514 /* NOTE: with the demand attach fileserver extensions, the global lock
3515 * is dropped within VHold */
3516 #ifdef AFS_DEMAND_ATTACH_FS
3518 VHold_r(Volume * vp)
3522 VCreateReservation_r(vp);
3523 VWaitExclusiveState_r(vp);
3525 LoadVolumeHeader(&error, vp);
3527 VCancelReservation_r(vp);
3531 VCancelReservation_r(vp);
3534 #else /* AFS_DEMAND_ATTACH_FS */
3536 VHold_r(Volume * vp)
3540 LoadVolumeHeader(&error, vp);
3546 #endif /* AFS_DEMAND_ATTACH_FS */
3548 /**** volume timeout-related stuff ****/
3550 #ifdef AFS_PTHREAD_ENV
3552 static struct timespec *shutdown_timeout;
3553 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3556 VTimedOut(const struct timespec *ts)
3561 if (ts->tv_sec == 0) {
3562 /* short-circuit; this will have always timed out */
3566 code = gettimeofday(&tv, NULL);
3568 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3569 /* assume no timeout; failure mode is we just wait longer than normal
3570 * instead of returning errors when we shouldn't */
3574 if (tv.tv_sec < ts->tv_sec ||
3575 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3584 * Calculate an absolute timeout.
3586 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3587 * NULL, the memory is not touched
3588 * @param[in] timeout How long the timeout should be from now
3590 * @return timeout to use
3591 * @retval NULL no timeout; wait forever
3592 * @retval non-NULL the given value for "ts"
3596 static struct timespec *
3597 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3607 ts->tv_sec = ts->tv_nsec = 0;
3611 code = gettimeofday(&now, NULL);
3613 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3617 ts->tv_sec = now.tv_sec + timeout;
3618 ts->tv_nsec = now.tv_usec * 1000;
3624 * Initialize the shutdown_timeout global.
3627 VShutdownTimeoutInit(void)
3629 struct timespec *ts;
3631 ts = malloc(sizeof(*ts));
3633 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3635 if (!shutdown_timeout) {
3641 * Figure out the timeout that should be used for waiting for offline volumes.
3643 * @param[out] ats Storage space for a local timeout value if needed
3645 * @return The timeout value that should be used
3646 * @retval NULL No timeout; wait forever for offlining volumes
3647 * @retval non-NULL A pointer to the absolute time that should be used as
3648 * the deadline for waiting for offlining volumes.
3650 * @note If we return non-NULL, the pointer we return may or may not be the
3653 static const struct timespec *
3654 VOfflineTimeout(struct timespec *ats)
3656 if (vol_shutting_down) {
3657 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3658 return shutdown_timeout;
3660 return VCalcTimeout(ats, vol_opts.offline_timeout);
3664 #else /* AFS_PTHREAD_ENV */
3666 /* Waiting a certain amount of time for offlining volumes is not supported
3667 * for LWP due to a lack of primitives. So, we never time out */
3668 # define VTimedOut(x) (0)
3669 # define VOfflineTimeout(x) (NULL)
3671 #endif /* !AFS_PTHREAD_ENV */
3679 retVal = VHold_r(vp);
3686 VIsGoingOffline_r(struct Volume *vp)
3690 if (vp->goingOffline) {
3691 if (vp->specialStatus) {
3692 code = vp->specialStatus;
3693 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3704 * Tell the caller if a volume is waiting to go offline.
3706 * @param[in] vp The volume we want to know about
3708 * @return volume status
3709 * @retval 0 volume is not waiting to go offline, go ahead and use it
3710 * @retval nonzero volume is waiting to offline, and give the returned code
3711 * as an error to anyone accessing the volume
3713 * @pre VOL_LOCK is NOT held
3714 * @pre caller holds a heavyweight reference on vp
3717 VIsGoingOffline(struct Volume *vp)
3722 code = VIsGoingOffline_r(vp);
3729 * Register an RX call with a volume.
3731 * @param[inout] ec Error code; if unset when passed in, may be set if
3732 * the volume starts going offline
3733 * @param[out] client_ec @see GetVolume
3734 * @param[in] vp Volume struct
3735 * @param[in] cbv VCallByVol struct containing the RX call to register
3737 * @pre VOL_LOCK held
3738 * @pre caller holds heavy ref on vp
3743 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3746 #ifdef AFS_DEMAND_ATTACH_FS
3748 /* just in case the volume started going offline after we got the
3749 * reference to it... otherwise, if the volume started going
3750 * offline right at the end of GetVolume(), we might race with the
3751 * RX call scanner, and return success and add our cbv to the
3752 * rx_call_list _after_ the scanner has scanned the list. */
3753 *ec = VIsGoingOffline_r(vp);
3759 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3760 VWaitStateChange_r(vp);
3762 #endif /* AFS_DEMAND_ATTACH_FS */
3764 queue_Prepend(&vp->rx_call_list, cbv);
3769 * Deregister an RX call with a volume.
3771 * @param[in] vp Volume struct
3772 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3774 * @pre VOL_LOCK held
3775 * @pre caller holds heavy ref on vp
3780 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3782 if (cbv && queue_IsOnQueue(cbv)) {
3783 #ifdef AFS_DEMAND_ATTACH_FS
3784 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3785 VWaitStateChange_r(vp);
3787 #endif /* AFS_DEMAND_ATTACH_FS */
3793 /***************************************************/
3794 /* get and put volume routines */
3795 /***************************************************/
3798 * put back a heavyweight reference to a volume object.
3800 * @param[in] vp volume object pointer
3802 * @pre VOL_LOCK held
3804 * @post heavyweight volume reference put back.
3805 * depending on state, volume may have been taken offline,
3806 * detached, salvaged, freed, etc.
3808 * @internal volume package internal use only
3811 VPutVolume_r(Volume * vp)
3813 osi_Assert(--vp->nUsers >= 0);
3814 if (vp->nUsers == 0) {