2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
9 * Portions Copyright (c) 2005-2008 Sine Nomine Associates
12 /* 1/1/89: NB: this stuff is all going to be replaced. Don't take it too seriously */
17 Institution: The Information Technology Center, Carnegie-Mellon University
21 #include <afsconfig.h>
22 #include <afs/param.h>
30 #ifdef HAVE_SYS_FILE_H
35 #include <afs/afsint.h>
38 #if !defined(AFS_SGI_ENV)
41 #else /* AFS_OSF_ENV */
42 #ifdef AFS_VFSINCL_ENV
45 #include <sys/fs/ufs_fs.h>
47 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
48 #include <ufs/ufs/dinode.h>
49 #include <ufs/ffs/fs.h>
54 #else /* AFS_VFSINCL_ENV */
55 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
58 #endif /* AFS_VFSINCL_ENV */
59 #endif /* AFS_OSF_ENV */
60 #endif /* AFS_SGI_ENV */
61 #endif /* !AFS_NT40_ENV */
69 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
71 #include <sys/mnttab.h>
72 #include <sys/mntent.h>
78 #if defined(AFS_SGI_ENV)
81 #ifndef AFS_LINUX20_ENV
82 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
85 #endif /* AFS_SGI_ENV */
87 #endif /* AFS_HPUX_ENV */
91 #include <afs/errors.h>
94 #include <afs/afssyscalls.h>
96 #include <afs/afsutil.h>
97 #include "daemon_com.h"
102 #include "partition.h"
103 #include "volume_inline.h"
108 #ifdef AFS_PTHREAD_ENV
109 pthread_mutex_t vol_glock_mutex;
110 pthread_mutex_t vol_trans_mutex;
111 pthread_cond_t vol_put_volume_cond;
112 pthread_cond_t vol_sleep_cond;
113 pthread_cond_t vol_init_attach_cond;
114 pthread_cond_t vol_vinit_cond;
115 int vol_attach_threads = 1;
116 #endif /* AFS_PTHREAD_ENV */
118 /* start-time configurable I/O parameters */
119 ih_init_params vol_io_params;
121 #ifdef AFS_DEMAND_ATTACH_FS
122 pthread_mutex_t vol_salvsync_mutex;
125 * Set this to 1 to disallow SALVSYNC communication in all threads; used
126 * during shutdown, since the salvageserver may have gone away.
128 static volatile sig_atomic_t vol_disallow_salvsync = 0;
129 #endif /* AFS_DEMAND_ATTACH_FS */
132 * has VShutdown_r been called / is VShutdown_r running?
134 static int vol_shutting_down = 0;
137 extern void *calloc(), *realloc();
140 /* Forward declarations */
141 static Volume *attach2(Error * ec, VolId volumeId, char *path,
142 struct DiskPartition64 *partp, Volume * vp,
143 int isbusy, int mode, int *acheckedOut);
144 static void ReallyFreeVolume(Volume * vp);
145 #ifdef AFS_DEMAND_ATTACH_FS
146 static void FreeVolume(Volume * vp);
147 #else /* !AFS_DEMAND_ATTACH_FS */
148 #define FreeVolume(vp) ReallyFreeVolume(vp)
149 static void VScanUpdateList(void);
150 #endif /* !AFS_DEMAND_ATTACH_FS */
151 static void VInitVolumeHeaderCache(afs_uint32 howMany);
152 static int GetVolumeHeader(Volume * vp);
153 static void ReleaseVolumeHeader(struct volHeader *hd);
154 static void FreeVolumeHeader(Volume * vp);
155 static void AddVolumeToHashTable(Volume * vp, int hashid);
156 static void DeleteVolumeFromHashTable(Volume * vp);
158 static int VHold(Volume * vp);
160 static int VHold_r(Volume * vp);
161 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
162 static void VReleaseVolumeHandles_r(Volume * vp);
163 static void VCloseVolumeHandles_r(Volume * vp);
164 static void LoadVolumeHeader(Error * ec, Volume * vp);
165 static int VCheckOffline(Volume * vp);
166 static int VCheckDetach(Volume * vp);
167 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
168 Volume * hint, const struct timespec *ts);
170 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
171 * defined when not linked with vice, XXXX */
172 ProgramType programType; /* The type of program using the package */
173 static VolumePackageOptions vol_opts;
175 /* extended volume package statistics */
178 #ifdef VOL_LOCK_DEBUG
179 pthread_t vol_glock_holder = 0;
183 /* this parameter needs to be tunable at runtime.
184 * 128 was really inadequate for largish servers -- at 16384 volumes this
185 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
186 * talk about bad spatial locality...
188 * an AVL or splay tree might work a lot better, but we'll just increase
189 * the default hash table size for now
191 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
192 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
193 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
196 * turn volume hash chains into partially ordered lists.
197 * when the threshold is exceeded between two adjacent elements,
198 * perform a chain rebalancing operation.
200 * keep the threshold high in order to keep cache line invalidates
201 * low "enough" on SMPs
203 #define VOLUME_HASH_REORDER_THRESHOLD 200
206 * when possible, don't just reorder single elements, but reorder
207 * entire chains of elements at once. a chain of elements that
208 * exceed the element previous to the pivot by at least CHAIN_THRESH
209 * accesses are moved in front of the chain whose elements have at
210 * least CHAIN_THRESH less accesses than the pivot element
212 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
214 #include "rx/rx_queue.h"
217 VolumeHashTable_t VolumeHashTable = {
218 DEFAULT_VOLUME_HASH_SIZE,
219 DEFAULT_VOLUME_HASH_MASK,
224 static void VInitVolumeHash(void);
228 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
232 afs_int32 ffs_tmp = x;
236 for (ffs_i = 1;; ffs_i++) {
243 #endif /* !AFS_HAVE_FFS */
245 #ifdef AFS_PTHREAD_ENV
247 * disk partition queue element
249 typedef struct diskpartition_queue_t {
250 struct rx_queue queue; /**< queue header */
251 struct DiskPartition64 *diskP; /**< disk partition table entry */
252 } diskpartition_queue_t;
254 #ifndef AFS_DEMAND_ATTACH_FS
256 typedef struct vinitvolumepackage_thread_t {
257 struct rx_queue queue;
258 pthread_cond_t thread_done_cv;
259 int n_threads_complete;
260 } vinitvolumepackage_thread_t;
261 static void * VInitVolumePackageThread(void * args);
263 #else /* !AFS_DEMAND_ATTTACH_FS */
264 #define VINIT_BATCH_MAX_SIZE 512
267 * disk partition work queue
269 struct partition_queue {
270 struct rx_queue head; /**< diskpartition_queue_t queue */
271 pthread_mutex_t mutex;
276 * volumes parameters for preattach
278 struct volume_init_batch {
279 struct rx_queue queue; /**< queue header */
280 int thread; /**< posting worker thread */
281 int last; /**< indicates thread is done */
282 int size; /**< number of volume ids in batch */
283 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
287 * volume parameters work queue
289 struct volume_init_queue {
290 struct rx_queue head; /**< volume_init_batch queue */
291 pthread_mutex_t mutex;
296 * volume init worker thread parameters
298 struct vinitvolumepackage_thread_param {
299 int nthreads; /**< total number of worker threads */
300 int thread; /**< thread number for this worker thread */
301 struct partition_queue *pq; /**< queue partitions to scan */
302 struct volume_init_queue *vq; /**< queue of volume to preattach */
305 static void *VInitVolumePackageThread(void *args);
306 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
307 static VolId VInitNextVolumeId(DIR *dirp);
308 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
310 #endif /* !AFS_DEMAND_ATTACH_FS */
311 #endif /* AFS_PTHREAD_ENV */
313 #ifndef AFS_DEMAND_ATTACH_FS
314 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
315 int * nAttached, int * nUnattached);
316 #endif /* AFS_DEMAND_ATTACH_FS */
319 #ifdef AFS_DEMAND_ATTACH_FS
320 /* demand attach fileserver extensions */
323 * in the future we will support serialization of VLRU state into the fs_state
326 * these structures are the beginning of that effort
328 struct VLRU_DiskHeader {
329 struct versionStamp stamp; /* magic and structure version number */
330 afs_uint32 mtime; /* time of dump to disk */
331 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
334 struct VLRU_DiskEntry {
335 afs_uint32 vid; /* volume ID */
336 afs_uint32 idx; /* generation */
337 afs_uint32 last_get; /* timestamp of last get */
340 struct VLRU_StartupQueue {
341 struct VLRU_DiskEntry * entry;
346 typedef struct vshutdown_thread_t {
348 pthread_mutex_t lock;
350 pthread_cond_t master_cv;
352 int n_threads_complete;
354 int schedule_version;
357 byte n_parts_done_pass;
358 byte part_thread_target[VOLMAXPARTS+1];
359 byte part_done_pass[VOLMAXPARTS+1];
360 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
361 int stats[4][VOLMAXPARTS+1];
362 } vshutdown_thread_t;
363 static void * VShutdownThread(void * args);
366 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
367 static int VCheckFree(Volume * vp);
370 static void AddVolumeToVByPList_r(Volume * vp);
371 static void DeleteVolumeFromVByPList_r(Volume * vp);
372 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
373 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
374 static void VVByPListWait_r(struct DiskPartition64 * dp);
376 /* online salvager */
377 static int VCheckSalvage(Volume * vp);
378 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
379 static int VScheduleSalvage_r(Volume * vp);
382 /* Volume hash table */
383 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
384 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
385 static void VHashEndExclusive_r(VolumeHashChainHead * head);
386 static void VHashWait_r(VolumeHashChainHead * head);
389 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
390 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
391 struct rx_queue ** idx);
392 static void ShutdownController(vshutdown_thread_t * params);
393 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
396 static void VLRU_ComputeConstants(void);
397 static void VInitVLRU(void);
398 static void VLRU_Init_Node_r(Volume * vp);
399 static void VLRU_Add_r(Volume * vp);
400 static void VLRU_Delete_r(Volume * vp);
401 static void VLRU_UpdateAccess_r(Volume * vp);
402 static void * VLRU_ScannerThread(void * args);
403 static void VLRU_Scan_r(int idx);
404 static void VLRU_Promote_r(int idx);
405 static void VLRU_Demote_r(int idx);
406 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
409 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
410 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
411 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
414 pthread_key_t VThread_key;
415 VThreadOptions_t VThread_defaults = {
416 0 /**< allow salvsync */
418 #endif /* AFS_DEMAND_ATTACH_FS */
421 struct Lock vol_listLock; /* Lock obtained when listing volumes:
422 * prevents a volume from being missed
423 * if the volume is attached during a
427 /* Common message used when the volume goes off line */
428 char *VSalvageMessage =
429 "Files in this volume are currently unavailable; call operations";
431 int VInit; /* 0 - uninitialized,
432 * 1 - initialized but not all volumes have been attached,
433 * 2 - initialized and all volumes have been attached,
434 * 3 - initialized, all volumes have been attached, and
435 * VConnectFS() has completed. */
437 static int vinit_attach_abort = 0;
439 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
440 * used to stamp volume headers and in-core
441 * vnodes. When the volume goes on-line the
442 * vnode will be invalidated
443 * access only with VOL_LOCK held */
448 /***************************************************/
449 /* Startup routines */
450 /***************************************************/
452 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
453 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
454 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
458 * assign default values to a VolumePackageOptions struct.
460 * Always call this on a VolumePackageOptions struct first, then set any
461 * specific options you want, then call VInitVolumePackage2.
463 * @param[in] pt caller's program type
464 * @param[out] opts volume package options
467 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
469 opts->nLargeVnodes = opts->nSmallVnodes = 5;
472 opts->canScheduleSalvage = 0;
473 opts->canUseFSSYNC = 0;
474 opts->canUseSALVSYNC = 0;
476 opts->interrupt_rxcall = NULL;
477 opts->offline_timeout = -1;
478 opts->offline_shutdown_timeout = -1;
479 opts->usage_threshold = 128;
480 opts->usage_rate_limit = 5;
483 opts->unsafe_attach = 1;
484 #else /* !FAST_RESTART */
485 opts->unsafe_attach = 0;
486 #endif /* !FAST_RESTART */
490 opts->canScheduleSalvage = 1;
491 opts->canUseSALVSYNC = 1;
495 opts->canUseFSSYNC = 1;
499 opts->nLargeVnodes = 0;
500 opts->nSmallVnodes = 0;
502 opts->canScheduleSalvage = 1;
503 opts->canUseFSSYNC = 1;
513 * Set VInit to a certain value, and signal waiters.
515 * @param[in] value the value to set VInit to
520 VSetVInit_r(int value)
523 CV_BROADCAST(&vol_vinit_cond);
527 VLogOfflineTimeout(const char *type, afs_int32 timeout)
533 Log("VInitVolumePackage: Interrupting clients accessing %s "
534 "immediately\n", type);
536 Log("VInitVolumePackage: Interrupting clients accessing %s "
537 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
542 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
544 int errors = 0; /* Number of errors while finding vice partitions. */
549 #ifndef AFS_PTHREAD_ENV
550 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
551 Log("VInitVolumePackage: offline_timeout and/or "
552 "offline_shutdown_timeout was specified, but the volume package "
553 "does not support these for LWP builds\n");
557 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
558 VLogOfflineTimeout("volumes going offline during shutdown",
559 opts->offline_shutdown_timeout);
561 memset(&VStats, 0, sizeof(VStats));
562 VStats.hdr_cache_size = 200;
564 VInitPartitionPackage();
566 #ifdef AFS_DEMAND_ATTACH_FS
567 if (programType == fileServer) {
570 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
572 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
575 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
576 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
577 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
578 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
579 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
580 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
581 #ifndef AFS_PTHREAD_ENV
583 #endif /* AFS_PTHREAD_ENV */
584 Lock_Init(&vol_listLock);
586 srandom(time(0)); /* For VGetVolumeInfo */
588 #ifdef AFS_DEMAND_ATTACH_FS
589 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
590 #endif /* AFS_DEMAND_ATTACH_FS */
592 /* Ok, we have done enough initialization that fileserver can
593 * start accepting calls, even though the volumes may not be
594 * available just yet.
598 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
599 if (programType == salvageServer) {
602 #endif /* AFS_DEMAND_ATTACH_FS */
603 #ifdef FSSYNC_BUILD_SERVER
604 if (programType == fileServer) {
608 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
609 if (VCanUseSALVSYNC()) {
610 /* establish a connection to the salvager at this point */
611 osi_Assert(VConnectSALV() != 0);
613 #endif /* AFS_DEMAND_ATTACH_FS */
615 if (opts->volcache > VStats.hdr_cache_size)
616 VStats.hdr_cache_size = opts->volcache;
617 VInitVolumeHeaderCache(VStats.hdr_cache_size);
619 VInitVnodes(vLarge, opts->nLargeVnodes);
620 VInitVnodes(vSmall, opts->nSmallVnodes);
623 errors = VAttachPartitions();
627 if (programType != fileServer) {
628 errors = VInitAttachVolumes(programType);
634 #ifdef FSSYNC_BUILD_CLIENT
635 if (VCanUseFSSYNC()) {
637 #ifdef AFS_DEMAND_ATTACH_FS
638 if (programType == salvageServer) {
639 Log("Unable to connect to file server; aborted\n");
642 #endif /* AFS_DEMAND_ATTACH_FS */
643 Log("Unable to connect to file server; will retry at need\n");
646 #endif /* FSSYNC_BUILD_CLIENT */
651 #if !defined(AFS_PTHREAD_ENV)
653 * Attach volumes in vice partitions
655 * @param[in] pt calling program type
658 * @note This is the original, non-threaded version of attach parititions.
660 * @post VInit state is 2
663 VInitAttachVolumes(ProgramType pt)
665 osi_Assert(VInit==1);
666 if (pt == fileServer) {
667 struct DiskPartition64 *diskP;
668 /* Attach all the volumes in this partition */
669 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
670 int nAttached = 0, nUnattached = 0;
671 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
675 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
676 LWP_NoYieldSignal(VInitAttachVolumes);
680 #endif /* !AFS_PTHREAD_ENV */
682 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
684 * Attach volumes in vice partitions
686 * @param[in] pt calling program type
689 * @note Threaded version of attach parititions.
691 * @post VInit state is 2
694 VInitAttachVolumes(ProgramType pt)
696 osi_Assert(VInit==1);
697 if (pt == fileServer) {
698 struct DiskPartition64 *diskP;
699 struct vinitvolumepackage_thread_t params;
700 struct diskpartition_queue_t * dpq;
701 int i, threads, parts;
703 pthread_attr_t attrs;
705 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
707 params.n_threads_complete = 0;
709 /* create partition work queue */
710 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
711 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
712 osi_Assert(dpq != NULL);
714 queue_Append(¶ms,dpq);
717 threads = min(parts, vol_attach_threads);
720 /* spawn off a bunch of initialization threads */
721 osi_Assert(pthread_attr_init(&attrs) == 0);
722 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
724 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
725 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
729 for (i=0; i < threads; i++) {
732 osi_Assert(pthread_create
733 (&tid, &attrs, &VInitVolumePackageThread,
735 AFS_SIGSET_RESTORE();
738 while(params.n_threads_complete < threads) {
739 VOL_CV_WAIT(¶ms.thread_done_cv);
743 osi_Assert(pthread_attr_destroy(&attrs) == 0);
745 /* if we're only going to run one init thread, don't bother creating
747 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
748 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
751 VInitVolumePackageThread(¶ms);
754 CV_DESTROY(¶ms.thread_done_cv);
757 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
758 CV_BROADCAST(&vol_init_attach_cond);
764 VInitVolumePackageThread(void * args) {
766 struct DiskPartition64 *diskP;
767 struct vinitvolumepackage_thread_t * params;
768 struct diskpartition_queue_t * dpq;
770 params = (vinitvolumepackage_thread_t *) args;
774 /* Attach all the volumes in this partition */
775 while (queue_IsNotEmpty(params)) {
776 int nAttached = 0, nUnattached = 0;
778 if (vinit_attach_abort) {
779 Log("Aborting initialization\n");
783 dpq = queue_First(params,diskpartition_queue_t);
789 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
795 params->n_threads_complete++;
796 CV_SIGNAL(¶ms->thread_done_cv);
800 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
802 #if defined(AFS_DEMAND_ATTACH_FS)
804 * Attach volumes in vice partitions
806 * @param[in] pt calling program type
809 * @note Threaded version of attach partitions.
811 * @post VInit state is 2
814 VInitAttachVolumes(ProgramType pt)
816 osi_Assert(VInit==1);
817 if (pt == fileServer) {
819 struct DiskPartition64 *diskP;
820 struct partition_queue pq;
821 struct volume_init_queue vq;
823 int i, threads, parts;
825 pthread_attr_t attrs;
827 /* create partition work queue */
829 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
830 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
831 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
832 struct diskpartition_queue_t *dp;
833 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
834 osi_Assert(dp != NULL);
836 queue_Append(&pq, dp);
839 /* number of worker threads; at least one, not to exceed the number of partitions */
840 threads = min(parts, vol_attach_threads);
842 /* create volume work queue */
844 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
845 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
847 osi_Assert(pthread_attr_init(&attrs) == 0);
848 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
850 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
851 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
854 /* create threads to scan disk partitions. */
855 for (i=0; i < threads; i++) {
856 struct vinitvolumepackage_thread_param *params;
859 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
863 params->nthreads = threads;
864 params->thread = i+1;
867 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
868 AFS_SIGSET_RESTORE();
871 VInitPreAttachVolumes(threads, &vq);
873 osi_Assert(pthread_attr_destroy(&attrs) == 0);
875 MUTEX_DESTROY(&pq.mutex);
877 MUTEX_DESTROY(&vq.mutex);
881 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
882 CV_BROADCAST(&vol_init_attach_cond);
889 * Volume package initialization worker thread. Scan partitions for volume
890 * header files. Gather batches of volume ids and dispatch them to
891 * the main thread to be preattached. The volume preattachement is done
892 * in the main thread to avoid global volume lock contention.
895 VInitVolumePackageThread(void *args)
897 struct vinitvolumepackage_thread_param *params;
898 struct DiskPartition64 *partition;
899 struct partition_queue *pq;
900 struct volume_init_queue *vq;
901 struct volume_init_batch *vb;
904 params = (struct vinitvolumepackage_thread_param *)args;
910 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
912 vb->thread = params->thread;
916 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
917 while((partition = VInitNextPartition(pq))) {
921 Log("Partition %s: pre-attaching volumes\n", partition->name);
922 dirp = opendir(VPartitionPath(partition));
924 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
927 while ((vid = VInitNextVolumeId(dirp))) {
928 Volume *vp = (Volume*)malloc(sizeof(Volume));
930 memset(vp, 0, sizeof(Volume));
931 vp->device = partition->device;
932 vp->partition = partition;
934 queue_Init(&vp->vnode_list);
935 queue_Init(&vp->rx_call_list);
936 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
938 vb->batch[vb->size++] = vp;
939 if (vb->size == VINIT_BATCH_MAX_SIZE) {
940 MUTEX_ENTER(&vq->mutex);
941 queue_Append(vq, vb);
942 CV_BROADCAST(&vq->cv);
943 MUTEX_EXIT(&vq->mutex);
945 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
947 vb->thread = params->thread;
956 MUTEX_ENTER(&vq->mutex);
957 queue_Append(vq, vb);
958 CV_BROADCAST(&vq->cv);
959 MUTEX_EXIT(&vq->mutex);
961 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
967 * Read next element from the pre-populated partition list.
969 static struct DiskPartition64*
970 VInitNextPartition(struct partition_queue *pq)
972 struct DiskPartition64 *partition;
973 struct diskpartition_queue_t *dp; /* queue element */
975 if (vinit_attach_abort) {
976 Log("Aborting volume preattach thread.\n");
980 /* get next partition to scan */
981 MUTEX_ENTER(&pq->mutex);
982 if (queue_IsEmpty(pq)) {
983 MUTEX_EXIT(&pq->mutex);
986 dp = queue_First(pq, diskpartition_queue_t);
988 MUTEX_EXIT(&pq->mutex);
991 osi_Assert(dp->diskP);
993 partition = dp->diskP;
999 * Find next volume id on the partition.
1002 VInitNextVolumeId(DIR *dirp)
1008 while((d = readdir(dirp))) {
1009 if (vinit_attach_abort) {
1010 Log("Aborting volume preattach thread.\n");
1013 ext = strrchr(d->d_name, '.');
1014 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1015 vid = VolumeNumber(d->d_name);
1019 Log("Warning: bogus volume header file: %s\n", d->d_name);
1026 * Preattach volumes in batches to avoid lock contention.
1029 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1031 struct volume_init_batch *vb;
1035 /* dequeue next volume */
1036 MUTEX_ENTER(&vq->mutex);
1037 if (queue_IsEmpty(vq)) {
1038 CV_WAIT(&vq->cv, &vq->mutex);
1040 vb = queue_First(vq, volume_init_batch);
1042 MUTEX_EXIT(&vq->mutex);
1046 for (i = 0; i<vb->size; i++) {
1052 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1054 Log("Error looking up volume, code=%d\n", ec);
1057 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1060 /* put pre-attached volume onto the hash table
1061 * and bring it up to the pre-attached state */
1062 AddVolumeToHashTable(vp, vp->hashid);
1063 AddVolumeToVByPList_r(vp);
1064 VLRU_Init_Node_r(vp);
1065 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1078 #endif /* AFS_DEMAND_ATTACH_FS */
1080 #if !defined(AFS_DEMAND_ATTACH_FS)
1082 * attach all volumes on a given disk partition
1085 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1091 Log("Partition %s: attaching volumes\n", diskP->name);
1092 dirp = opendir(VPartitionPath(diskP));
1094 Log("opendir on Partition %s failed!\n", diskP->name);
1098 while ((dp = readdir(dirp))) {
1100 p = strrchr(dp->d_name, '.');
1102 if (vinit_attach_abort) {
1103 Log("Partition %s: abort attach volumes\n", diskP->name);
1107 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1110 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1112 (*(vp ? nAttached : nUnattached))++;
1113 if (error == VOFFLINE)
1114 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1115 else if (LogLevel >= 5) {
1116 Log("Partition %s: attached volume %d (%s)\n",
1117 diskP->name, VolumeNumber(dp->d_name),
1126 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1131 #endif /* !AFS_DEMAND_ATTACH_FS */
1133 /***************************************************/
1134 /* Shutdown routines */
1135 /***************************************************/
1139 * highly multithreaded volume package shutdown
1141 * with the demand attach fileserver extensions,
1142 * VShutdown has been modified to be multithreaded.
1143 * In order to achieve optimal use of many threads,
1144 * the shutdown code involves one control thread and
1145 * n shutdown worker threads. The control thread
1146 * periodically examines the number of volumes available
1147 * for shutdown on each partition, and produces a worker
1148 * thread allocation schedule. The idea is to eliminate
1149 * redundant scheduling computation on the workers by
1150 * having a single master scheduler.
1152 * The scheduler's objectives are:
1154 * each partition with volumes remaining gets allocated
1155 * at least 1 thread (assuming sufficient threads)
1157 * threads are allocated proportional to the number of
1158 * volumes remaining to be offlined. This ensures that
1159 * the OS I/O scheduler has many requests to elevator
1160 * seek on partitions that will (presumably) take the
1161 * longest amount of time (from now) to finish shutdown
1162 * (3) keep threads busy
1163 * when there are extra threads, they are assigned to
1164 * partitions using a simple round-robin algorithm
1166 * In the future, we may wish to add the ability to adapt
1167 * to the relative performance patterns of each disk
1172 * multi-step shutdown process
1174 * demand attach shutdown is a four-step process. Each
1175 * shutdown "pass" shuts down increasingly more difficult
1176 * volumes. The main purpose is to achieve better cache
1177 * utilization during shutdown.
1180 * shutdown volumes in the unattached, pre-attached
1183 * shutdown attached volumes with cached volume headers
1185 * shutdown all volumes in non-exclusive states
1187 * shutdown all remaining volumes
1190 #ifdef AFS_DEMAND_ATTACH_FS
1196 struct DiskPartition64 * diskP;
1197 struct diskpartition_queue_t * dpq;
1198 vshutdown_thread_t params;
1200 pthread_attr_t attrs;
1202 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1205 Log("VShutdown: aborting attach volumes\n");
1206 vinit_attach_abort = 1;
1207 VOL_CV_WAIT(&vol_init_attach_cond);
1210 for (params.n_parts=0, diskP = DiskPartitionList;
1211 diskP; diskP = diskP->next, params.n_parts++);
1213 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1214 params.n_parts, params.n_parts > 1 ? "s" : "");
1216 vol_shutting_down = 1;
1218 if (vol_attach_threads > 1) {
1219 /* prepare for parallel shutdown */
1220 params.n_threads = vol_attach_threads;
1221 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1222 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1223 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1224 osi_Assert(pthread_attr_init(&attrs) == 0);
1225 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1226 queue_Init(¶ms);
1228 /* setup the basic partition information structures for
1229 * parallel shutdown */
1230 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1232 struct rx_queue * qp, * nqp;
1236 VVByPListWait_r(diskP);
1237 VVByPListBeginExclusive_r(diskP);
1240 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1241 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1245 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1246 VPartitionPath(diskP), count);
1249 /* build up the pass 0 shutdown work queue */
1250 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1251 osi_Assert(dpq != NULL);
1253 queue_Prepend(¶ms, dpq);
1255 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1258 Log("VShutdown: beginning parallel fileserver shutdown\n");
1259 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1260 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1262 /* do pass 0 shutdown */
1263 MUTEX_ENTER(¶ms.lock);
1264 for (i=0; i < params.n_threads; i++) {
1265 osi_Assert(pthread_create
1266 (&tid, &attrs, &VShutdownThread,
1270 /* wait for all the pass 0 shutdowns to complete */
1271 while (params.n_threads_complete < params.n_threads) {
1272 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1274 params.n_threads_complete = 0;
1276 CV_BROADCAST(¶ms.cv);
1277 MUTEX_EXIT(¶ms.lock);
1279 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1280 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1282 /* run the parallel shutdown scheduler. it will drop the glock internally */
1283 ShutdownController(¶ms);
1285 /* wait for all the workers to finish pass 3 and terminate */
1286 while (params.pass < 4) {
1287 VOL_CV_WAIT(¶ms.cv);
1290 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1291 CV_DESTROY(¶ms.cv);
1292 CV_DESTROY(¶ms.master_cv);
1293 MUTEX_DESTROY(¶ms.lock);
1295 /* drop the VByPList exclusive reservations */
1296 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1297 VVByPListEndExclusive_r(diskP);
1298 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1299 VPartitionPath(diskP),
1300 params.stats[0][diskP->index],
1301 params.stats[1][diskP->index],
1302 params.stats[2][diskP->index],
1303 params.stats[3][diskP->index]);
1306 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1308 /* if we're only going to run one shutdown thread, don't bother creating
1310 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1312 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1313 VShutdownByPartition_r(diskP);
1317 Log("VShutdown: complete.\n");
1320 #else /* AFS_DEMAND_ATTACH_FS */
1330 Log("VShutdown: aborting attach volumes\n");
1331 vinit_attach_abort = 1;
1332 #ifdef AFS_PTHREAD_ENV
1333 VOL_CV_WAIT(&vol_init_attach_cond);
1335 LWP_WaitProcess(VInitAttachVolumes);
1336 #endif /* AFS_PTHREAD_ENV */
1339 Log("VShutdown: shutting down on-line volumes...\n");
1340 vol_shutting_down = 1;
1341 for (i = 0; i < VolumeHashTable.Size; i++) {
1342 /* try to hold first volume in the hash table */
1343 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1347 Log("VShutdown: Attempting to take volume %u offline.\n",
1350 /* next, take the volume offline (drops reference count) */
1351 VOffline_r(vp, "File server was shut down");
1355 Log("VShutdown: complete.\n");
1357 #endif /* AFS_DEMAND_ATTACH_FS */
1363 osi_Assert(VInit>0);
1370 * stop new activity (e.g. SALVSYNC) from occurring
1372 * Use this to make the volume package less busy; for example, during
1373 * shutdown. This doesn't actually shutdown/detach anything in the
1374 * volume package, but prevents certain processes from ocurring. For
1375 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1376 * could also use this to prevent new volume attachment, or prevent
1377 * other programs from checking out volumes, etc.
1382 #ifdef AFS_DEMAND_ATTACH_FS
1383 /* make sure we don't try to contact the salvageserver, since it may
1384 * not be around anymore */
1385 vol_disallow_salvsync = 1;
1389 #ifdef AFS_DEMAND_ATTACH_FS
1392 * shutdown control thread
1395 ShutdownController(vshutdown_thread_t * params)
1398 struct DiskPartition64 * diskP;
1400 vshutdown_thread_t shadow;
1402 ShutdownCreateSchedule(params);
1404 while ((params->pass < 4) &&
1405 (params->n_threads_complete < params->n_threads)) {
1406 /* recompute schedule once per second */
1408 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1412 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1413 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1414 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1415 shadow.n_threads_complete, shadow.n_parts_done_pass);
1416 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1418 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1420 diskP->vol_list.len,
1421 shadow.part_thread_target[id],
1422 shadow.part_done_pass[id],
1423 shadow.part_pass_head[id]);
1429 ShutdownCreateSchedule(params);
1433 /* create the shutdown thread work schedule.
1434 * this scheduler tries to implement fairness
1435 * by allocating at least 1 thread to each
1436 * partition with volumes to be shutdown,
1437 * and then it attempts to allocate remaining
1438 * threads based upon the amount of work left
1441 ShutdownCreateSchedule(vshutdown_thread_t * params)
1443 struct DiskPartition64 * diskP;
1444 int sum, thr_workload, thr_left;
1445 int part_residue[VOLMAXPARTS+1];
1448 /* compute the total number of outstanding volumes */
1450 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1451 sum += diskP->vol_list.len;
1454 params->schedule_version++;
1455 params->vol_remaining = sum;
1460 /* compute average per-thread workload */
1461 thr_workload = sum / params->n_threads;
1462 if (sum % params->n_threads)
1465 thr_left = params->n_threads;
1466 memset(&part_residue, 0, sizeof(part_residue));
1468 /* for fairness, give every partition with volumes remaining
1469 * at least one thread */
1470 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1472 if (diskP->vol_list.len) {
1473 params->part_thread_target[id] = 1;
1476 params->part_thread_target[id] = 0;
1480 if (thr_left && thr_workload) {
1481 /* compute length-weighted workloads */
1484 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1486 delta = (diskP->vol_list.len / thr_workload) -
1487 params->part_thread_target[id];
1491 if (delta < thr_left) {
1492 params->part_thread_target[id] += delta;
1495 params->part_thread_target[id] += thr_left;
1503 /* try to assign any leftover threads to partitions that
1504 * had volume lengths closer to needing thread_target+1 */
1505 int max_residue, max_id = 0;
1507 /* compute the residues */
1508 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1510 part_residue[id] = diskP->vol_list.len -
1511 (params->part_thread_target[id] * thr_workload);
1514 /* now try to allocate remaining threads to partitions with the
1515 * highest residues */
1518 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1520 if (part_residue[id] > max_residue) {
1521 max_residue = part_residue[id];
1530 params->part_thread_target[max_id]++;
1532 part_residue[max_id] = 0;
1537 /* punt and give any remaining threads equally to each partition */
1539 if (thr_left >= params->n_parts) {
1540 alloc = thr_left / params->n_parts;
1541 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1543 params->part_thread_target[id] += alloc;
1548 /* finish off the last of the threads */
1549 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1551 params->part_thread_target[id]++;
1557 /* worker thread for parallel shutdown */
1559 VShutdownThread(void * args)
1561 vshutdown_thread_t * params;
1562 int found, pass, schedule_version_save, count;
1563 struct DiskPartition64 *diskP;
1564 struct diskpartition_queue_t * dpq;
1567 params = (vshutdown_thread_t *) args;
1569 /* acquire the shutdown pass 0 lock */
1570 MUTEX_ENTER(¶ms->lock);
1572 /* if there's still pass 0 work to be done,
1573 * get a work entry, and do a pass 0 shutdown */
1574 if (queue_IsNotEmpty(params)) {
1575 dpq = queue_First(params, diskpartition_queue_t);
1577 MUTEX_EXIT(¶ms->lock);
1583 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1585 params->stats[0][diskP->index] = count;
1586 MUTEX_ENTER(¶ms->lock);
1589 params->n_threads_complete++;
1590 if (params->n_threads_complete == params->n_threads) {
1591 /* notify control thread that all workers have completed pass 0 */
1592 CV_SIGNAL(¶ms->master_cv);
1594 while (params->pass == 0) {
1595 CV_WAIT(¶ms->cv, ¶ms->lock);
1599 MUTEX_EXIT(¶ms->lock);
1602 pass = params->pass;
1603 osi_Assert(pass > 0);
1605 /* now escalate through the more complicated shutdowns */
1607 schedule_version_save = params->schedule_version;
1609 /* find a disk partition to work on */
1610 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1612 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1613 params->part_thread_target[id]--;
1620 /* hmm. for some reason the controller thread couldn't find anything for
1621 * us to do. let's see if there's anything we can do */
1622 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1624 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1627 } else if (!params->part_done_pass[id]) {
1628 params->part_done_pass[id] = 1;
1629 params->n_parts_done_pass++;
1631 Log("VShutdown: done shutting down volumes on partition %s.\n",
1632 VPartitionPath(diskP));
1638 /* do work on this partition until either the controller
1639 * creates a new schedule, or we run out of things to do
1640 * on this partition */
1643 while (!params->part_done_pass[id] &&
1644 (schedule_version_save == params->schedule_version)) {
1645 /* ShutdownVolumeWalk_r will drop the glock internally */
1646 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1647 if (!params->part_done_pass[id]) {
1648 params->part_done_pass[id] = 1;
1649 params->n_parts_done_pass++;
1651 Log("VShutdown: done shutting down volumes on partition %s.\n",
1652 VPartitionPath(diskP));
1660 params->stats[pass][id] += count;
1662 /* ok, everyone is done this pass, proceed */
1665 params->n_threads_complete++;
1666 while (params->pass == pass) {
1667 if (params->n_threads_complete == params->n_threads) {
1668 /* we are the last thread to complete, so we will
1669 * reinitialize worker pool state for the next pass */
1670 params->n_threads_complete = 0;
1671 params->n_parts_done_pass = 0;
1673 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1675 params->part_done_pass[id] = 0;
1676 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1679 /* compute a new thread schedule before releasing all the workers */
1680 ShutdownCreateSchedule(params);
1682 /* wake up all the workers */
1683 CV_BROADCAST(¶ms->cv);
1686 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1687 pass, params->n_threads, params->n_parts);
1690 VOL_CV_WAIT(¶ms->cv);
1693 pass = params->pass;
1707 /* shut down all volumes on a given disk partition
1709 * note that this function will not allow mp-fast
1710 * shutdown of a partition */
1712 VShutdownByPartition_r(struct DiskPartition64 * dp)
1718 /* wait for other exclusive ops to finish */
1719 VVByPListWait_r(dp);
1721 /* begin exclusive access */
1722 VVByPListBeginExclusive_r(dp);
1724 /* pick the low-hanging fruit first,
1725 * then do the complicated ones last
1726 * (has the advantage of keeping
1727 * in-use volumes up until the bitter end) */
1728 for (pass = 0, total=0; pass < 4; pass++) {
1729 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1730 total += pass_stats[pass];
1733 /* end exclusive access */
1734 VVByPListEndExclusive_r(dp);
1736 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1737 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1742 /* internal shutdown functionality
1744 * for multi-pass shutdown:
1745 * 0 to only "shutdown" {pre,un}attached and error state volumes
1746 * 1 to also shutdown attached volumes w/ volume header loaded
1747 * 2 to also shutdown attached volumes w/o volume header loaded
1748 * 3 to also shutdown exclusive state volumes
1750 * caller MUST hold exclusive access on the hash chain
1751 * because we drop vol_glock_mutex internally
1753 * this function is reentrant for passes 1--3
1754 * (e.g. multiple threads can cooperate to
1755 * shutdown a partition mp-fast)
1757 * pass 0 is not scaleable because the volume state data is
1758 * synchronized by vol_glock mutex, and the locking overhead
1759 * is too high to drop the lock long enough to do linked list
1763 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1765 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1768 while (ShutdownVolumeWalk_r(dp, pass, &q))
1774 /* conditionally shutdown one volume on partition dp
1775 * returns 1 if a volume was shutdown in this pass,
1778 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1779 struct rx_queue ** idx)
1781 struct rx_queue *qp, *nqp;
1786 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1787 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1791 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1792 (V_attachState(vp) != VOL_STATE_ERROR) &&
1793 (V_attachState(vp) != VOL_STATE_DELETED) &&
1794 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1798 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1799 (vp->header == NULL)) {
1803 if (VIsExclusiveState(V_attachState(vp))) {
1808 DeleteVolumeFromVByPList_r(vp);
1809 VShutdownVolume_r(vp);
1819 * shutdown a specific volume
1821 /* caller MUST NOT hold a heavyweight ref on vp */
1823 VShutdownVolume_r(Volume * vp)
1827 VCreateReservation_r(vp);
1829 if (LogLevel >= 5) {
1830 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1831 vp->hashid, vp->partition->device, V_attachState(vp));
1834 /* wait for other blocking ops to finish */
1835 VWaitExclusiveState_r(vp);
1837 osi_Assert(VIsValidState(V_attachState(vp)));
1839 switch(V_attachState(vp)) {
1840 case VOL_STATE_SALVAGING:
1841 /* Leave salvaging volumes alone. Any in-progress salvages will
1842 * continue working after viced shuts down. This is intentional.
1845 case VOL_STATE_PREATTACHED:
1846 case VOL_STATE_ERROR:
1847 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1848 case VOL_STATE_UNATTACHED:
1849 case VOL_STATE_DELETED:
1851 case VOL_STATE_GOING_OFFLINE:
1852 case VOL_STATE_SHUTTING_DOWN:
1853 case VOL_STATE_ATTACHED:
1857 Log("VShutdown: Attempting to take volume %u offline.\n",
1860 /* take the volume offline (drops reference count) */
1861 VOffline_r(vp, "File server was shut down");
1868 VCancelReservation_r(vp);
1872 #endif /* AFS_DEMAND_ATTACH_FS */
1875 /***************************************************/
1876 /* Header I/O routines */
1877 /***************************************************/
1880 HeaderName(bit32 magic)
1883 case VOLUMEINFOMAGIC:
1884 return "volume info";
1885 case SMALLINDEXMAGIC:
1886 return "small index";
1887 case LARGEINDEXMAGIC:
1888 return "large index";
1889 case LINKTABLEMAGIC:
1890 return "link table";
1895 /* open a descriptor for the inode (h),
1896 * read in an on-disk structure into buffer (to) of size (size),
1897 * verify versionstamp in structure has magic (magic) and
1898 * optionally verify version (version) if (version) is nonzero
1901 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1904 struct versionStamp *vsn;
1906 afs_sfsize_t nbytes;
1911 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1919 Log("ReadHeader: Failed to open %s header file "
1920 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1921 PrintInode(stmp, h->ih_ino), errno);
1926 vsn = (struct versionStamp *)to;
1927 nbytes = FDH_PREAD(fdP, to, size, 0);
1929 Log("ReadHeader: Failed to read %s header file "
1930 "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1931 PrintInode(stmp, h->ih_ino), errno);
1933 FDH_REALLYCLOSE(fdP);
1936 if (nbytes != size) {
1937 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1938 "(volume=%u, inode=%s); expected=%d, read=%d\n",
1939 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), size,
1942 FDH_REALLYCLOSE(fdP);
1945 if (vsn->magic != magic) {
1946 Log("ReadHeader: Incorrect magic for %s header file "
1947 "(volume=%u, inode=%s); expected=0x%x, read=0x%x\n",
1948 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), magic,
1951 FDH_REALLYCLOSE(fdP);
1957 /* Check is conditional, in case caller wants to inspect version himself */
1958 if (version && vsn->version != version) {
1959 Log("ReadHeader: Incorrect version for %s header file "
1960 "(volume=%u, inode=%s); expected=%x, read=%x\n",
1961 HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino),
1962 version, vsn->version);
1968 WriteVolumeHeader_r(Error * ec, Volume * vp)
1970 IHandle_t *h = V_diskDataHandle(vp);
1980 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1981 != sizeof(V_disk(vp))) {
1983 FDH_REALLYCLOSE(fdP);
1989 /* VolumeHeaderToDisk
1990 * Allows for storing 64 bit inode numbers in on-disk volume header
1993 /* convert in-memory representation of a volume header to the
1994 * on-disk representation of a volume header */
1996 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1999 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2000 dh->stamp = h->stamp;
2002 dh->parent = h->parent;
2004 #ifdef AFS_64BIT_IOPS_ENV
2005 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2006 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2007 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2008 dh->smallVnodeIndex_hi =
2009 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2010 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2011 dh->largeVnodeIndex_hi =
2012 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2013 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2014 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2016 dh->volumeInfo_lo = h->volumeInfo;
2017 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2018 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2019 dh->linkTable_lo = h->linkTable;
2023 /* DiskToVolumeHeader
2024 * Converts an on-disk representation of a volume header to
2025 * the in-memory representation of a volume header.
2027 * Makes the assumption that AFS has *always*
2028 * zero'd the volume header file so that high parts of inode
2029 * numbers are 0 in older (SGI EFS) volume header files.
2032 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2034 memset(h, 0, sizeof(VolumeHeader_t));
2035 h->stamp = dh->stamp;
2037 h->parent = dh->parent;
2039 #ifdef AFS_64BIT_IOPS_ENV
2041 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2043 h->smallVnodeIndex =
2044 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2045 smallVnodeIndex_hi << 32);
2047 h->largeVnodeIndex =
2048 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2049 largeVnodeIndex_hi << 32);
2051 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2053 h->volumeInfo = dh->volumeInfo_lo;
2054 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2055 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2056 h->linkTable = dh->linkTable_lo;
2061 /***************************************************/
2062 /* Volume Attachment routines */
2063 /***************************************************/
2065 #ifdef AFS_DEMAND_ATTACH_FS
2067 * pre-attach a volume given its path.
2069 * @param[out] ec outbound error code
2070 * @param[in] partition partition path string
2071 * @param[in] name volume id string
2073 * @return volume object pointer
2075 * @note A pre-attached volume will only have its partition
2076 * and hashid fields initialized. At first call to
2077 * VGetVolume, the volume will be fully attached.
2081 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2085 vp = VPreAttachVolumeByName_r(ec, partition, name);
2091 * pre-attach a volume given its path.
2093 * @param[out] ec outbound error code
2094 * @param[in] partition path to vice partition
2095 * @param[in] name volume id string
2097 * @return volume object pointer
2099 * @pre VOL_LOCK held
2101 * @internal volume package internal use only.
2104 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2106 return VPreAttachVolumeById_r(ec,
2108 VolumeNumber(name));
2112 * pre-attach a volume given its path and numeric volume id.
2114 * @param[out] ec error code return
2115 * @param[in] partition path to vice partition
2116 * @param[in] volumeId numeric volume id
2118 * @return volume object pointer
2120 * @pre VOL_LOCK held
2122 * @internal volume package internal use only.
2125 VPreAttachVolumeById_r(Error * ec,
2130 struct DiskPartition64 *partp;
2134 osi_Assert(programType == fileServer);
2136 if (!(partp = VGetPartition_r(partition, 0))) {
2138 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2142 vp = VLookupVolume_r(ec, volumeId, NULL);
2147 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2151 * preattach a volume.
2153 * @param[out] ec outbound error code
2154 * @param[in] partp pointer to partition object
2155 * @param[in] vp pointer to volume object
2156 * @param[in] vid volume id
2158 * @return volume object pointer
2160 * @pre VOL_LOCK is held.
2162 * @warning Returned volume object pointer does not have to
2163 * equal the pointer passed in as argument vp. There
2164 * are potential race conditions which can result in
2165 * the pointers having different values. It is up to
2166 * the caller to make sure that references are handled
2167 * properly in this case.
2169 * @note If there is already a volume object registered with
2170 * the same volume id, its pointer MUST be passed as
2171 * argument vp. Failure to do so will result in a silent
2172 * failure to preattach.
2174 * @internal volume package internal use only.
2177 VPreAttachVolumeByVp_r(Error * ec,
2178 struct DiskPartition64 * partp,
2186 /* check to see if pre-attach already happened */
2188 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2189 (V_attachState(vp) != VOL_STATE_DELETED) &&
2190 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2191 !VIsErrorState(V_attachState(vp))) {
2193 * pre-attach is a no-op in all but the following cases:
2195 * - volume is unattached
2196 * - volume is in an error state
2197 * - volume is pre-attached
2199 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state (state %u flags 0x%x)\n",
2200 vid, V_attachState(vp), V_attachFlags(vp));
2203 /* we're re-attaching a volume; clear out some old state */
2204 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2206 if (V_partition(vp) != partp) {
2207 /* XXX potential race */
2208 DeleteVolumeFromVByPList_r(vp);
2211 /* if we need to allocate a new Volume struct,
2212 * go ahead and drop the vol glock, otherwise
2213 * do the basic setup synchronised, as it's
2214 * probably not worth dropping the lock */
2217 /* allocate the volume structure */
2218 vp = nvp = (Volume *) malloc(sizeof(Volume));
2219 osi_Assert(vp != NULL);
2220 memset(vp, 0, sizeof(Volume));
2221 queue_Init(&vp->vnode_list);
2222 queue_Init(&vp->rx_call_list);
2223 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2226 /* link the volume with its associated vice partition */
2227 vp->device = partp->device;
2228 vp->partition = partp;
2231 vp->specialStatus = 0;
2233 /* if we dropped the lock, reacquire the lock,
2234 * check for pre-attach races, and then add
2235 * the volume to the hash table */
2238 nvp = VLookupVolume_r(ec, vid, NULL);
2243 } else if (nvp) { /* race detected */
2248 /* hack to make up for VChangeState_r() decrementing
2249 * the old state counter */
2250 VStats.state_levels[0]++;
2254 /* put pre-attached volume onto the hash table
2255 * and bring it up to the pre-attached state */
2256 AddVolumeToHashTable(vp, vp->hashid);
2257 AddVolumeToVByPList_r(vp);
2258 VLRU_Init_Node_r(vp);
2259 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2262 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2270 #endif /* AFS_DEMAND_ATTACH_FS */
2272 /* Attach an existing volume, given its pathname, and return a
2273 pointer to the volume header information. The volume also
2274 normally goes online at this time. An offline volume
2275 must be reattached to make it go online */
2277 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2281 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2287 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2290 struct DiskPartition64 *partp;
2295 #ifdef AFS_DEMAND_ATTACH_FS
2296 VolumeStats stats_save;
2298 #endif /* AFS_DEMAND_ATTACH_FS */
2302 volumeId = VolumeNumber(name);
2304 if (!(partp = VGetPartition_r(partition, 0))) {
2306 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2310 if (VRequiresPartLock()) {
2311 osi_Assert(VInit == 3);
2312 VLockPartition_r(partition);
2313 } else if (programType == fileServer) {
2314 #ifdef AFS_DEMAND_ATTACH_FS
2315 /* lookup the volume in the hash table */
2316 vp = VLookupVolume_r(ec, volumeId, NULL);
2322 /* save any counters that are supposed to
2323 * be monotonically increasing over the
2324 * lifetime of the fileserver */
2325 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2327 memset(&stats_save, 0, sizeof(VolumeStats));
2330 /* if there's something in the hash table, and it's not
2331 * in the pre-attach state, then we may need to detach
2332 * it before proceeding */
2333 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2334 VCreateReservation_r(vp);
2335 VWaitExclusiveState_r(vp);
2337 /* at this point state must be one of:
2347 if (vp->specialStatus == VBUSY)
2350 /* if it's already attached, see if we can return it */
2351 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2352 VGetVolumeByVp_r(ec, vp);
2353 if (V_inUse(vp) == fileServer) {
2354 VCancelReservation_r(vp);
2358 /* otherwise, we need to detach, and attempt to re-attach */
2359 VDetachVolume_r(ec, vp);
2361 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2364 /* if it isn't fully attached, delete from the hash tables,
2365 and let the refcounter handle the rest */
2366 DeleteVolumeFromHashTable(vp);
2367 DeleteVolumeFromVByPList_r(vp);
2370 VCancelReservation_r(vp);
2374 /* pre-attach volume if it hasn't been done yet */
2376 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2377 (V_attachState(vp) == VOL_STATE_DELETED) ||
2378 (V_attachState(vp) == VOL_STATE_ERROR)) {
2380 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2386 osi_Assert(vp != NULL);
2388 /* handle pre-attach races
2390 * multiple threads can race to pre-attach a volume,
2391 * but we can't let them race beyond that
2393 * our solution is to let the first thread to bring
2394 * the volume into an exclusive state win; the other
2395 * threads just wait until it finishes bringing the
2396 * volume online, and then they do a vgetvolumebyvp
2398 if (svp && (svp != vp)) {
2399 /* wait for other exclusive ops to finish */
2400 VCreateReservation_r(vp);
2401 VWaitExclusiveState_r(vp);
2403 /* get a heavyweight ref, kill the lightweight ref, and return */
2404 VGetVolumeByVp_r(ec, vp);
2405 VCancelReservation_r(vp);
2409 /* at this point, we are chosen as the thread to do
2410 * demand attachment for this volume. all other threads
2411 * doing a getvolume on vp->hashid will block until we finish */
2413 /* make sure any old header cache entries are invalidated
2414 * before proceeding */
2415 FreeVolumeHeader(vp);
2417 VChangeState_r(vp, VOL_STATE_ATTACHING);
2419 /* restore any saved counters */
2420 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2421 #else /* AFS_DEMAND_ATTACH_FS */
2422 vp = VGetVolume_r(ec, volumeId);
2424 if (V_inUse(vp) == fileServer)
2426 if (vp->specialStatus == VBUSY)
2428 VDetachVolume_r(ec, vp);
2430 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2434 #endif /* AFS_DEMAND_ATTACH_FS */
2438 strcpy(path, VPartitionPath(partp));
2442 strcat(path, OS_DIRSEP);
2446 vp = (Volume *) calloc(1, sizeof(Volume));
2447 osi_Assert(vp != NULL);
2448 vp->hashid = volumeId;
2449 vp->device = partp->device;
2450 vp->partition = partp;
2451 queue_Init(&vp->vnode_list);
2452 queue_Init(&vp->rx_call_list);
2453 #ifdef AFS_DEMAND_ATTACH_FS
2454 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2455 #endif /* AFS_DEMAND_ATTACH_FS */
2458 /* attach2 is entered without any locks, and returns
2459 * with vol_glock_mutex held */
2460 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2462 if (VCanUseFSSYNC() && vp) {
2463 #ifdef AFS_DEMAND_ATTACH_FS
2464 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2465 /* mark volume header as in use so that volser crashes lead to a
2466 * salvage attempt */
2467 VUpdateVolume_r(ec, vp, 0);
2469 /* for dafs, we should tell the fileserver, except for V_PEEK
2470 * where we know it is not necessary */
2471 if (mode == V_PEEK) {
2472 vp->needsPutBack = 0;
2474 vp->needsPutBack = VOL_PUTBACK;
2476 #else /* !AFS_DEMAND_ATTACH_FS */
2477 /* duplicate computation in fssync.c about whether the server
2478 * takes the volume offline or not. If the volume isn't
2479 * offline, we must not return it when we detach the volume,
2480 * or the server will abort */
2481 if (mode == V_READONLY || mode == V_PEEK
2482 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2483 vp->needsPutBack = 0;
2485 vp->needsPutBack = VOL_PUTBACK;
2486 #endif /* !AFS_DEMAND_ATTACH_FS */
2488 #ifdef FSSYNC_BUILD_CLIENT
2489 /* Only give back the vol to the fileserver if we checked it out; attach2
2490 * will set checkedOut only if we successfully checked it out from the
2492 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2494 #ifdef AFS_DEMAND_ATTACH_FS
2495 /* If we couldn't attach but we scheduled a salvage, we already
2496 * notified the fileserver; don't online it now */
2497 if (*ec != VSALVAGING)
2498 #endif /* AFS_DEMAND_ATTACH_FS */
2499 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2502 if (programType == fileServer && vp) {
2503 #ifdef AFS_DEMAND_ATTACH_FS
2505 * we can get here in cases where we don't "own"
2506 * the volume (e.g. volume owned by a utility).
2507 * short circuit around potential disk header races.
2509 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2513 VUpdateVolume_r(ec, vp, 0);
2515 Log("VAttachVolume: Error updating volume\n");
2520 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2521 #ifndef AFS_DEMAND_ATTACH_FS
2522 /* This is a hack: by temporarily setting the incore
2523 * dontSalvage flag ON, the volume will be put back on the
2524 * Update list (with dontSalvage OFF again). It will then
2525 * come back in N minutes with DONT_SALVAGE eventually
2526 * set. This is the way that volumes that have never had
2527 * it set get it set; or that volumes that have been
2528 * offline without DONT SALVAGE having been set also
2529 * eventually get it set */
2530 V_dontSalvage(vp) = DONT_SALVAGE;
2531 #endif /* !AFS_DEMAND_ATTACH_FS */
2532 VAddToVolumeUpdateList_r(ec, vp);
2534 Log("VAttachVolume: Error adding volume to update list\n");
2541 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2546 if (VRequiresPartLock()) {
2547 VUnlockPartition_r(partition);
2550 #ifdef AFS_DEMAND_ATTACH_FS
2551 /* attach failed; make sure we're in error state */
2552 if (vp && !VIsErrorState(V_attachState(vp))) {
2553 VChangeState_r(vp, VOL_STATE_ERROR);
2555 #endif /* AFS_DEMAND_ATTACH_FS */
2562 #ifdef AFS_DEMAND_ATTACH_FS
2563 /* VAttachVolumeByVp_r
2565 * finish attaching a volume that is
2566 * in a less than fully attached state
2568 /* caller MUST hold a ref count on vp */
2570 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2572 char name[VMAXPATHLEN];
2574 struct DiskPartition64 *partp;
2578 Volume * nvp = NULL;
2579 VolumeStats stats_save;
2583 /* volume utility should never call AttachByVp */
2584 osi_Assert(programType == fileServer);
2586 volumeId = vp->hashid;
2587 partp = vp->partition;
2588 VolumeExternalName_r(volumeId, name, sizeof(name));
2591 /* if another thread is performing a blocking op, wait */
2592 VWaitExclusiveState_r(vp);
2594 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2596 /* if it's already attached, see if we can return it */
2597 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2598 VGetVolumeByVp_r(ec, vp);
2599 if (V_inUse(vp) == fileServer) {
2602 if (vp->specialStatus == VBUSY)
2604 VDetachVolume_r(ec, vp);
2606 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2612 /* pre-attach volume if it hasn't been done yet */
2614 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2615 (V_attachState(vp) == VOL_STATE_DELETED) ||
2616 (V_attachState(vp) == VOL_STATE_ERROR)) {
2617 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2623 VCreateReservation_r(nvp);
2628 osi_Assert(vp != NULL);
2629 VChangeState_r(vp, VOL_STATE_ATTACHING);
2631 /* restore monotonically increasing stats */
2632 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2636 /* compute path to disk header */
2637 strcpy(path, VPartitionPath(partp));
2641 strcat(path, OS_DIRSEP);
2646 * NOTE: attach2 is entered without any locks, and returns
2647 * with vol_glock_mutex held */
2648 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2651 * the event that an error was encountered, or
2652 * the volume was not brought to an attached state
2653 * for any reason, skip to the end. We cannot
2654 * safely call VUpdateVolume unless we "own" it.
2658 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2662 VUpdateVolume_r(ec, vp, 0);
2664 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2668 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2669 #ifndef AFS_DEMAND_ATTACH_FS
2670 /* This is a hack: by temporarily setting the incore
2671 * dontSalvage flag ON, the volume will be put back on the
2672 * Update list (with dontSalvage OFF again). It will then
2673 * come back in N minutes with DONT_SALVAGE eventually
2674 * set. This is the way that volumes that have never had
2675 * it set get it set; or that volumes that have been
2676 * offline without DONT SALVAGE having been set also
2677 * eventually get it set */
2678 V_dontSalvage(vp) = DONT_SALVAGE;
2679 #endif /* !AFS_DEMAND_ATTACH_FS */
2680 VAddToVolumeUpdateList_r(ec, vp);
2682 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2689 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2693 VCancelReservation_r(nvp);
2696 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2697 if (vp && !VIsErrorState(V_attachState(vp))) {
2698 VChangeState_r(vp, VOL_STATE_ERROR);
2707 * lock a volume on disk (non-blocking).
2709 * @param[in] vp The volume to lock
2710 * @param[in] locktype READ_LOCK or WRITE_LOCK
2712 * @return operation status
2713 * @retval 0 success, lock was obtained
2714 * @retval EBUSY a conflicting lock was held by another process
2715 * @retval EIO error acquiring lock
2717 * @pre If we're in the fileserver, vp is in an exclusive state
2719 * @pre vp is not already locked
2722 VLockVolumeNB(Volume *vp, int locktype)
2726 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2727 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2729 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2731 V_attachFlags(vp) |= VOL_LOCKED;
2738 * unlock a volume on disk that was locked with VLockVolumeNB.
2740 * @param[in] vp volume to unlock
2742 * @pre If we're in the fileserver, vp is in an exclusive state
2744 * @pre vp has already been locked
2747 VUnlockVolume(Volume *vp)
2749 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2750 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2752 VUnlockVolumeById(vp->hashid, vp->partition);
2754 V_attachFlags(vp) &= ~VOL_LOCKED;
2756 #endif /* AFS_DEMAND_ATTACH_FS */
2759 * read in a vol header, possibly lock the vol header, and possibly check out
2760 * the vol header from the fileserver, as part of volume attachment.
2762 * @param[out] ec error code
2763 * @param[in] vp volume pointer object
2764 * @param[in] partp disk partition object of the attaching partition
2765 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2767 * @param[in] peek 1 to just try to read in the volume header and make sure
2768 * we don't try to lock the vol, or check it out from
2769 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2771 * @param[out] acheckedOut If we successfully checked-out the volume from
2772 * the fileserver (if we needed to), this is set
2773 * to 1, otherwise it is untouched.
2775 * @note As part of DAFS volume attachment, the volume header may be either
2776 * read- or write-locked to ensure mutual exclusion of certain volume
2777 * operations. In some cases in order to determine whether we need to
2778 * read- or write-lock the header, we need to read in the header to see
2779 * if the volume is RW or not. So, if we read in the header under a
2780 * read-lock and determine that we actually need a write-lock on the
2781 * volume header, this function will drop the read lock, acquire a write
2782 * lock, and read the header in again.
2785 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2786 int mode, int peek, int *acheckedOut)
2788 struct VolumeDiskHeader diskHeader;
2789 struct VolumeHeader header;
2792 int lock_tries = 0, checkout_tries = 0;
2794 VolumeId volid = vp->hashid;
2795 #ifdef FSSYNC_BUILD_CLIENT
2796 int checkout, done_checkout = 0;
2797 #endif /* FSSYNC_BUILD_CLIENT */
2798 #ifdef AFS_DEMAND_ATTACH_FS
2799 int locktype = 0, use_locktype = -1;
2800 #endif /* AFS_DEMAND_ATTACH_FS */
2806 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2807 Log("VAttachVolume: retried too many times trying to lock header for "
2808 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2809 VPartitionPath(partp));
2813 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2814 Log("VAttachVolume: retried too many times trying to checkout "
2815 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2816 VPartitionPath(partp));
2821 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2822 /* short-circuit the 'volume does not exist' case */
2827 #ifdef FSSYNC_BUILD_CLIENT
2828 checkout = !done_checkout;
2830 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2832 memset(&res, 0, sizeof(res));
2834 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2837 if (res.hdr.reason == FSYNC_SALVAGE) {
2838 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2839 afs_printable_uint32_lu(volid));
2842 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2843 afs_printable_uint32_lu(volid));
2844 *ec = VNOVOL; /* XXXX */
2852 #ifdef AFS_DEMAND_ATTACH_FS
2853 if (use_locktype < 0) {
2854 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2855 * if it turns out to be RW */
2856 locktype = VVolLockType(mode, 0);
2859 /* a previous try says we should use use_locktype to lock the volume,
2861 locktype = use_locktype;
2864 if (!peek && locktype) {
2865 code = VLockVolumeNB(vp, locktype);
2867 if (code == EBUSY) {
2868 Log("VAttachVolume: another program has vol %lu locked\n",
2869 afs_printable_uint32_lu(volid));
2871 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2872 code, afs_printable_uint32_lu(volid));
2879 #endif /* AFS_DEMAND_ATTACH_FS */
2881 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2891 DiskToVolumeHeader(&header, &diskHeader);
2893 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2894 header.largeVnodeIndex);
2895 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2896 header.smallVnodeIndex);
2897 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2899 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2902 /* only need to do this once */
2904 GetVolumeHeader(vp);
2908 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2909 /* demand attach changes the V_PEEK mechanism
2911 * we can now suck the current disk data structure over
2912 * the fssync interface without going to disk
2914 * (technically, we don't need to restrict this feature
2915 * to demand attach fileservers. However, I'm trying
2916 * to limit the number of common code changes)
2918 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2920 res.payload.len = sizeof(VolumeDiskData);
2921 res.payload.buf = &vp->header->diskstuff;
2923 if (FSYNC_VolOp(vp->hashid,
2925 FSYNC_VOL_QUERY_HDR,
2928 goto disk_header_loaded;
2931 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2932 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2933 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2935 #ifdef AFS_DEMAND_ATTACH_FS
2938 IncUInt64(&VStats.hdr_loads);
2939 IncUInt64(&vp->stats.hdr_loads);
2941 #endif /* AFS_DEMAND_ATTACH_FS */
2944 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2945 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2949 #ifdef AFS_DEMAND_ATTACH_FS
2950 # ifdef FSSYNC_BUILD_CLIENT
2952 # endif /* FSSYNC_BUILD_CLIENT */
2954 /* if the lock type we actually used to lock the volume is different than
2955 * the lock type we should have used, retry with the lock type we should
2957 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2958 if (locktype != use_locktype) {
2962 #endif /* AFS_DEMAND_ATTACH_FS */
2967 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2968 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2970 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2972 if (code == SYNC_DENIED) {
2973 /* must retry checkout; fileserver no longer thinks we have
2979 } else if (code != SYNC_OK) {
2983 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2986 /* either we are going to be called again for a second pass, or we
2987 * encountered an error; clean up in either case */
2989 #ifdef AFS_DEMAND_ATTACH_FS
2990 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2993 #endif /* AFS_DEMAND_ATTACH_FS */
2994 if (vp->linkHandle) {
2995 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2996 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2997 IH_RELEASE(vp->diskDataHandle);
2998 IH_RELEASE(vp->linkHandle);
3004 FreeVolumeHeader(vp);
3014 #ifdef AFS_DEMAND_ATTACH_FS
3016 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3017 Volume *vp, int *acheckedOut)
3021 if (vp->pending_vol_op) {
3025 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3027 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3029 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3030 } else if (code == 0) {
3031 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3034 /* we need the vol header to determine if the volume can be
3035 * left online for the vop, so... get the header */
3039 /* attach header with peek=1 to avoid checking out the volume
3040 * or locking it; we just want the header info, we're not
3041 * messing with the volume itself at all */
3042 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3049 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3050 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3052 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3055 /* make sure we grab a new vol header and re-open stuff on
3056 * actual attachment; we can't keep the data we grabbed, since
3057 * it was not done under a lock and thus not safe */
3058 FreeVolumeHeader(vp);
3059 VReleaseVolumeHandles_r(vp);
3062 /* see if the pending volume op requires exclusive access */
3063 switch (vp->pending_vol_op->vol_op_state) {
3064 case FSSYNC_VolOpPending:
3065 /* this should never happen */
3066 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3069 case FSSYNC_VolOpRunningUnknown:
3070 /* this should never happen; we resolved 'unknown' above */
3071 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3074 case FSSYNC_VolOpRunningOffline:
3075 /* mark the volume down */
3077 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3079 /* do not set V_offlineMessage here; we don't have ownership of
3080 * the volume (and probably do not have the header loaded), so we
3081 * can't alter the disk header */
3083 /* check to see if we should set the specialStatus flag */
3084 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3085 /* don't overwrite specialStatus if it was already set to
3086 * something else (e.g. VMOVED) */
3087 if (!vp->specialStatus) {
3088 vp->specialStatus = VBUSY;
3100 #endif /* AFS_DEMAND_ATTACH_FS */
3103 * volume attachment helper function.
3105 * @param[out] ec error code
3106 * @param[in] volumeId volume ID of the attaching volume
3107 * @param[in] path full path to the volume header .vol file
3108 * @param[in] partp disk partition object for the attaching partition
3109 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3110 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3111 * DAFS) should already be initialized
3112 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3113 * if there is a volume operation running for this volume
3114 * that should set the volume to VBUSY during its run. 0
3115 * otherwise. (see VVolOpSetVBusy_r)
3116 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3118 * @param[out] acheckedOut If we successfully checked-out the volume from
3119 * the fileserver (if we needed to), this is set
3120 * to 1, otherwise it is 0.
3122 * @return pointer to the semi-attached volume pointer
3123 * @retval NULL an error occurred (check value of *ec)
3124 * @retval vp volume successfully attaching
3126 * @pre no locks held
3128 * @post VOL_LOCK held
3131 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3132 Volume * vp, int isbusy, int mode, int *acheckedOut)
3134 /* have we read in the header successfully? */
3135 int read_header = 0;
3137 #ifdef AFS_DEMAND_ATTACH_FS
3138 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3142 /* in the case of an error, to what state should the volume be
3144 VolState error_state = VOL_STATE_ERROR;
3145 #endif /* AFS_DEMAND_ATTACH_FS */
3149 vp->vnodeIndex[vLarge].handle = NULL;
3150 vp->vnodeIndex[vSmall].handle = NULL;
3151 vp->diskDataHandle = NULL;
3152 vp->linkHandle = NULL;
3156 #ifdef AFS_DEMAND_ATTACH_FS
3157 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3159 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3162 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3163 #endif /* !AFS_DEMAND_ATTACH_FS */
3165 if (*ec == VNOVOL) {
3166 /* if the volume doesn't exist, skip straight to 'error' so we don't
3167 * request a salvage */
3169 goto error_notbroken;
3175 /* ensure that we don't override specialStatus if it was set to
3176 * something else (e.g. VMOVED) */
3177 if (isbusy && !vp->specialStatus) {
3178 vp->specialStatus = VBUSY;
3180 vp->shuttingDown = 0;
3181 vp->goingOffline = 0;
3183 #ifdef AFS_DEMAND_ATTACH_FS
3184 vp->stats.last_attach = FT_ApproxTime();
3185 vp->stats.attaches++;
3189 IncUInt64(&VStats.attaches);
3190 vp->cacheCheck = ++VolumeCacheCheck;
3191 /* just in case this ever rolls over */
3192 if (!vp->cacheCheck)
3193 vp->cacheCheck = ++VolumeCacheCheck;
3196 #ifdef AFS_DEMAND_ATTACH_FS
3197 V_attachFlags(vp) |= VOL_HDR_LOADED;
3198 vp->stats.last_hdr_load = vp->stats.last_attach;
3199 #endif /* AFS_DEMAND_ATTACH_FS */
3203 struct IndexFileHeader iHead;
3206 * We just read in the diskstuff part of the header. If the detailed
3207 * volume stats area has not yet been initialized, we should bzero the
3208 * area and mark it as initialized.
3210 if (!(V_stat_initialized(vp))) {
3211 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3212 V_stat_initialized(vp) = 1;
3215 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3216 (char *)&iHead, sizeof(iHead),
3217 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3220 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3225 struct IndexFileHeader iHead;
3227 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3228 (char *)&iHead, sizeof(iHead),
3229 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3232 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3236 #ifdef AFS_NAMEI_ENV
3238 struct versionStamp stamp;
3240 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3241 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3244 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3247 #endif /* AFS_NAMEI_ENV */
3249 #if defined(AFS_DEMAND_ATTACH_FS)
3250 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3252 if (!VCanScheduleSalvage()) {
3253 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3255 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3260 /* volume operation in progress */
3262 goto error_notbroken;
3264 #else /* AFS_DEMAND_ATTACH_FS */
3266 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3267 goto unlocked_error;
3269 #endif /* AFS_DEMAND_ATTACH_FS */
3271 if (V_needsSalvaged(vp)) {
3272 if (vp->specialStatus)
3273 vp->specialStatus = 0;
3275 #if defined(AFS_DEMAND_ATTACH_FS)
3276 if (!VCanScheduleSalvage()) {
3277 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3279 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3282 #else /* AFS_DEMAND_ATTACH_FS */
3284 #endif /* AFS_DEMAND_ATTACH_FS */
3290 vp->nextVnodeUnique = V_uniquifier(vp);
3292 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3293 if (!V_needsSalvaged(vp)) {
3294 V_needsSalvaged(vp) = 1;
3295 VUpdateVolume_r(ec, vp, 0);
3297 #if defined(AFS_DEMAND_ATTACH_FS)
3298 if (!VCanScheduleSalvage()) {
3299 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3301 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3304 #else /* AFS_DEMAND_ATTACH_FS */
3305 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3307 #endif /* AFS_DEMAND_ATTACH_FS */
3312 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3313 /* Only check destroyMe if we are the fileserver, since the
3314 * volserver et al sometimes need to work with volumes with
3315 * destroyMe set. Examples are 'temporary' volumes the
3316 * volserver creates, and when we create a volume (destroyMe
3317 * is set on creation; sometimes a separate volserver
3318 * transaction is created to clear destroyMe).
3321 #if defined(AFS_DEMAND_ATTACH_FS)
3322 /* schedule a salvage so the volume goes away on disk */
3323 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3324 VChangeState_r(vp, VOL_STATE_ERROR);
3327 #endif /* AFS_DEMAND_ATTACH_FS */
3328 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3333 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3334 #ifndef BITMAP_LATER
3335 if (programType == fileServer && VolumeWriteable(vp)) {
3337 for (i = 0; i < nVNODECLASSES; i++) {
3338 VGetBitmap_r(ec, vp, i);
3340 #ifdef AFS_DEMAND_ATTACH_FS
3341 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3343 #endif /* AFS_DEMAND_ATTACH_FS */
3344 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3350 #endif /* BITMAP_LATER */
3352 if (VInit >= 2 && V_needsCallback(vp)) {
3353 if (V_BreakVolumeCallbacks) {
3354 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3355 afs_printable_uint32_lu(V_id(vp)));
3356 V_needsCallback(vp) = 0;
3358 (*V_BreakVolumeCallbacks) (V_id(vp));
3361 VUpdateVolume_r(ec, vp, 0);
3363 #ifdef FSSYNC_BUILD_CLIENT
3364 else if (VCanUseFSSYNC()) {
3365 afs_int32 fsync_code;
3367 V_needsCallback(vp) = 0;
3369 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3373 V_needsCallback(vp) = 1;
3374 Log("Error trying to tell the fileserver to break callbacks for "
3375 "changed volume %lu; error code %ld\n",
3376 afs_printable_uint32_lu(V_id(vp)),
3377 afs_printable_int32_ld(fsync_code));
3379 VUpdateVolume_r(ec, vp, 0);
3382 #endif /* FSSYNC_BUILD_CLIENT */
3385 Log("VAttachVolume: error %d clearing needsCallback on volume "
3386 "%lu; needs salvage\n", (int)*ec,
3387 afs_printable_uint32_lu(V_id(vp)));
3388 #ifdef AFS_DEMAND_ATTACH_FS
3389 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3391 #else /* !AFS_DEMAND_ATTACH_FS */
3393 #endif /* !AFS_DEMAND_ATTACh_FS */
3398 if (programType == fileServer) {
3399 if (vp->specialStatus)
3400 vp->specialStatus = 0;
3401 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3402 V_inUse(vp) = fileServer;
3403 V_offlineMessage(vp)[0] = '\0';
3407 #ifdef AFS_DEMAND_ATTACH_FS
3408 /* Put the vol into PREATTACHED state, so if someone tries to
3409 * access it again, we try to attach, see that we're not blessed,
3410 * and give a VNOVOL error again. Putting it into UNATTACHED state
3411 * would result in a VOFFLINE error instead. */
3412 error_state = VOL_STATE_PREATTACHED;
3413 #endif /* AFS_DEMAND_ATTACH_FS */
3415 /* mimic e.g. GetVolume errors */
3416 if (!V_blessed(vp)) {
3417 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3418 FreeVolumeHeader(vp);
3419 } else if (!V_inService(vp)) {
3420 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3421 FreeVolumeHeader(vp);
3423 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3425 #ifdef AFS_DEMAND_ATTACH_FS
3426 error_state = VOL_STATE_ERROR;
3427 /* see if we can recover */
3428 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0 /*flags*/);
3431 #ifdef AFS_DEMAND_ATTACH_FS
3437 #ifdef AFS_DEMAND_ATTACH_FS
3438 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3439 V_inUse(vp) = programType;
3440 #endif /* AFS_DEMAND_ATTACH_FS */
3441 V_checkoutMode(vp) = mode;
3444 AddVolumeToHashTable(vp, V_id(vp));
3445 #ifdef AFS_DEMAND_ATTACH_FS
3446 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3449 if ((programType != fileServer) ||
3450 (V_inUse(vp) == fileServer)) {
3451 AddVolumeToVByPList_r(vp);
3453 VChangeState_r(vp, VOL_STATE_ATTACHED);
3455 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3461 #ifndef AFS_DEMAND_ATTACH_FS
3467 #ifdef AFS_DEMAND_ATTACH_FS
3468 if (!VIsErrorState(V_attachState(vp))) {
3469 if (VIsErrorState(error_state)) {
3470 Log("attach2: forcing vol %u to error state (state %u flags 0x%x ec %d)\n",
3471 vp->hashid, V_attachState(vp), V_attachFlags(vp), *ec);
3473 VChangeState_r(vp, error_state);
3475 #endif /* AFS_DEMAND_ATTACH_FS */
3478 VReleaseVolumeHandles_r(vp);
3482 #ifdef AFS_DEMAND_ATTACH_FS
3489 #else /* !AFS_DEMAND_ATTACH_FS */
3491 #endif /* !AFS_DEMAND_ATTACH_FS */
3495 /* Attach an existing volume.
3496 The volume also normally goes online at this time.
3497 An offline volume must be reattached to make it go online.
3501 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3505 retVal = VAttachVolume_r(ec, volumeId, mode);
3511 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3514 VGetVolumePath(ec, volumeId, &part, &name);
3518 vp = VGetVolume_r(&error, volumeId);
3520 osi_Assert(V_inUse(vp) == 0);
3521 VDetachVolume_r(ec, vp);
3525 return VAttachVolumeByName_r(ec, part, name, mode);
3528 /* Increment a reference count to a volume, sans context swaps. Requires
3529 * possibly reading the volume header in from the disk, since there's
3530 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3532 * N.B. This call can fail if we can't read in the header!! In this case
3533 * we still guarantee we won't context swap, but the ref count won't be
3534 * incremented (otherwise we'd violate the invariant).
3536 /* NOTE: with the demand attach fileserver extensions, the global lock
3537 * is dropped within VHold */
3538 #ifdef AFS_DEMAND_ATTACH_FS
3540 VHold_r(Volume * vp)
3544 VCreateReservation_r(vp);
3545 VWaitExclusiveState_r(vp);
3547 LoadVolumeHeader(&error, vp);
3549 VCancelReservation_r(vp);
3553 VCancelReservation_r(vp);
3556 #else /* AFS_DEMAND_ATTACH_FS */
3558 VHold_r(Volume * vp)
3562 LoadVolumeHeader(&error, vp);
3568 #endif /* AFS_DEMAND_ATTACH_FS */
3570 /**** volume timeout-related stuff ****/
3572 #ifdef AFS_PTHREAD_ENV
3574 static struct timespec *shutdown_timeout;
3575 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3578 VTimedOut(const struct timespec *ts)
3583 if (ts->tv_sec == 0) {
3584 /* short-circuit; this will have always timed out */
3588 code = gettimeofday(&tv, NULL);
3590 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3591 /* assume no timeout; failure mode is we just wait longer than normal
3592 * instead of returning errors when we shouldn't */
3596 if (tv.tv_sec < ts->tv_sec ||
3597 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3606 * Calculate an absolute timeout.
3608 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3609 * NULL, the memory is not touched
3610 * @param[in] timeout How long the timeout should be from now
3612 * @return timeout to use
3613 * @retval NULL no timeout; wait forever
3614 * @retval non-NULL the given value for "ts"
3618 static struct timespec *
3619 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3629 ts->tv_sec = ts->tv_nsec = 0;
3633 code = gettimeofday(&now, NULL);
3635 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3639 ts->tv_sec = now.tv_sec + timeout;
3640 ts->tv_nsec = now.tv_usec * 1000;
3646 * Initialize the shutdown_timeout global.
3649 VShutdownTimeoutInit(void)
3651 struct timespec *ts;
3653 ts = malloc(sizeof(*ts));
3655 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3657 if (!shutdown_timeout) {
3663 * Figure out the timeout that should be used for waiting for offline volumes.
3665 * @param[out] ats Storage space for a local timeout value if needed
3667 * @return The timeout value that should be used
3668 * @retval NULL No timeout; wait forever for offlining volumes
3669 * @retval non-NULL A pointer to the absolute time that should be used as
3670 * the deadline for waiting for offlining volumes.
3672 * @note If we return non-NULL, the pointer we return may or may not be the
3675 static const struct timespec *
3676 VOfflineTimeout(struct timespec *ats)
3678 if (vol_shutting_down) {
3679 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3680 return shutdown_timeout;
3682 return VCalcTimeout(ats, vol_opts.offline_timeout);
3686 #else /* AFS_PTHREAD_ENV */
3688 /* Waiting a certain amount of time for offlining volumes is not supported
3689 * for LWP due to a lack of primitives. So, we never time out */
3690 # define VTimedOut(x) (0)
3691 # define VOfflineTimeout(x) (NULL)
3693 #endif /* !AFS_PTHREAD_ENV */
3701 retVal = VHold_r(vp);
3708 VIsGoingOffline_r(struct Volume *vp)
3712 if (vp->goingOffline) {
3713 if (vp->specialStatus) {
3714 code = vp->specialStatus;
3715 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3726 * Tell the caller if a volume is waiting to go offline.
3728 * @param[in] vp The volume we want to know about
3730 * @return volume status
3731 * @retval 0 volume is not waiting to go offline, go ahead and use it
3732 * @retval nonzero volume is waiting to offline, and give the returned code
3733 * as an error to anyone accessing the volume
3735 * @pre VOL_LOCK is NOT held
3736 * @pre caller holds a heavyweight reference on vp
3739 VIsGoingOffline(struct Volume *vp)
3744 code = VIsGoingOffline_r(vp);
3751 * Register an RX call with a volume.
3753 * @param[inout] ec Error code; if unset when passed in, may be set if
3754 * the volume starts going offline
3755 * @param[out] client_ec @see GetVolume
3756 * @param[in] vp Volume struct
3757 * @param[in] cbv VCallByVol struct containing the RX call to register
3759 * @pre VOL_LOCK held
3760 * @pre caller holds heavy ref on vp
3765 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3768 #ifdef AFS_DEMAND_ATTACH_FS
3770 /* just in case the volume started going offline after we got the
3771 * reference to it... otherwise, if the volume started going
3772 * offline right at the end of GetVolume(), we might race with the
3773 * RX call scanner, and return success and add our cbv to the
3774 * rx_call_list _after_ the scanner has scanned the list. */
3775 *ec = VIsGoingOffline_r(vp);
3781 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3782 VWaitStateChange_r(vp);
3784 #endif /* AFS_DEMAND_ATTACH_FS */
3786 queue_Prepend(&vp->rx_call_list, cbv);
3791 * Deregister an RX call with a volume.
3793 * @param[in] vp Volume struct
3794 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3796 * @pre VOL_LOCK held
3797 * @pre caller holds heavy ref on vp
3802 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3804 if (cbv && queue_IsOnQueue(cbv)) {
3805 #ifdef AFS_DEMAND_ATTACH_FS
3806 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3807 VWaitStateChange_r(vp);
3809 #endif /* AFS_DEMAND_ATTACH_FS */