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)
139 #ifdef AFS_PTHREAD_ENV
140 pthread_mutex_t vol_glock_mutex;
141 pthread_mutex_t vol_trans_mutex;
142 pthread_cond_t vol_put_volume_cond;
143 pthread_cond_t vol_sleep_cond;
144 pthread_cond_t vol_init_attach_cond;
145 pthread_cond_t vol_vinit_cond;
146 int vol_attach_threads = 1;
147 #endif /* AFS_PTHREAD_ENV */
149 /* start-time configurable I/O parameters */
150 ih_init_params vol_io_params;
152 #ifdef AFS_DEMAND_ATTACH_FS
153 pthread_mutex_t vol_salvsync_mutex;
156 * Set this to 1 to disallow SALVSYNC communication in all threads; used
157 * during shutdown, since the salvageserver may have gone away.
159 static volatile sig_atomic_t vol_disallow_salvsync = 0;
160 #endif /* AFS_DEMAND_ATTACH_FS */
163 * has VShutdown_r been called / is VShutdown_r running?
165 static int vol_shutting_down = 0;
168 extern void *calloc(), *realloc();
171 /* Forward declarations */
172 static Volume *attach2(Error * ec, VolId volumeId, char *path,
173 struct DiskPartition64 *partp, Volume * vp,
174 int isbusy, int mode, int *acheckedOut);
175 static void ReallyFreeVolume(Volume * vp);
176 #ifdef AFS_DEMAND_ATTACH_FS
177 static void FreeVolume(Volume * vp);
178 #else /* !AFS_DEMAND_ATTACH_FS */
179 #define FreeVolume(vp) ReallyFreeVolume(vp)
180 static void VScanUpdateList(void);
181 #endif /* !AFS_DEMAND_ATTACH_FS */
182 static void VInitVolumeHeaderCache(afs_uint32 howMany);
183 static int GetVolumeHeader(Volume * vp);
184 static void ReleaseVolumeHeader(struct volHeader *hd);
185 static void FreeVolumeHeader(Volume * vp);
186 static void AddVolumeToHashTable(Volume * vp, int hashid);
187 static void DeleteVolumeFromHashTable(Volume * vp);
189 static int VHold(Volume * vp);
191 static int VHold_r(Volume * vp);
192 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
193 static void VReleaseVolumeHandles_r(Volume * vp);
194 static void VCloseVolumeHandles_r(Volume * vp);
195 static void LoadVolumeHeader(Error * ec, Volume * vp);
196 static int VCheckOffline(Volume * vp);
197 static int VCheckDetach(Volume * vp);
198 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
199 Volume * hint, const struct timespec *ts);
201 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
202 * defined when not linked with vice, XXXX */
203 ProgramType programType; /* The type of program using the package */
204 static VolumePackageOptions vol_opts;
206 /* extended volume package statistics */
209 #ifdef VOL_LOCK_DEBUG
210 pthread_t vol_glock_holder = 0;
214 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
215 /* Must be a multiple of 4 (1 word) !! */
217 /* this parameter needs to be tunable at runtime.
218 * 128 was really inadequate for largish servers -- at 16384 volumes this
219 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
220 * talk about bad spatial locality...
222 * an AVL or splay tree might work a lot better, but we'll just increase
223 * the default hash table size for now
225 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
226 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
227 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
230 * turn volume hash chains into partially ordered lists.
231 * when the threshold is exceeded between two adjacent elements,
232 * perform a chain rebalancing operation.
234 * keep the threshold high in order to keep cache line invalidates
235 * low "enough" on SMPs
237 #define VOLUME_HASH_REORDER_THRESHOLD 200
240 * when possible, don't just reorder single elements, but reorder
241 * entire chains of elements at once. a chain of elements that
242 * exceed the element previous to the pivot by at least CHAIN_THRESH
243 * accesses are moved in front of the chain whose elements have at
244 * least CHAIN_THRESH less accesses than the pivot element
246 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
248 #include "rx/rx_queue.h"
251 VolumeHashTable_t VolumeHashTable = {
252 DEFAULT_VOLUME_HASH_SIZE,
253 DEFAULT_VOLUME_HASH_MASK,
258 static void VInitVolumeHash(void);
262 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
266 afs_int32 ffs_tmp = x;
270 for (ffs_i = 1;; ffs_i++) {
277 #endif /* !AFS_HAVE_FFS */
279 #ifdef AFS_PTHREAD_ENV
281 * disk partition queue element
283 typedef struct diskpartition_queue_t {
284 struct rx_queue queue; /**< queue header */
285 struct DiskPartition64 *diskP; /**< disk partition table entry */
286 } diskpartition_queue_t;
288 #ifndef AFS_DEMAND_ATTACH_FS
290 typedef struct vinitvolumepackage_thread_t {
291 struct rx_queue queue;
292 pthread_cond_t thread_done_cv;
293 int n_threads_complete;
294 } vinitvolumepackage_thread_t;
295 static void * VInitVolumePackageThread(void * args);
297 #else /* !AFS_DEMAND_ATTTACH_FS */
298 #define VINIT_BATCH_MAX_SIZE 512
301 * disk partition work queue
303 struct partition_queue {
304 struct rx_queue head; /**< diskpartition_queue_t queue */
305 pthread_mutex_t mutex;
310 * volumes parameters for preattach
312 struct volume_init_batch {
313 struct rx_queue queue; /**< queue header */
314 int thread; /**< posting worker thread */
315 int last; /**< indicates thread is done */
316 int size; /**< number of volume ids in batch */
317 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
321 * volume parameters work queue
323 struct volume_init_queue {
324 struct rx_queue head; /**< volume_init_batch queue */
325 pthread_mutex_t mutex;
330 * volume init worker thread parameters
332 struct vinitvolumepackage_thread_param {
333 int nthreads; /**< total number of worker threads */
334 int thread; /**< thread number for this worker thread */
335 struct partition_queue *pq; /**< queue partitions to scan */
336 struct volume_init_queue *vq; /**< queue of volume to preattach */
339 static void *VInitVolumePackageThread(void *args);
340 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
341 static VolId VInitNextVolumeId(DIR *dirp);
342 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
344 #endif /* !AFS_DEMAND_ATTACH_FS */
345 #endif /* AFS_PTHREAD_ENV */
347 #ifndef AFS_DEMAND_ATTACH_FS
348 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
349 int * nAttached, int * nUnattached);
350 #endif /* AFS_DEMAND_ATTACH_FS */
353 #ifdef AFS_DEMAND_ATTACH_FS
354 /* demand attach fileserver extensions */
357 * in the future we will support serialization of VLRU state into the fs_state
360 * these structures are the beginning of that effort
362 struct VLRU_DiskHeader {
363 struct versionStamp stamp; /* magic and structure version number */
364 afs_uint32 mtime; /* time of dump to disk */
365 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
368 struct VLRU_DiskEntry {
369 afs_uint32 vid; /* volume ID */
370 afs_uint32 idx; /* generation */
371 afs_uint32 last_get; /* timestamp of last get */
374 struct VLRU_StartupQueue {
375 struct VLRU_DiskEntry * entry;
380 typedef struct vshutdown_thread_t {
382 pthread_mutex_t lock;
384 pthread_cond_t master_cv;
386 int n_threads_complete;
388 int schedule_version;
391 byte n_parts_done_pass;
392 byte part_thread_target[VOLMAXPARTS+1];
393 byte part_done_pass[VOLMAXPARTS+1];
394 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
395 int stats[4][VOLMAXPARTS+1];
396 } vshutdown_thread_t;
397 static void * VShutdownThread(void * args);
400 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
401 static int VCheckFree(Volume * vp);
404 static void AddVolumeToVByPList_r(Volume * vp);
405 static void DeleteVolumeFromVByPList_r(Volume * vp);
406 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
407 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
408 static void VVByPListWait_r(struct DiskPartition64 * dp);
410 /* online salvager */
411 static int VCheckSalvage(Volume * vp);
412 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
413 static int VScheduleSalvage_r(Volume * vp);
416 /* Volume hash table */
417 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
418 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
419 static void VHashEndExclusive_r(VolumeHashChainHead * head);
420 static void VHashWait_r(VolumeHashChainHead * head);
423 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
424 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
425 struct rx_queue ** idx);
426 static void ShutdownController(vshutdown_thread_t * params);
427 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
430 static void VLRU_ComputeConstants(void);
431 static void VInitVLRU(void);
432 static void VLRU_Init_Node_r(Volume * vp);
433 static void VLRU_Add_r(Volume * vp);
434 static void VLRU_Delete_r(Volume * vp);
435 static void VLRU_UpdateAccess_r(Volume * vp);
436 static void * VLRU_ScannerThread(void * args);
437 static void VLRU_Scan_r(int idx);
438 static void VLRU_Promote_r(int idx);
439 static void VLRU_Demote_r(int idx);
440 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
443 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
444 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
445 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
448 pthread_key_t VThread_key;
449 VThreadOptions_t VThread_defaults = {
450 0 /**< allow salvsync */
452 #endif /* AFS_DEMAND_ATTACH_FS */
455 struct Lock vol_listLock; /* Lock obtained when listing volumes:
456 * prevents a volume from being missed
457 * if the volume is attached during a
461 /* Common message used when the volume goes off line */
462 char *VSalvageMessage =
463 "Files in this volume are currently unavailable; call operations";
465 int VInit; /* 0 - uninitialized,
466 * 1 - initialized but not all volumes have been attached,
467 * 2 - initialized and all volumes have been attached,
468 * 3 - initialized, all volumes have been attached, and
469 * VConnectFS() has completed. */
471 static int vinit_attach_abort = 0;
473 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
474 * used to stamp volume headers and in-core
475 * vnodes. When the volume goes on-line the
476 * vnode will be invalidated
477 * access only with VOL_LOCK held */
482 /***************************************************/
483 /* Startup routines */
484 /***************************************************/
486 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
487 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
488 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
492 * assign default values to a VolumePackageOptions struct.
494 * Always call this on a VolumePackageOptions struct first, then set any
495 * specific options you want, then call VInitVolumePackage2.
497 * @param[in] pt caller's program type
498 * @param[out] opts volume package options
501 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
503 opts->nLargeVnodes = opts->nSmallVnodes = 5;
506 opts->canScheduleSalvage = 0;
507 opts->canUseFSSYNC = 0;
508 opts->canUseSALVSYNC = 0;
510 opts->interrupt_rxcall = NULL;
511 opts->offline_timeout = -1;
512 opts->offline_shutdown_timeout = -1;
515 opts->unsafe_attach = 1;
516 #else /* !FAST_RESTART */
517 opts->unsafe_attach = 0;
518 #endif /* !FAST_RESTART */
522 opts->canScheduleSalvage = 1;
523 opts->canUseSALVSYNC = 1;
527 opts->canUseFSSYNC = 1;
531 opts->nLargeVnodes = 0;
532 opts->nSmallVnodes = 0;
534 opts->canScheduleSalvage = 1;
535 opts->canUseFSSYNC = 1;
545 * Set VInit to a certain value, and signal waiters.
547 * @param[in] value the value to set VInit to
552 VSetVInit_r(int value)
555 CV_BROADCAST(&vol_vinit_cond);
559 VLogOfflineTimeout(const char *type, afs_int32 timeout)
565 Log("VInitVolumePackage: Interrupting clients accessing %s "
566 "immediately\n", type);
568 Log("VInitVolumePackage: Interrupting clients accessing %s "
569 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
574 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
576 int errors = 0; /* Number of errors while finding vice partitions. */
581 #ifndef AFS_PTHREAD_ENV
582 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
583 Log("VInitVolumePackage: offline_timeout and/or "
584 "offline_shutdown_timeout was specified, but the volume package "
585 "does not support these for LWP builds\n");
589 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
590 VLogOfflineTimeout("volumes going offline during shutdown",
591 opts->offline_shutdown_timeout);
593 memset(&VStats, 0, sizeof(VStats));
594 VStats.hdr_cache_size = 200;
596 VInitPartitionPackage();
598 #ifdef AFS_DEMAND_ATTACH_FS
599 if (programType == fileServer) {
602 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
604 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
607 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
608 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
609 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
610 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
611 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
612 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
613 #ifndef AFS_PTHREAD_ENV
615 #endif /* AFS_PTHREAD_ENV */
616 Lock_Init(&vol_listLock);
618 srandom(time(0)); /* For VGetVolumeInfo */
620 #ifdef AFS_DEMAND_ATTACH_FS
621 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
622 #endif /* AFS_DEMAND_ATTACH_FS */
624 /* Ok, we have done enough initialization that fileserver can
625 * start accepting calls, even though the volumes may not be
626 * available just yet.
630 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
631 if (programType == salvageServer) {
634 #endif /* AFS_DEMAND_ATTACH_FS */
635 #ifdef FSSYNC_BUILD_SERVER
636 if (programType == fileServer) {
640 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
641 if (VCanUseSALVSYNC()) {
642 /* establish a connection to the salvager at this point */
643 osi_Assert(VConnectSALV() != 0);
645 #endif /* AFS_DEMAND_ATTACH_FS */
647 if (opts->volcache > VStats.hdr_cache_size)
648 VStats.hdr_cache_size = opts->volcache;
649 VInitVolumeHeaderCache(VStats.hdr_cache_size);
651 VInitVnodes(vLarge, opts->nLargeVnodes);
652 VInitVnodes(vSmall, opts->nSmallVnodes);
655 errors = VAttachPartitions();
659 if (programType != fileServer) {
660 errors = VInitAttachVolumes(programType);
666 #ifdef FSSYNC_BUILD_CLIENT
667 if (VCanUseFSSYNC()) {
669 #ifdef AFS_DEMAND_ATTACH_FS
670 if (programType == salvageServer) {
671 Log("Unable to connect to file server; aborted\n");
674 #endif /* AFS_DEMAND_ATTACH_FS */
675 Log("Unable to connect to file server; will retry at need\n");
678 #endif /* FSSYNC_BUILD_CLIENT */
683 #if !defined(AFS_PTHREAD_ENV)
685 * Attach volumes in vice partitions
687 * @param[in] pt calling program type
690 * @note This is the original, non-threaded version of attach parititions.
692 * @post VInit state is 2
695 VInitAttachVolumes(ProgramType pt)
697 osi_Assert(VInit==1);
698 if (pt == fileServer) {
699 struct DiskPartition64 *diskP;
700 /* Attach all the volumes in this partition */
701 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
702 int nAttached = 0, nUnattached = 0;
703 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
707 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
708 LWP_NoYieldSignal(VInitAttachVolumes);
712 #endif /* !AFS_PTHREAD_ENV */
714 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
716 * Attach volumes in vice partitions
718 * @param[in] pt calling program type
721 * @note Threaded version of attach parititions.
723 * @post VInit state is 2
726 VInitAttachVolumes(ProgramType pt)
728 osi_Assert(VInit==1);
729 if (pt == fileServer) {
730 struct DiskPartition64 *diskP;
731 struct vinitvolumepackage_thread_t params;
732 struct diskpartition_queue_t * dpq;
733 int i, threads, parts;
735 pthread_attr_t attrs;
737 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
739 params.n_threads_complete = 0;
741 /* create partition work queue */
742 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
743 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
744 osi_Assert(dpq != NULL);
746 queue_Append(¶ms,dpq);
749 threads = MIN(parts, vol_attach_threads);
752 /* spawn off a bunch of initialization threads */
753 osi_Assert(pthread_attr_init(&attrs) == 0);
754 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
756 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
757 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
761 for (i=0; i < threads; i++) {
764 osi_Assert(pthread_create
765 (&tid, &attrs, &VInitVolumePackageThread,
767 AFS_SIGSET_RESTORE();
770 while(params.n_threads_complete < threads) {
771 VOL_CV_WAIT(¶ms.thread_done_cv);
775 osi_Assert(pthread_attr_destroy(&attrs) == 0);
777 /* if we're only going to run one init thread, don't bother creating
779 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
780 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
783 VInitVolumePackageThread(¶ms);
786 CV_DESTROY(¶ms.thread_done_cv);
789 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
790 CV_BROADCAST(&vol_init_attach_cond);
796 VInitVolumePackageThread(void * args) {
798 struct DiskPartition64 *diskP;
799 struct vinitvolumepackage_thread_t * params;
800 struct diskpartition_queue_t * dpq;
802 params = (vinitvolumepackage_thread_t *) args;
806 /* Attach all the volumes in this partition */
807 while (queue_IsNotEmpty(params)) {
808 int nAttached = 0, nUnattached = 0;
810 if (vinit_attach_abort) {
811 Log("Aborting initialization\n");
815 dpq = queue_First(params,diskpartition_queue_t);
821 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
827 params->n_threads_complete++;
828 CV_SIGNAL(¶ms->thread_done_cv);
832 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
834 #if defined(AFS_DEMAND_ATTACH_FS)
836 * Attach volumes in vice partitions
838 * @param[in] pt calling program type
841 * @note Threaded version of attach partitions.
843 * @post VInit state is 2
846 VInitAttachVolumes(ProgramType pt)
848 osi_Assert(VInit==1);
849 if (pt == fileServer) {
851 struct DiskPartition64 *diskP;
852 struct partition_queue pq;
853 struct volume_init_queue vq;
855 int i, threads, parts;
857 pthread_attr_t attrs;
859 /* create partition work queue */
861 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
862 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
863 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
864 struct diskpartition_queue_t *dp;
865 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
866 osi_Assert(dp != NULL);
868 queue_Append(&pq, dp);
871 /* number of worker threads; at least one, not to exceed the number of partitions */
872 threads = MIN(parts, vol_attach_threads);
874 /* create volume work queue */
876 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
877 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
879 osi_Assert(pthread_attr_init(&attrs) == 0);
880 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
882 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
883 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
886 /* create threads to scan disk partitions. */
887 for (i=0; i < threads; i++) {
888 struct vinitvolumepackage_thread_param *params;
891 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
895 params->nthreads = threads;
896 params->thread = i+1;
899 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
900 AFS_SIGSET_RESTORE();
903 VInitPreAttachVolumes(threads, &vq);
905 osi_Assert(pthread_attr_destroy(&attrs) == 0);
907 MUTEX_DESTROY(&pq.mutex);
909 MUTEX_DESTROY(&vq.mutex);
913 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
914 CV_BROADCAST(&vol_init_attach_cond);
921 * Volume package initialization worker thread. Scan partitions for volume
922 * header files. Gather batches of volume ids and dispatch them to
923 * the main thread to be preattached. The volume preattachement is done
924 * in the main thread to avoid global volume lock contention.
927 VInitVolumePackageThread(void *args)
929 struct vinitvolumepackage_thread_param *params;
930 struct DiskPartition64 *partition;
931 struct partition_queue *pq;
932 struct volume_init_queue *vq;
933 struct volume_init_batch *vb;
936 params = (struct vinitvolumepackage_thread_param *)args;
942 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
944 vb->thread = params->thread;
948 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
949 while((partition = VInitNextPartition(pq))) {
953 Log("Partition %s: pre-attaching volumes\n", partition->name);
954 dirp = opendir(VPartitionPath(partition));
956 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
959 while ((vid = VInitNextVolumeId(dirp))) {
960 Volume *vp = (Volume*)malloc(sizeof(Volume));
962 memset(vp, 0, sizeof(Volume));
963 vp->device = partition->device;
964 vp->partition = partition;
966 queue_Init(&vp->vnode_list);
967 queue_Init(&vp->rx_call_list);
968 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
970 vb->batch[vb->size++] = vp;
971 if (vb->size == VINIT_BATCH_MAX_SIZE) {
972 MUTEX_ENTER(&vq->mutex);
973 queue_Append(vq, vb);
974 CV_BROADCAST(&vq->cv);
975 MUTEX_EXIT(&vq->mutex);
977 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
979 vb->thread = params->thread;
988 MUTEX_ENTER(&vq->mutex);
989 queue_Append(vq, vb);
990 CV_BROADCAST(&vq->cv);
991 MUTEX_EXIT(&vq->mutex);
993 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
999 * Read next element from the pre-populated partition list.
1001 static struct DiskPartition64*
1002 VInitNextPartition(struct partition_queue *pq)
1004 struct DiskPartition64 *partition;
1005 struct diskpartition_queue_t *dp; /* queue element */
1007 if (vinit_attach_abort) {
1008 Log("Aborting volume preattach thread.\n");
1012 /* get next partition to scan */
1013 MUTEX_ENTER(&pq->mutex);
1014 if (queue_IsEmpty(pq)) {
1015 MUTEX_EXIT(&pq->mutex);
1018 dp = queue_First(pq, diskpartition_queue_t);
1020 MUTEX_EXIT(&pq->mutex);
1023 osi_Assert(dp->diskP);
1025 partition = dp->diskP;
1031 * Find next volume id on the partition.
1034 VInitNextVolumeId(DIR *dirp)
1040 while((d = readdir(dirp))) {
1041 if (vinit_attach_abort) {
1042 Log("Aborting volume preattach thread.\n");
1045 ext = strrchr(d->d_name, '.');
1046 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1047 vid = VolumeNumber(d->d_name);
1051 Log("Warning: bogus volume header file: %s\n", d->d_name);
1058 * Preattach volumes in batches to avoid lock contention.
1061 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1063 struct volume_init_batch *vb;
1067 /* dequeue next volume */
1068 MUTEX_ENTER(&vq->mutex);
1069 if (queue_IsEmpty(vq)) {
1070 CV_WAIT(&vq->cv, &vq->mutex);
1072 vb = queue_First(vq, volume_init_batch);
1074 MUTEX_EXIT(&vq->mutex);
1078 for (i = 0; i<vb->size; i++) {
1084 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1086 Log("Error looking up volume, code=%d\n", ec);
1089 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1092 /* put pre-attached volume onto the hash table
1093 * and bring it up to the pre-attached state */
1094 AddVolumeToHashTable(vp, vp->hashid);
1095 AddVolumeToVByPList_r(vp);
1096 VLRU_Init_Node_r(vp);
1097 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1110 #endif /* AFS_DEMAND_ATTACH_FS */
1112 #if !defined(AFS_DEMAND_ATTACH_FS)
1114 * attach all volumes on a given disk partition
1117 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1123 Log("Partition %s: attaching volumes\n", diskP->name);
1124 dirp = opendir(VPartitionPath(diskP));
1126 Log("opendir on Partition %s failed!\n", diskP->name);
1130 while ((dp = readdir(dirp))) {
1132 p = strrchr(dp->d_name, '.');
1134 if (vinit_attach_abort) {
1135 Log("Partition %s: abort attach volumes\n", diskP->name);
1139 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1142 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1144 (*(vp ? nAttached : nUnattached))++;
1145 if (error == VOFFLINE)
1146 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1147 else if (LogLevel >= 5) {
1148 Log("Partition %s: attached volume %d (%s)\n",
1149 diskP->name, VolumeNumber(dp->d_name),
1158 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1163 #endif /* !AFS_DEMAND_ATTACH_FS */
1165 /***************************************************/
1166 /* Shutdown routines */
1167 /***************************************************/
1171 * highly multithreaded volume package shutdown
1173 * with the demand attach fileserver extensions,
1174 * VShutdown has been modified to be multithreaded.
1175 * In order to achieve optimal use of many threads,
1176 * the shutdown code involves one control thread and
1177 * n shutdown worker threads. The control thread
1178 * periodically examines the number of volumes available
1179 * for shutdown on each partition, and produces a worker
1180 * thread allocation schedule. The idea is to eliminate
1181 * redundant scheduling computation on the workers by
1182 * having a single master scheduler.
1184 * The scheduler's objectives are:
1186 * each partition with volumes remaining gets allocated
1187 * at least 1 thread (assuming sufficient threads)
1189 * threads are allocated proportional to the number of
1190 * volumes remaining to be offlined. This ensures that
1191 * the OS I/O scheduler has many requests to elevator
1192 * seek on partitions that will (presumably) take the
1193 * longest amount of time (from now) to finish shutdown
1194 * (3) keep threads busy
1195 * when there are extra threads, they are assigned to
1196 * partitions using a simple round-robin algorithm
1198 * In the future, we may wish to add the ability to adapt
1199 * to the relative performance patterns of each disk
1204 * multi-step shutdown process
1206 * demand attach shutdown is a four-step process. Each
1207 * shutdown "pass" shuts down increasingly more difficult
1208 * volumes. The main purpose is to achieve better cache
1209 * utilization during shutdown.
1212 * shutdown volumes in the unattached, pre-attached
1215 * shutdown attached volumes with cached volume headers
1217 * shutdown all volumes in non-exclusive states
1219 * shutdown all remaining volumes
1222 #ifdef AFS_DEMAND_ATTACH_FS
1228 struct DiskPartition64 * diskP;
1229 struct diskpartition_queue_t * dpq;
1230 vshutdown_thread_t params;
1232 pthread_attr_t attrs;
1234 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1237 Log("VShutdown: aborting attach volumes\n");
1238 vinit_attach_abort = 1;
1239 VOL_CV_WAIT(&vol_init_attach_cond);
1242 for (params.n_parts=0, diskP = DiskPartitionList;
1243 diskP; diskP = diskP->next, params.n_parts++);
1245 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1246 params.n_parts, params.n_parts > 1 ? "s" : "");
1248 vol_shutting_down = 1;
1250 if (vol_attach_threads > 1) {
1251 /* prepare for parallel shutdown */
1252 params.n_threads = vol_attach_threads;
1253 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1254 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1255 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1256 osi_Assert(pthread_attr_init(&attrs) == 0);
1257 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1258 queue_Init(¶ms);
1260 /* setup the basic partition information structures for
1261 * parallel shutdown */
1262 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1264 struct rx_queue * qp, * nqp;
1268 VVByPListWait_r(diskP);
1269 VVByPListBeginExclusive_r(diskP);
1272 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1273 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1277 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1278 VPartitionPath(diskP), count);
1281 /* build up the pass 0 shutdown work queue */
1282 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1283 osi_Assert(dpq != NULL);
1285 queue_Prepend(¶ms, dpq);
1287 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1290 Log("VShutdown: beginning parallel fileserver shutdown\n");
1291 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1292 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1294 /* do pass 0 shutdown */
1295 MUTEX_ENTER(¶ms.lock);
1296 for (i=0; i < params.n_threads; i++) {
1297 osi_Assert(pthread_create
1298 (&tid, &attrs, &VShutdownThread,
1302 /* wait for all the pass 0 shutdowns to complete */
1303 while (params.n_threads_complete < params.n_threads) {
1304 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1306 params.n_threads_complete = 0;
1308 CV_BROADCAST(¶ms.cv);
1309 MUTEX_EXIT(¶ms.lock);
1311 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1312 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1314 /* run the parallel shutdown scheduler. it will drop the glock internally */
1315 ShutdownController(¶ms);
1317 /* wait for all the workers to finish pass 3 and terminate */
1318 while (params.pass < 4) {
1319 VOL_CV_WAIT(¶ms.cv);
1322 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1323 CV_DESTROY(¶ms.cv);
1324 CV_DESTROY(¶ms.master_cv);
1325 MUTEX_DESTROY(¶ms.lock);
1327 /* drop the VByPList exclusive reservations */
1328 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1329 VVByPListEndExclusive_r(diskP);
1330 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1331 VPartitionPath(diskP),
1332 params.stats[0][diskP->index],
1333 params.stats[1][diskP->index],
1334 params.stats[2][diskP->index],
1335 params.stats[3][diskP->index]);
1338 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1340 /* if we're only going to run one shutdown thread, don't bother creating
1342 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1344 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1345 VShutdownByPartition_r(diskP);
1349 Log("VShutdown: complete.\n");
1352 #else /* AFS_DEMAND_ATTACH_FS */
1362 Log("VShutdown: aborting attach volumes\n");
1363 vinit_attach_abort = 1;
1364 #ifdef AFS_PTHREAD_ENV
1365 VOL_CV_WAIT(&vol_init_attach_cond);
1367 LWP_WaitProcess(VInitAttachVolumes);
1368 #endif /* AFS_PTHREAD_ENV */
1371 Log("VShutdown: shutting down on-line volumes...\n");
1372 vol_shutting_down = 1;
1373 for (i = 0; i < VolumeHashTable.Size; i++) {
1374 /* try to hold first volume in the hash table */
1375 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1379 Log("VShutdown: Attempting to take volume %u offline.\n",
1382 /* next, take the volume offline (drops reference count) */
1383 VOffline_r(vp, "File server was shut down");
1387 Log("VShutdown: complete.\n");
1389 #endif /* AFS_DEMAND_ATTACH_FS */
1395 osi_Assert(VInit>0);
1402 * stop new activity (e.g. SALVSYNC) from occurring
1404 * Use this to make the volume package less busy; for example, during
1405 * shutdown. This doesn't actually shutdown/detach anything in the
1406 * volume package, but prevents certain processes from ocurring. For
1407 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1408 * could also use this to prevent new volume attachment, or prevent
1409 * other programs from checking out volumes, etc.
1414 #ifdef AFS_DEMAND_ATTACH_FS
1415 /* make sure we don't try to contact the salvageserver, since it may
1416 * not be around anymore */
1417 vol_disallow_salvsync = 1;
1421 #ifdef AFS_DEMAND_ATTACH_FS
1424 * shutdown control thread
1427 ShutdownController(vshutdown_thread_t * params)
1430 struct DiskPartition64 * diskP;
1432 vshutdown_thread_t shadow;
1434 ShutdownCreateSchedule(params);
1436 while ((params->pass < 4) &&
1437 (params->n_threads_complete < params->n_threads)) {
1438 /* recompute schedule once per second */
1440 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1444 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1445 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1446 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1447 shadow.n_threads_complete, shadow.n_parts_done_pass);
1448 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1450 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1452 diskP->vol_list.len,
1453 shadow.part_thread_target[id],
1454 shadow.part_done_pass[id],
1455 shadow.part_pass_head[id]);
1461 ShutdownCreateSchedule(params);
1465 /* create the shutdown thread work schedule.
1466 * this scheduler tries to implement fairness
1467 * by allocating at least 1 thread to each
1468 * partition with volumes to be shutdown,
1469 * and then it attempts to allocate remaining
1470 * threads based upon the amount of work left
1473 ShutdownCreateSchedule(vshutdown_thread_t * params)
1475 struct DiskPartition64 * diskP;
1476 int sum, thr_workload, thr_left;
1477 int part_residue[VOLMAXPARTS+1];
1480 /* compute the total number of outstanding volumes */
1482 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1483 sum += diskP->vol_list.len;
1486 params->schedule_version++;
1487 params->vol_remaining = sum;
1492 /* compute average per-thread workload */
1493 thr_workload = sum / params->n_threads;
1494 if (sum % params->n_threads)
1497 thr_left = params->n_threads;
1498 memset(&part_residue, 0, sizeof(part_residue));
1500 /* for fairness, give every partition with volumes remaining
1501 * at least one thread */
1502 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1504 if (diskP->vol_list.len) {
1505 params->part_thread_target[id] = 1;
1508 params->part_thread_target[id] = 0;
1512 if (thr_left && thr_workload) {
1513 /* compute length-weighted workloads */
1516 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1518 delta = (diskP->vol_list.len / thr_workload) -
1519 params->part_thread_target[id];
1523 if (delta < thr_left) {
1524 params->part_thread_target[id] += delta;
1527 params->part_thread_target[id] += thr_left;
1535 /* try to assign any leftover threads to partitions that
1536 * had volume lengths closer to needing thread_target+1 */
1537 int max_residue, max_id = 0;
1539 /* compute the residues */
1540 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1542 part_residue[id] = diskP->vol_list.len -
1543 (params->part_thread_target[id] * thr_workload);
1546 /* now try to allocate remaining threads to partitions with the
1547 * highest residues */
1550 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1552 if (part_residue[id] > max_residue) {
1553 max_residue = part_residue[id];
1562 params->part_thread_target[max_id]++;
1564 part_residue[max_id] = 0;
1569 /* punt and give any remaining threads equally to each partition */
1571 if (thr_left >= params->n_parts) {
1572 alloc = thr_left / params->n_parts;
1573 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1575 params->part_thread_target[id] += alloc;
1580 /* finish off the last of the threads */
1581 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1583 params->part_thread_target[id]++;
1589 /* worker thread for parallel shutdown */
1591 VShutdownThread(void * args)
1593 vshutdown_thread_t * params;
1594 int found, pass, schedule_version_save, count;
1595 struct DiskPartition64 *diskP;
1596 struct diskpartition_queue_t * dpq;
1599 params = (vshutdown_thread_t *) args;
1601 /* acquire the shutdown pass 0 lock */
1602 MUTEX_ENTER(¶ms->lock);
1604 /* if there's still pass 0 work to be done,
1605 * get a work entry, and do a pass 0 shutdown */
1606 if (queue_IsNotEmpty(params)) {
1607 dpq = queue_First(params, diskpartition_queue_t);
1609 MUTEX_EXIT(¶ms->lock);
1615 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1617 params->stats[0][diskP->index] = count;
1618 MUTEX_ENTER(¶ms->lock);
1621 params->n_threads_complete++;
1622 if (params->n_threads_complete == params->n_threads) {
1623 /* notify control thread that all workers have completed pass 0 */
1624 CV_SIGNAL(¶ms->master_cv);
1626 while (params->pass == 0) {
1627 CV_WAIT(¶ms->cv, ¶ms->lock);
1631 MUTEX_EXIT(¶ms->lock);
1634 pass = params->pass;
1635 osi_Assert(pass > 0);
1637 /* now escalate through the more complicated shutdowns */
1639 schedule_version_save = params->schedule_version;
1641 /* find a disk partition to work on */
1642 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1644 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1645 params->part_thread_target[id]--;
1652 /* hmm. for some reason the controller thread couldn't find anything for
1653 * us to do. let's see if there's anything we can do */
1654 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1656 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1659 } else if (!params->part_done_pass[id]) {
1660 params->part_done_pass[id] = 1;
1661 params->n_parts_done_pass++;
1663 Log("VShutdown: done shutting down volumes on partition %s.\n",
1664 VPartitionPath(diskP));
1670 /* do work on this partition until either the controller
1671 * creates a new schedule, or we run out of things to do
1672 * on this partition */
1675 while (!params->part_done_pass[id] &&
1676 (schedule_version_save == params->schedule_version)) {
1677 /* ShutdownVolumeWalk_r will drop the glock internally */
1678 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1679 if (!params->part_done_pass[id]) {
1680 params->part_done_pass[id] = 1;
1681 params->n_parts_done_pass++;
1683 Log("VShutdown: done shutting down volumes on partition %s.\n",
1684 VPartitionPath(diskP));
1692 params->stats[pass][id] += count;
1694 /* ok, everyone is done this pass, proceed */
1697 params->n_threads_complete++;
1698 while (params->pass == pass) {
1699 if (params->n_threads_complete == params->n_threads) {
1700 /* we are the last thread to complete, so we will
1701 * reinitialize worker pool state for the next pass */
1702 params->n_threads_complete = 0;
1703 params->n_parts_done_pass = 0;
1705 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1707 params->part_done_pass[id] = 0;
1708 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1711 /* compute a new thread schedule before releasing all the workers */
1712 ShutdownCreateSchedule(params);
1714 /* wake up all the workers */
1715 CV_BROADCAST(¶ms->cv);
1718 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1719 pass, params->n_threads, params->n_parts);
1722 VOL_CV_WAIT(¶ms->cv);
1725 pass = params->pass;
1739 /* shut down all volumes on a given disk partition
1741 * note that this function will not allow mp-fast
1742 * shutdown of a partition */
1744 VShutdownByPartition_r(struct DiskPartition64 * dp)
1750 /* wait for other exclusive ops to finish */
1751 VVByPListWait_r(dp);
1753 /* begin exclusive access */
1754 VVByPListBeginExclusive_r(dp);
1756 /* pick the low-hanging fruit first,
1757 * then do the complicated ones last
1758 * (has the advantage of keeping
1759 * in-use volumes up until the bitter end) */
1760 for (pass = 0, total=0; pass < 4; pass++) {
1761 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1762 total += pass_stats[pass];
1765 /* end exclusive access */
1766 VVByPListEndExclusive_r(dp);
1768 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1769 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1774 /* internal shutdown functionality
1776 * for multi-pass shutdown:
1777 * 0 to only "shutdown" {pre,un}attached and error state volumes
1778 * 1 to also shutdown attached volumes w/ volume header loaded
1779 * 2 to also shutdown attached volumes w/o volume header loaded
1780 * 3 to also shutdown exclusive state volumes
1782 * caller MUST hold exclusive access on the hash chain
1783 * because we drop vol_glock_mutex internally
1785 * this function is reentrant for passes 1--3
1786 * (e.g. multiple threads can cooperate to
1787 * shutdown a partition mp-fast)
1789 * pass 0 is not scaleable because the volume state data is
1790 * synchronized by vol_glock mutex, and the locking overhead
1791 * is too high to drop the lock long enough to do linked list
1795 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1797 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1800 while (ShutdownVolumeWalk_r(dp, pass, &q))
1806 /* conditionally shutdown one volume on partition dp
1807 * returns 1 if a volume was shutdown in this pass,
1810 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1811 struct rx_queue ** idx)
1813 struct rx_queue *qp, *nqp;
1818 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1819 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1823 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1824 (V_attachState(vp) != VOL_STATE_ERROR) &&
1825 (V_attachState(vp) != VOL_STATE_DELETED) &&
1826 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1830 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1831 (vp->header == NULL)) {
1835 if (VIsExclusiveState(V_attachState(vp))) {
1840 DeleteVolumeFromVByPList_r(vp);
1841 VShutdownVolume_r(vp);
1851 * shutdown a specific volume
1853 /* caller MUST NOT hold a heavyweight ref on vp */
1855 VShutdownVolume_r(Volume * vp)
1859 VCreateReservation_r(vp);
1861 if (LogLevel >= 5) {
1862 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1863 vp->hashid, vp->partition->device, V_attachState(vp));
1866 /* wait for other blocking ops to finish */
1867 VWaitExclusiveState_r(vp);
1869 osi_Assert(VIsValidState(V_attachState(vp)));
1871 switch(V_attachState(vp)) {
1872 case VOL_STATE_SALVAGING:
1873 /* Leave salvaging volumes alone. Any in-progress salvages will
1874 * continue working after viced shuts down. This is intentional.
1877 case VOL_STATE_PREATTACHED:
1878 case VOL_STATE_ERROR:
1879 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1880 case VOL_STATE_UNATTACHED:
1881 case VOL_STATE_DELETED:
1883 case VOL_STATE_GOING_OFFLINE:
1884 case VOL_STATE_SHUTTING_DOWN:
1885 case VOL_STATE_ATTACHED:
1889 Log("VShutdown: Attempting to take volume %u offline.\n",
1892 /* take the volume offline (drops reference count) */
1893 VOffline_r(vp, "File server was shut down");
1900 VCancelReservation_r(vp);
1904 #endif /* AFS_DEMAND_ATTACH_FS */
1907 /***************************************************/
1908 /* Header I/O routines */
1909 /***************************************************/
1911 /* open a descriptor for the inode (h),
1912 * read in an on-disk structure into buffer (to) of size (size),
1913 * verify versionstamp in structure has magic (magic) and
1914 * optionally verify version (version) if (version) is nonzero
1917 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1920 struct versionStamp *vsn;
1935 vsn = (struct versionStamp *)to;
1936 if (FDH_PREAD(fdP, to, size, 0) != size || vsn->magic != magic) {
1938 FDH_REALLYCLOSE(fdP);
1943 /* Check is conditional, in case caller wants to inspect version himself */
1944 if (version && vsn->version != version) {
1950 WriteVolumeHeader_r(Error * ec, Volume * vp)
1952 IHandle_t *h = V_diskDataHandle(vp);
1962 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1963 != sizeof(V_disk(vp))) {
1965 FDH_REALLYCLOSE(fdP);
1971 /* VolumeHeaderToDisk
1972 * Allows for storing 64 bit inode numbers in on-disk volume header
1975 /* convert in-memory representation of a volume header to the
1976 * on-disk representation of a volume header */
1978 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1981 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1982 dh->stamp = h->stamp;
1984 dh->parent = h->parent;
1986 #ifdef AFS_64BIT_IOPS_ENV
1987 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1988 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1989 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1990 dh->smallVnodeIndex_hi =
1991 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1992 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1993 dh->largeVnodeIndex_hi =
1994 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1995 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1996 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1998 dh->volumeInfo_lo = h->volumeInfo;
1999 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2000 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2001 dh->linkTable_lo = h->linkTable;
2005 /* DiskToVolumeHeader
2006 * Converts an on-disk representation of a volume header to
2007 * the in-memory representation of a volume header.
2009 * Makes the assumption that AFS has *always*
2010 * zero'd the volume header file so that high parts of inode
2011 * numbers are 0 in older (SGI EFS) volume header files.
2014 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2016 memset(h, 0, sizeof(VolumeHeader_t));
2017 h->stamp = dh->stamp;
2019 h->parent = dh->parent;
2021 #ifdef AFS_64BIT_IOPS_ENV
2023 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2025 h->smallVnodeIndex =
2026 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2027 smallVnodeIndex_hi << 32);
2029 h->largeVnodeIndex =
2030 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2031 largeVnodeIndex_hi << 32);
2033 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2035 h->volumeInfo = dh->volumeInfo_lo;
2036 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2037 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2038 h->linkTable = dh->linkTable_lo;
2043 /***************************************************/
2044 /* Volume Attachment routines */
2045 /***************************************************/
2047 #ifdef AFS_DEMAND_ATTACH_FS
2049 * pre-attach a volume given its path.
2051 * @param[out] ec outbound error code
2052 * @param[in] partition partition path string
2053 * @param[in] name volume id string
2055 * @return volume object pointer
2057 * @note A pre-attached volume will only have its partition
2058 * and hashid fields initialized. At first call to
2059 * VGetVolume, the volume will be fully attached.
2063 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2067 vp = VPreAttachVolumeByName_r(ec, partition, name);
2073 * pre-attach a volume given its path.
2075 * @param[out] ec outbound error code
2076 * @param[in] partition path to vice partition
2077 * @param[in] name volume id string
2079 * @return volume object pointer
2081 * @pre VOL_LOCK held
2083 * @internal volume package internal use only.
2086 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2088 return VPreAttachVolumeById_r(ec,
2090 VolumeNumber(name));
2094 * pre-attach a volume given its path and numeric volume id.
2096 * @param[out] ec error code return
2097 * @param[in] partition path to vice partition
2098 * @param[in] volumeId numeric volume id
2100 * @return volume object pointer
2102 * @pre VOL_LOCK held
2104 * @internal volume package internal use only.
2107 VPreAttachVolumeById_r(Error * ec,
2112 struct DiskPartition64 *partp;
2116 osi_Assert(programType == fileServer);
2118 if (!(partp = VGetPartition_r(partition, 0))) {
2120 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2124 vp = VLookupVolume_r(ec, volumeId, NULL);
2129 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2133 * preattach a volume.
2135 * @param[out] ec outbound error code
2136 * @param[in] partp pointer to partition object
2137 * @param[in] vp pointer to volume object
2138 * @param[in] vid volume id
2140 * @return volume object pointer
2142 * @pre VOL_LOCK is held.
2144 * @warning Returned volume object pointer does not have to
2145 * equal the pointer passed in as argument vp. There
2146 * are potential race conditions which can result in
2147 * the pointers having different values. It is up to
2148 * the caller to make sure that references are handled
2149 * properly in this case.
2151 * @note If there is already a volume object registered with
2152 * the same volume id, its pointer MUST be passed as
2153 * argument vp. Failure to do so will result in a silent
2154 * failure to preattach.
2156 * @internal volume package internal use only.
2159 VPreAttachVolumeByVp_r(Error * ec,
2160 struct DiskPartition64 * partp,
2168 /* check to see if pre-attach already happened */
2170 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2171 (V_attachState(vp) != VOL_STATE_DELETED) &&
2172 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2173 !VIsErrorState(V_attachState(vp))) {
2175 * pre-attach is a no-op in all but the following cases:
2177 * - volume is unattached
2178 * - volume is in an error state
2179 * - volume is pre-attached
2181 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2184 /* we're re-attaching a volume; clear out some old state */
2185 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2187 if (V_partition(vp) != partp) {
2188 /* XXX potential race */
2189 DeleteVolumeFromVByPList_r(vp);
2192 /* if we need to allocate a new Volume struct,
2193 * go ahead and drop the vol glock, otherwise
2194 * do the basic setup synchronised, as it's
2195 * probably not worth dropping the lock */
2198 /* allocate the volume structure */
2199 vp = nvp = (Volume *) malloc(sizeof(Volume));
2200 osi_Assert(vp != NULL);
2201 memset(vp, 0, sizeof(Volume));
2202 queue_Init(&vp->vnode_list);
2203 queue_Init(&vp->rx_call_list);
2204 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2207 /* link the volume with its associated vice partition */
2208 vp->device = partp->device;
2209 vp->partition = partp;
2212 vp->specialStatus = 0;
2214 /* if we dropped the lock, reacquire the lock,
2215 * check for pre-attach races, and then add
2216 * the volume to the hash table */
2219 nvp = VLookupVolume_r(ec, vid, NULL);
2224 } else if (nvp) { /* race detected */
2229 /* hack to make up for VChangeState_r() decrementing
2230 * the old state counter */
2231 VStats.state_levels[0]++;
2235 /* put pre-attached volume onto the hash table
2236 * and bring it up to the pre-attached state */
2237 AddVolumeToHashTable(vp, vp->hashid);
2238 AddVolumeToVByPList_r(vp);
2239 VLRU_Init_Node_r(vp);
2240 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2243 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2251 #endif /* AFS_DEMAND_ATTACH_FS */
2253 /* Attach an existing volume, given its pathname, and return a
2254 pointer to the volume header information. The volume also
2255 normally goes online at this time. An offline volume
2256 must be reattached to make it go online */
2258 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2262 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2268 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2271 struct DiskPartition64 *partp;
2276 #ifdef AFS_DEMAND_ATTACH_FS
2277 VolumeStats stats_save;
2279 #endif /* AFS_DEMAND_ATTACH_FS */
2283 volumeId = VolumeNumber(name);
2285 if (!(partp = VGetPartition_r(partition, 0))) {
2287 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2291 if (VRequiresPartLock()) {
2292 osi_Assert(VInit == 3);
2293 VLockPartition_r(partition);
2294 } else if (programType == fileServer) {
2295 #ifdef AFS_DEMAND_ATTACH_FS
2296 /* lookup the volume in the hash table */
2297 vp = VLookupVolume_r(ec, volumeId, NULL);
2303 /* save any counters that are supposed to
2304 * be monotonically increasing over the
2305 * lifetime of the fileserver */
2306 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2308 memset(&stats_save, 0, sizeof(VolumeStats));
2311 /* if there's something in the hash table, and it's not
2312 * in the pre-attach state, then we may need to detach
2313 * it before proceeding */
2314 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2315 VCreateReservation_r(vp);
2316 VWaitExclusiveState_r(vp);
2318 /* at this point state must be one of:
2328 if (vp->specialStatus == VBUSY)
2331 /* if it's already attached, see if we can return it */
2332 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2333 VGetVolumeByVp_r(ec, vp);
2334 if (V_inUse(vp) == fileServer) {
2335 VCancelReservation_r(vp);
2339 /* otherwise, we need to detach, and attempt to re-attach */
2340 VDetachVolume_r(ec, vp);
2342 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2345 /* if it isn't fully attached, delete from the hash tables,
2346 and let the refcounter handle the rest */
2347 DeleteVolumeFromHashTable(vp);
2348 DeleteVolumeFromVByPList_r(vp);
2351 VCancelReservation_r(vp);
2355 /* pre-attach volume if it hasn't been done yet */
2357 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2358 (V_attachState(vp) == VOL_STATE_DELETED) ||
2359 (V_attachState(vp) == VOL_STATE_ERROR)) {
2361 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2367 osi_Assert(vp != NULL);
2369 /* handle pre-attach races
2371 * multiple threads can race to pre-attach a volume,
2372 * but we can't let them race beyond that
2374 * our solution is to let the first thread to bring
2375 * the volume into an exclusive state win; the other
2376 * threads just wait until it finishes bringing the
2377 * volume online, and then they do a vgetvolumebyvp
2379 if (svp && (svp != vp)) {
2380 /* wait for other exclusive ops to finish */
2381 VCreateReservation_r(vp);
2382 VWaitExclusiveState_r(vp);
2384 /* get a heavyweight ref, kill the lightweight ref, and return */
2385 VGetVolumeByVp_r(ec, vp);
2386 VCancelReservation_r(vp);
2390 /* at this point, we are chosen as the thread to do
2391 * demand attachment for this volume. all other threads
2392 * doing a getvolume on vp->hashid will block until we finish */
2394 /* make sure any old header cache entries are invalidated
2395 * before proceeding */
2396 FreeVolumeHeader(vp);
2398 VChangeState_r(vp, VOL_STATE_ATTACHING);
2400 /* restore any saved counters */
2401 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2402 #else /* AFS_DEMAND_ATTACH_FS */
2403 vp = VGetVolume_r(ec, volumeId);
2405 if (V_inUse(vp) == fileServer)
2407 if (vp->specialStatus == VBUSY)
2409 VDetachVolume_r(ec, vp);
2411 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2415 #endif /* AFS_DEMAND_ATTACH_FS */
2419 strcpy(path, VPartitionPath(partp));
2423 strcat(path, OS_DIRSEP);
2427 vp = (Volume *) calloc(1, sizeof(Volume));
2428 osi_Assert(vp != NULL);
2429 vp->hashid = volumeId;
2430 vp->device = partp->device;
2431 vp->partition = partp;
2432 queue_Init(&vp->vnode_list);
2433 queue_Init(&vp->rx_call_list);
2434 #ifdef AFS_DEMAND_ATTACH_FS
2435 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2436 #endif /* AFS_DEMAND_ATTACH_FS */
2439 /* attach2 is entered without any locks, and returns
2440 * with vol_glock_mutex held */
2441 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2443 if (VCanUseFSSYNC() && vp) {
2444 #ifdef AFS_DEMAND_ATTACH_FS
2445 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2446 /* mark volume header as in use so that volser crashes lead to a
2447 * salvage attempt */
2448 VUpdateVolume_r(ec, vp, 0);
2450 /* for dafs, we should tell the fileserver, except for V_PEEK
2451 * where we know it is not necessary */
2452 if (mode == V_PEEK) {
2453 vp->needsPutBack = 0;
2455 vp->needsPutBack = VOL_PUTBACK;
2457 #else /* !AFS_DEMAND_ATTACH_FS */
2458 /* duplicate computation in fssync.c about whether the server
2459 * takes the volume offline or not. If the volume isn't
2460 * offline, we must not return it when we detach the volume,
2461 * or the server will abort */
2462 if (mode == V_READONLY || mode == V_PEEK
2463 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2464 vp->needsPutBack = 0;
2466 vp->needsPutBack = VOL_PUTBACK;
2467 #endif /* !AFS_DEMAND_ATTACH_FS */
2469 #ifdef FSSYNC_BUILD_CLIENT
2470 /* Only give back the vol to the fileserver if we checked it out; attach2
2471 * will set checkedOut only if we successfully checked it out from the
2473 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2475 #ifdef AFS_DEMAND_ATTACH_FS
2476 /* If we couldn't attach but we scheduled a salvage, we already
2477 * notified the fileserver; don't online it now */
2478 if (*ec != VSALVAGING)
2479 #endif /* AFS_DEMAND_ATTACH_FS */
2480 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2483 if (programType == fileServer && vp) {
2484 #ifdef AFS_DEMAND_ATTACH_FS
2486 * we can get here in cases where we don't "own"
2487 * the volume (e.g. volume owned by a utility).
2488 * short circuit around potential disk header races.
2490 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2494 VUpdateVolume_r(ec, vp, 0);
2496 Log("VAttachVolume: Error updating volume\n");
2501 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2502 #ifndef AFS_DEMAND_ATTACH_FS
2503 /* This is a hack: by temporarily setting the incore
2504 * dontSalvage flag ON, the volume will be put back on the
2505 * Update list (with dontSalvage OFF again). It will then
2506 * come back in N minutes with DONT_SALVAGE eventually
2507 * set. This is the way that volumes that have never had
2508 * it set get it set; or that volumes that have been
2509 * offline without DONT SALVAGE having been set also
2510 * eventually get it set */
2511 V_dontSalvage(vp) = DONT_SALVAGE;
2512 #endif /* !AFS_DEMAND_ATTACH_FS */
2513 VAddToVolumeUpdateList_r(ec, vp);
2515 Log("VAttachVolume: Error adding volume to update list\n");
2522 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2527 if (VRequiresPartLock()) {
2528 VUnlockPartition_r(partition);
2531 #ifdef AFS_DEMAND_ATTACH_FS
2532 /* attach failed; make sure we're in error state */
2533 if (vp && !VIsErrorState(V_attachState(vp))) {
2534 VChangeState_r(vp, VOL_STATE_ERROR);
2536 #endif /* AFS_DEMAND_ATTACH_FS */
2543 #ifdef AFS_DEMAND_ATTACH_FS
2544 /* VAttachVolumeByVp_r
2546 * finish attaching a volume that is
2547 * in a less than fully attached state
2549 /* caller MUST hold a ref count on vp */
2551 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2553 char name[VMAXPATHLEN];
2555 struct DiskPartition64 *partp;
2559 Volume * nvp = NULL;
2560 VolumeStats stats_save;
2564 /* volume utility should never call AttachByVp */
2565 osi_Assert(programType == fileServer);
2567 volumeId = vp->hashid;
2568 partp = vp->partition;
2569 VolumeExternalName_r(volumeId, name, sizeof(name));
2572 /* if another thread is performing a blocking op, wait */
2573 VWaitExclusiveState_r(vp);
2575 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2577 /* if it's already attached, see if we can return it */
2578 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2579 VGetVolumeByVp_r(ec, vp);
2580 if (V_inUse(vp) == fileServer) {
2583 if (vp->specialStatus == VBUSY)
2585 VDetachVolume_r(ec, vp);
2587 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2593 /* pre-attach volume if it hasn't been done yet */
2595 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2596 (V_attachState(vp) == VOL_STATE_DELETED) ||
2597 (V_attachState(vp) == VOL_STATE_ERROR)) {
2598 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2604 VCreateReservation_r(nvp);
2609 osi_Assert(vp != NULL);
2610 VChangeState_r(vp, VOL_STATE_ATTACHING);
2612 /* restore monotonically increasing stats */
2613 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2617 /* compute path to disk header */
2618 strcpy(path, VPartitionPath(partp));
2622 strcat(path, OS_DIRSEP);
2627 * NOTE: attach2 is entered without any locks, and returns
2628 * with vol_glock_mutex held */
2629 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2632 * the event that an error was encountered, or
2633 * the volume was not brought to an attached state
2634 * for any reason, skip to the end. We cannot
2635 * safely call VUpdateVolume unless we "own" it.
2639 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2643 VUpdateVolume_r(ec, vp, 0);
2645 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2649 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2650 #ifndef AFS_DEMAND_ATTACH_FS
2651 /* This is a hack: by temporarily setting the incore
2652 * dontSalvage flag ON, the volume will be put back on the
2653 * Update list (with dontSalvage OFF again). It will then
2654 * come back in N minutes with DONT_SALVAGE eventually
2655 * set. This is the way that volumes that have never had
2656 * it set get it set; or that volumes that have been
2657 * offline without DONT SALVAGE having been set also
2658 * eventually get it set */
2659 V_dontSalvage(vp) = DONT_SALVAGE;
2660 #endif /* !AFS_DEMAND_ATTACH_FS */
2661 VAddToVolumeUpdateList_r(ec, vp);
2663 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2670 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2674 VCancelReservation_r(nvp);
2677 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2678 if (vp && !VIsErrorState(V_attachState(vp))) {
2679 VChangeState_r(vp, VOL_STATE_ERROR);
2688 * lock a volume on disk (non-blocking).
2690 * @param[in] vp The volume to lock
2691 * @param[in] locktype READ_LOCK or WRITE_LOCK
2693 * @return operation status
2694 * @retval 0 success, lock was obtained
2695 * @retval EBUSY a conflicting lock was held by another process
2696 * @retval EIO error acquiring lock
2698 * @pre If we're in the fileserver, vp is in an exclusive state
2700 * @pre vp is not already locked
2703 VLockVolumeNB(Volume *vp, int locktype)
2707 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2708 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2710 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2712 V_attachFlags(vp) |= VOL_LOCKED;
2719 * unlock a volume on disk that was locked with VLockVolumeNB.
2721 * @param[in] vp volume to unlock
2723 * @pre If we're in the fileserver, vp is in an exclusive state
2725 * @pre vp has already been locked
2728 VUnlockVolume(Volume *vp)
2730 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2731 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2733 VUnlockVolumeById(vp->hashid, vp->partition);
2735 V_attachFlags(vp) &= ~VOL_LOCKED;
2737 #endif /* AFS_DEMAND_ATTACH_FS */
2740 * read in a vol header, possibly lock the vol header, and possibly check out
2741 * the vol header from the fileserver, as part of volume attachment.
2743 * @param[out] ec error code
2744 * @param[in] vp volume pointer object
2745 * @param[in] partp disk partition object of the attaching partition
2746 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2748 * @param[in] peek 1 to just try to read in the volume header and make sure
2749 * we don't try to lock the vol, or check it out from
2750 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2752 * @param[out] acheckedOut If we successfully checked-out the volume from
2753 * the fileserver (if we needed to), this is set
2754 * to 1, otherwise it is untouched.
2756 * @note As part of DAFS volume attachment, the volume header may be either
2757 * read- or write-locked to ensure mutual exclusion of certain volume
2758 * operations. In some cases in order to determine whether we need to
2759 * read- or write-lock the header, we need to read in the header to see
2760 * if the volume is RW or not. So, if we read in the header under a
2761 * read-lock and determine that we actually need a write-lock on the
2762 * volume header, this function will drop the read lock, acquire a write
2763 * lock, and read the header in again.
2766 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2767 int mode, int peek, int *acheckedOut)
2769 struct VolumeDiskHeader diskHeader;
2770 struct VolumeHeader header;
2773 int lock_tries = 0, checkout_tries = 0;
2775 VolumeId volid = vp->hashid;
2776 #ifdef FSSYNC_BUILD_CLIENT
2777 int checkout, done_checkout = 0;
2778 #endif /* FSSYNC_BUILD_CLIENT */
2779 #ifdef AFS_DEMAND_ATTACH_FS
2780 int locktype = 0, use_locktype = -1;
2781 #endif /* AFS_DEMAND_ATTACH_FS */
2787 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2788 Log("VAttachVolume: retried too many times trying to lock header for "
2789 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2790 VPartitionPath(partp));
2794 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2795 Log("VAttachVolume: retried too many times trying to checkout "
2796 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2797 VPartitionPath(partp));
2802 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2803 /* short-circuit the 'volume does not exist' case */
2808 #ifdef FSSYNC_BUILD_CLIENT
2809 checkout = !done_checkout;
2811 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2813 memset(&res, 0, sizeof(res));
2815 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2818 if (res.hdr.reason == FSYNC_SALVAGE) {
2819 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2820 afs_printable_uint32_lu(volid));
2823 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2824 afs_printable_uint32_lu(volid));
2825 *ec = VNOVOL; /* XXXX */
2833 #ifdef AFS_DEMAND_ATTACH_FS
2834 if (use_locktype < 0) {
2835 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2836 * if it turns out to be RW */
2837 locktype = VVolLockType(mode, 0);
2840 /* a previous try says we should use use_locktype to lock the volume,
2842 locktype = use_locktype;
2845 if (!peek && locktype) {
2846 code = VLockVolumeNB(vp, locktype);
2848 if (code == EBUSY) {
2849 Log("VAttachVolume: another program has vol %lu locked\n",
2850 afs_printable_uint32_lu(volid));
2852 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2853 code, afs_printable_uint32_lu(volid));
2860 #endif /* AFS_DEMAND_ATTACH_FS */
2862 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2872 DiskToVolumeHeader(&header, &diskHeader);
2874 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2875 header.largeVnodeIndex);
2876 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2877 header.smallVnodeIndex);
2878 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2880 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2883 /* only need to do this once */
2885 GetVolumeHeader(vp);
2889 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2890 /* demand attach changes the V_PEEK mechanism
2892 * we can now suck the current disk data structure over
2893 * the fssync interface without going to disk
2895 * (technically, we don't need to restrict this feature
2896 * to demand attach fileservers. However, I'm trying
2897 * to limit the number of common code changes)
2899 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2901 res.payload.len = sizeof(VolumeDiskData);
2902 res.payload.buf = &vp->header->diskstuff;
2904 if (FSYNC_VolOp(vp->hashid,
2906 FSYNC_VOL_QUERY_HDR,
2909 goto disk_header_loaded;
2912 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2913 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2914 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2916 #ifdef AFS_DEMAND_ATTACH_FS
2919 IncUInt64(&VStats.hdr_loads);
2920 IncUInt64(&vp->stats.hdr_loads);
2922 #endif /* AFS_DEMAND_ATTACH_FS */
2925 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2926 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2930 #ifdef AFS_DEMAND_ATTACH_FS
2931 # ifdef FSSYNC_BUILD_CLIENT
2933 # endif /* FSSYNC_BUILD_CLIENT */
2935 /* if the lock type we actually used to lock the volume is different than
2936 * the lock type we should have used, retry with the lock type we should
2938 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2939 if (locktype != use_locktype) {
2943 #endif /* AFS_DEMAND_ATTACH_FS */
2948 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2949 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2951 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2953 if (code == SYNC_DENIED) {
2954 /* must retry checkout; fileserver no longer thinks we have
2960 } else if (code != SYNC_OK) {
2964 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2967 /* either we are going to be called again for a second pass, or we
2968 * encountered an error; clean up in either case */
2970 #ifdef AFS_DEMAND_ATTACH_FS
2971 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2974 #endif /* AFS_DEMAND_ATTACH_FS */
2975 if (vp->linkHandle) {
2976 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2977 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2978 IH_RELEASE(vp->diskDataHandle);
2979 IH_RELEASE(vp->linkHandle);
2992 #ifdef AFS_DEMAND_ATTACH_FS
2994 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2995 Volume *vp, int *acheckedOut)
2999 if (vp->pending_vol_op) {
3003 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3005 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3007 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3008 } else if (code == 0) {
3009 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3012 /* we need the vol header to determine if the volume can be
3013 * left online for the vop, so... get the header */
3017 /* attach header with peek=1 to avoid checking out the volume
3018 * or locking it; we just want the header info, we're not
3019 * messing with the volume itself at all */
3020 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3027 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3028 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3030 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3033 /* make sure we grab a new vol header and re-open stuff on
3034 * actual attachment; we can't keep the data we grabbed, since
3035 * it was not done under a lock and thus not safe */
3036 FreeVolumeHeader(vp);
3037 VReleaseVolumeHandles_r(vp);
3040 /* see if the pending volume op requires exclusive access */
3041 switch (vp->pending_vol_op->vol_op_state) {
3042 case FSSYNC_VolOpPending:
3043 /* this should never happen */
3044 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3047 case FSSYNC_VolOpRunningUnknown:
3048 /* this should never happen; we resolved 'unknown' above */
3049 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3052 case FSSYNC_VolOpRunningOffline:
3053 /* mark the volume down */
3055 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3057 /* do not set V_offlineMessage here; we don't have ownership of
3058 * the volume (and probably do not have the header loaded), so we
3059 * can't alter the disk header */
3061 /* check to see if we should set the specialStatus flag */
3062 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3063 vp->specialStatus = VBUSY;
3074 #endif /* AFS_DEMAND_ATTACH_FS */
3077 * volume attachment helper function.
3079 * @param[out] ec error code
3080 * @param[in] volumeId volume ID of the attaching volume
3081 * @param[in] path full path to the volume header .vol file
3082 * @param[in] partp disk partition object for the attaching partition
3083 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3084 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3085 * DAFS) should already be initialized
3086 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3087 * if there is a volume operation running for this volume
3088 * that should set the volume to VBUSY during its run. 0
3089 * otherwise. (see VVolOpSetVBusy_r)
3090 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3092 * @param[out] acheckedOut If we successfully checked-out the volume from
3093 * the fileserver (if we needed to), this is set
3094 * to 1, otherwise it is 0.
3096 * @return pointer to the semi-attached volume pointer
3097 * @retval NULL an error occurred (check value of *ec)
3098 * @retval vp volume successfully attaching
3100 * @pre no locks held
3102 * @post VOL_LOCK held
3105 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3106 Volume * vp, int isbusy, int mode, int *acheckedOut)
3108 /* have we read in the header successfully? */
3109 int read_header = 0;
3111 #ifdef AFS_DEMAND_ATTACH_FS
3112 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3116 /* in the case of an error, to what state should the volume be
3118 VolState error_state = VOL_STATE_ERROR;
3119 #endif /* AFS_DEMAND_ATTACH_FS */
3123 vp->vnodeIndex[vLarge].handle = NULL;
3124 vp->vnodeIndex[vSmall].handle = NULL;
3125 vp->diskDataHandle = NULL;
3126 vp->linkHandle = NULL;
3130 #ifdef AFS_DEMAND_ATTACH_FS
3131 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3133 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3136 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3137 #endif /* !AFS_DEMAND_ATTACH_FS */
3139 if (*ec == VNOVOL) {
3140 /* if the volume doesn't exist, skip straight to 'error' so we don't
3141 * request a salvage */
3142 goto unlocked_error;
3148 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3149 vp->shuttingDown = 0;
3150 vp->goingOffline = 0;
3152 #ifdef AFS_DEMAND_ATTACH_FS
3153 vp->stats.last_attach = FT_ApproxTime();
3154 vp->stats.attaches++;
3158 IncUInt64(&VStats.attaches);
3159 vp->cacheCheck = ++VolumeCacheCheck;
3160 /* just in case this ever rolls over */
3161 if (!vp->cacheCheck)
3162 vp->cacheCheck = ++VolumeCacheCheck;
3165 #ifdef AFS_DEMAND_ATTACH_FS
3166 V_attachFlags(vp) |= VOL_HDR_LOADED;
3167 vp->stats.last_hdr_load = vp->stats.last_attach;
3168 #endif /* AFS_DEMAND_ATTACH_FS */
3172 struct IndexFileHeader iHead;
3174 #if OPENAFS_VOL_STATS
3176 * We just read in the diskstuff part of the header. If the detailed
3177 * volume stats area has not yet been initialized, we should bzero the
3178 * area and mark it as initialized.
3180 if (!(V_stat_initialized(vp))) {
3181 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3182 V_stat_initialized(vp) = 1;
3184 #endif /* OPENAFS_VOL_STATS */
3186 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3187 (char *)&iHead, sizeof(iHead),
3188 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3191 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3196 struct IndexFileHeader iHead;
3198 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3199 (char *)&iHead, sizeof(iHead),
3200 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3203 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3207 #ifdef AFS_NAMEI_ENV
3209 struct versionStamp stamp;
3211 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3212 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3215 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3218 #endif /* AFS_NAMEI_ENV */
3220 #if defined(AFS_DEMAND_ATTACH_FS)
3221 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3223 if (!VCanScheduleSalvage()) {
3224 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3226 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3227 VOL_SALVAGE_NO_OFFLINE);
3232 /* volume operation in progress */
3233 goto unlocked_error;
3235 #else /* AFS_DEMAND_ATTACH_FS */
3237 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3238 goto unlocked_error;
3240 #endif /* AFS_DEMAND_ATTACH_FS */
3242 if (V_needsSalvaged(vp)) {
3243 if (vp->specialStatus)
3244 vp->specialStatus = 0;
3246 #if defined(AFS_DEMAND_ATTACH_FS)
3247 if (!VCanScheduleSalvage()) {
3248 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3250 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3251 VOL_SALVAGE_NO_OFFLINE);
3254 #else /* AFS_DEMAND_ATTACH_FS */
3256 #endif /* AFS_DEMAND_ATTACH_FS */
3262 vp->nextVnodeUnique = V_uniquifier(vp);
3264 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3265 if (!V_needsSalvaged(vp)) {
3266 V_needsSalvaged(vp) = 1;
3267 VUpdateVolume_r(ec, vp, 0);
3269 #if defined(AFS_DEMAND_ATTACH_FS)
3270 if (!VCanScheduleSalvage()) {
3271 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3273 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3274 VOL_SALVAGE_NO_OFFLINE);
3277 #else /* AFS_DEMAND_ATTACH_FS */
3278 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3280 #endif /* AFS_DEMAND_ATTACH_FS */
3285 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3286 /* Only check destroyMe if we are the fileserver, since the
3287 * volserver et al sometimes need to work with volumes with
3288 * destroyMe set. Examples are 'temporary' volumes the
3289 * volserver creates, and when we create a volume (destroyMe
3290 * is set on creation; sometimes a separate volserver
3291 * transaction is created to clear destroyMe).
3294 #if defined(AFS_DEMAND_ATTACH_FS)
3295 /* schedule a salvage so the volume goes away on disk */
3296 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3297 VOL_SALVAGE_NO_OFFLINE);
3298 VChangeState_r(vp, VOL_STATE_ERROR);
3301 #endif /* AFS_DEMAND_ATTACH_FS */
3302 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3307 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3308 #ifndef BITMAP_LATER
3309 if (programType == fileServer && VolumeWriteable(vp)) {
3311 for (i = 0; i < nVNODECLASSES; i++) {
3312 VGetBitmap_r(ec, vp, i);
3314 #ifdef AFS_DEMAND_ATTACH_FS
3315 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3316 VOL_SALVAGE_NO_OFFLINE);
3318 #endif /* AFS_DEMAND_ATTACH_FS */
3319 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3325 #endif /* BITMAP_LATER */
3327 if (VInit >= 2 && V_needsCallback(vp)) {
3328 if (V_BreakVolumeCallbacks) {
3329 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3330 afs_printable_uint32_lu(V_id(vp)));
3331 V_needsCallback(vp) = 0;
3333 (*V_BreakVolumeCallbacks) (V_id(vp));
3336 VUpdateVolume_r(ec, vp, 0);
3338 #ifdef FSSYNC_BUILD_CLIENT
3339 else if (VCanUseFSSYNC()) {
3340 afs_int32 fsync_code;
3342 V_needsCallback(vp) = 0;
3344 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3348 V_needsCallback(vp) = 1;
3349 Log("Error trying to tell the fileserver to break callbacks for "
3350 "changed volume %lu; error code %ld\n",
3351 afs_printable_uint32_lu(V_id(vp)),
3352 afs_printable_int32_ld(fsync_code));
3354 VUpdateVolume_r(ec, vp, 0);
3357 #endif /* FSSYNC_BUILD_CLIENT */
3360 Log("VAttachVolume: error %d clearing needsCallback on volume "
3361 "%lu; needs salvage\n", (int)*ec,
3362 afs_printable_uint32_lu(V_id(vp)));
3363 #ifdef AFS_DEMAND_ATTACH_FS
3364 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3365 VOL_SALVAGE_NO_OFFLINE);
3367 #else /* !AFS_DEMAND_ATTACH_FS */
3369 #endif /* !AFS_DEMAND_ATTACh_FS */
3374 if (programType == fileServer) {
3375 if (vp->specialStatus)
3376 vp->specialStatus = 0;
3377 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3378 V_inUse(vp) = fileServer;
3379 V_offlineMessage(vp)[0] = '\0';
3383 #ifdef AFS_DEMAND_ATTACH_FS
3384 /* Put the vol into PREATTACHED state, so if someone tries to
3385 * access it again, we try to attach, see that we're not blessed,
3386 * and give a VNOVOL error again. Putting it into UNATTACHED state
3387 * would result in a VOFFLINE error instead. */
3388 error_state = VOL_STATE_PREATTACHED;
3389 #endif /* AFS_DEMAND_ATTACH_FS */
3391 /* mimic e.g. GetVolume errors */
3392 if (!V_blessed(vp)) {
3393 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3394 FreeVolumeHeader(vp);
3395 } else if (!V_inService(vp)) {
3396 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3397 FreeVolumeHeader(vp);
3399 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3401 #ifdef AFS_DEMAND_ATTACH_FS
3402 error_state = VOL_STATE_ERROR;
3403 /* see if we can recover */
3404 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3407 #ifdef AFS_DEMAND_ATTACH_FS
3413 #ifdef AFS_DEMAND_ATTACH_FS
3414 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3415 V_inUse(vp) = programType;
3416 #endif /* AFS_DEMAND_ATTACH_FS */
3417 V_checkoutMode(vp) = mode;
3420 AddVolumeToHashTable(vp, V_id(vp));
3421 #ifdef AFS_DEMAND_ATTACH_FS
3422 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3425 if ((programType != fileServer) ||
3426 (V_inUse(vp) == fileServer)) {
3427 AddVolumeToVByPList_r(vp);
3429 VChangeState_r(vp, VOL_STATE_ATTACHED);
3431 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3440 #ifdef AFS_DEMAND_ATTACH_FS
3441 if (!VIsErrorState(V_attachState(vp))) {
3442 VChangeState_r(vp, error_state);
3444 #endif /* AFS_DEMAND_ATTACH_FS */
3447 VReleaseVolumeHandles_r(vp);
3450 #ifdef AFS_DEMAND_ATTACH_FS
3457 #else /* !AFS_DEMAND_ATTACH_FS */
3459 #endif /* !AFS_DEMAND_ATTACH_FS */
3463 /* Attach an existing volume.
3464 The volume also normally goes online at this time.
3465 An offline volume must be reattached to make it go online.
3469 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3473 retVal = VAttachVolume_r(ec, volumeId, mode);
3479 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3482 VGetVolumePath(ec, volumeId, &part, &name);
3486 vp = VGetVolume_r(&error, volumeId);
3488 osi_Assert(V_inUse(vp) == 0);
3489 VDetachVolume_r(ec, vp);
3493 return VAttachVolumeByName_r(ec, part, name, mode);
3496 /* Increment a reference count to a volume, sans context swaps. Requires
3497 * possibly reading the volume header in from the disk, since there's
3498 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3500 * N.B. This call can fail if we can't read in the header!! In this case
3501 * we still guarantee we won't context swap, but the ref count won't be
3502 * incremented (otherwise we'd violate the invariant).
3504 /* NOTE: with the demand attach fileserver extensions, the global lock
3505 * is dropped within VHold */
3506 #ifdef AFS_DEMAND_ATTACH_FS
3508 VHold_r(Volume * vp)
3512 VCreateReservation_r(vp);
3513 VWaitExclusiveState_r(vp);
3515 LoadVolumeHeader(&error, vp);
3517 VCancelReservation_r(vp);
3521 VCancelReservation_r(vp);
3524 #else /* AFS_DEMAND_ATTACH_FS */
3526 VHold_r(Volume * vp)
3530 LoadVolumeHeader(&error, vp);
3536 #endif /* AFS_DEMAND_ATTACH_FS */
3538 /**** volume timeout-related stuff ****/
3540 #ifdef AFS_PTHREAD_ENV
3542 static struct timespec *shutdown_timeout;
3543 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3546 VTimedOut(const struct timespec *ts)
3551 if (ts->tv_sec == 0) {
3552 /* short-circuit; this will have always timed out */
3556 code = gettimeofday(&tv, NULL);
3558 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3559 /* assume no timeout; failure mode is we just wait longer than normal
3560 * instead of returning errors when we shouldn't */
3564 if (tv.tv_sec < ts->tv_sec ||
3565 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3574 * Calculate an absolute timeout.
3576 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3577 * NULL, the memory is not touched
3578 * @param[in] timeout How long the timeout should be from now
3580 * @return timeout to use
3581 * @retval NULL no timeout; wait forever
3582 * @retval non-NULL the given value for "ts"
3586 static struct timespec *
3587 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3597 ts->tv_sec = ts->tv_nsec = 0;
3601 code = gettimeofday(&now, NULL);
3603 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3607 ts->tv_sec = now.tv_sec + timeout;
3608 ts->tv_nsec = now.tv_usec * 1000;
3614 * Initialize the shutdown_timeout global.
3617 VShutdownTimeoutInit(void)
3619 struct timespec *ts;
3621 ts = malloc(sizeof(*ts));
3623 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3625 if (!shutdown_timeout) {
3631 * Figure out the timeout that should be used for waiting for offline volumes.
3633 * @param[out] ats Storage space for a local timeout value if needed
3635 * @return The timeout value that should be used
3636 * @retval NULL No timeout; wait forever for offlining volumes
3637 * @retval non-NULL A pointer to the absolute time that should be used as
3638 * the deadline for waiting for offlining volumes.
3640 * @note If we return non-NULL, the pointer we return may or may not be the
3643 static const struct timespec *
3644 VOfflineTimeout(struct timespec *ats)
3646 if (vol_shutting_down) {
3647 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3648 return shutdown_timeout;
3650 return VCalcTimeout(ats, vol_opts.offline_timeout);
3654 #else /* AFS_PTHREAD_ENV */
3656 /* Waiting a certain amount of time for offlining volumes is not supported
3657 * for LWP due to a lack of primitives. So, we never time out */
3658 # define VTimedOut(x) (0)
3659 # define VOfflineTimeout(x) (NULL)
3661 #endif /* !AFS_PTHREAD_ENV */
3669 retVal = VHold_r(vp);
3676 VIsGoingOffline_r(struct Volume *vp)
3680 if (vp->goingOffline) {
3681 if (vp->specialStatus) {
3682 code = vp->specialStatus;
3683 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3694 * Tell the caller if a volume is waiting to go offline.
3696 * @param[in] vp The volume we want to know about
3698 * @return volume status
3699 * @retval 0 volume is not waiting to go offline, go ahead and use it
3700 * @retval nonzero volume is waiting to offline, and give the returned code
3701 * as an error to anyone accessing the volume
3703 * @pre VOL_LOCK is NOT held
3704 * @pre caller holds a heavyweight reference on vp
3707 VIsGoingOffline(struct Volume *vp)
3712 code = VIsGoingOffline_r(vp);
3719 * Register an RX call with a volume.
3721 * @param[inout] ec Error code; if unset when passed in, may be set if
3722 * the volume starts going offline
3723 * @param[out] client_ec @see GetVolume
3724 * @param[in] vp Volume struct
3725 * @param[in] cbv VCallByVol struct containing the RX call to register
3727 * @pre VOL_LOCK held
3728 * @pre caller holds heavy ref on vp
3733 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3736 #ifdef AFS_DEMAND_ATTACH_FS
3738 /* just in case the volume started going offline after we got the
3739 * reference to it... otherwise, if the volume started going
3740 * offline right at the end of GetVolume(), we might race with the
3741 * RX call scanner, and return success and add our cbv to the
3742 * rx_call_list _after_ the scanner has scanned the list. */
3743 *ec = VIsGoingOffline_r(vp);
3749 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3750 VWaitStateChange_r(vp);
3752 #endif /* AFS_DEMAND_ATTACH_FS */
3754 queue_Prepend(&vp->rx_call_list, cbv);
3759 * Deregister an RX call with a volume.
3761 * @param[in] vp Volume struct
3762 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3764 * @pre VOL_LOCK held
3765 * @pre caller holds heavy ref on vp
3770 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3772 if (cbv && queue_IsOnQueue(cbv)) {
3773 #ifdef AFS_DEMAND_ATTACH_FS
3774 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3775 VWaitStateChange_r(vp);
3777 #endif /* AFS_DEMAND_ATTACH_FS */
3783 /***************************************************/
3784 /* get and put volume routines */
3785 /***************************************************/
3788 * put back a heavyweight reference to a volume object.
3790 * @param[in] vp volume object pointer
3792 * @pre VOL_LOCK held
3794 * @post heavyweight volume reference put back.
3795 * depending on state, volume may have been taken offline,
3796 * detached, salvaged, freed, etc.
3798 * @internal volume package internal use only
3801 VPutVolume_r(Volume * vp)
3803 osi_Assert(--vp->nUsers >= 0);
3804 if (vp->nUsers == 0) {
3806 ReleaseVolumeHeader(vp->header);
3807 #ifdef AFS_DEMAND_ATTACH_FS
3808 if (!VCheckDetach(vp)) {
3812 #else /* AFS_DEMAND_ATTACH_FS */
3814 #endif /* AFS_DEMAND_ATTACH_FS */
3819 VPutVolume(Volume * vp)
3827 * Puts a volume reference obtained with VGetVolumeWithCall.
3829 * @param[in] vp Volume struct
3830 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3832 * @pre VOL_LOCK is NOT held
3835 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3838 VDeregisterCall_r(vp, cbv);
3843 /* Get a pointer to an attached volume. The pointer is returned regardless
3844 of whether or not the volume is in service or on/off line. An error
3845 code, however, is returned with an indication of the volume's status */
3847 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3851 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3857 * Get a volume reference associated with an RX call.
3859 * @param[out] ec @see GetVolume
3860 * @param[out] client_ec @see GetVolume
3861 * @param[in] volumeId @see GetVolume
3862 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3863 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3864 * with an error if the volume is going offline.
3865 * @param[in] cbv Contains an RX call to be associated with this volume
3866 * reference. This call may be interrupted if the volume is
3867 * requested to go offline while we hold a ref on it. Give NULL
3868 * to not associate an RX call with this reference.
3870 * @return @see GetVolume
3872 * @note for LWP builds, ts must be NULL
3874 * @note A reference obtained with this function MUST be put back with
3875 * VPutVolumeWithCall
3878 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3879 const struct timespec *ts, struct VCallByVol *cbv)
3883 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3884 VRegisterCall_r(ec, client_ec, retVal, cbv);
3890 VGetVolume_r(Error * ec, VolId volumeId)
3892 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3895 /* try to get a volume we've previously looked up */
3896 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3898 VGetVolumeByVp_r(Error * ec, Volume * vp)
3900 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3904 * private interface for getting a volume handle
3906 * @param[out] ec error code (0 if no error)
3907 * @param[out] client_ec wire error code to be given to clients
3908 * @param[in] volumeId ID of the volume we want
3909 * @param[in] hint optional hint for hash lookups, or NULL
3910 * @param[in] timeout absolute deadline for waiting for the volume to go
3911 * offline, if it is going offline. NULL to wait forever.
3913 * @return a volume handle for the specified volume
3914 * @retval NULL an error occurred, or the volume is in such a state that
3915 * we cannot load a header or return any volume struct
3917 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3919 * @note 'timeout' is only checked if the volume is actually going offline; so
3920 * if you pass timeout->tv_sec = 0, this will exhibit typical
3921 * nonblocking behavior.
3923 * @note for LWP builds, 'timeout' must be NULL
3926 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3927 const struct timespec *timeout)
3930 /* pull this profiling/debugging code out of regular builds */
3932 #define VGET_CTR_INC(x) x++
3933 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3934 0, V7 = 0, V8 = 0, V9 = 0;
3935 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3937 #define VGET_CTR_INC(x)
3939 #ifdef AFS_DEMAND_ATTACH_FS
3940 Volume *avp, * rvp = hint;
3944 * if VInit is zero, the volume package dynamic
3945 * data structures have not been initialized yet,
3946 * and we must immediately return an error
3952 *client_ec = VOFFLINE;
3957 #ifdef AFS_DEMAND_ATTACH_FS
3959 VCreateReservation_r(rvp);
3961 #endif /* AFS_DEMAND_ATTACH_FS */
3969 vp = VLookupVolume_r(ec, volumeId, vp);
3975 #ifdef AFS_DEMAND_ATTACH_FS
3976 if (rvp && (rvp != vp)) {
3977 /* break reservation on old vp */
3978 VCancelReservation_r(rvp);
3981 #endif /* AFS_DEMAND_ATTACH_FS */
3987 /* Until we have reached an initialization level of 2
3988 * we don't know whether this volume exists or not.
3989 * We can't sleep and retry later because before a volume
3990 * is attached, the caller tries to get it first. Just
3991 * return VOFFLINE and the caller can choose whether to
3992 * retry the command or not. */
4002 IncUInt64(&VStats.hdr_gets);
4004 #ifdef AFS_DEMAND_ATTACH_FS
4005 /* block if someone else is performing an exclusive op on this volume */
4008 VCreateReservation_r(rvp);
4010 VWaitExclusiveState_r(vp);
4012 /* short circuit with VNOVOL in the following circumstances:
4015 * - VOL_STATE_SHUTTING_DOWN
4017 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4018 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
4019 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
4026 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
4027 * VNOVOL for VOL_STATE_DELETED
4029 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4030 (V_attachState(vp) == VOL_STATE_DELETED)) {
4031 if (vp->specialStatus) {
4032 *ec = vp->specialStatus;
4033 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4042 /* allowable states:
4049 if (vp->salvage.requested) {
4050 VUpdateSalvagePriority_r(vp);
4053 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4054 avp = VAttachVolumeByVp_r(ec, vp, 0);
4057 /* VAttachVolumeByVp_r can return a pointer
4058 * != the vp passed to it under certain
4059 * conditions; make sure we don't leak
4060 * reservations if that happens */
4062 VCancelReservation_r(rvp);
4064 VCreateReservation_r(rvp);
4074 if (!vp->pending_vol_op) {
4089 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4091 /* see CheckVnode() in afsfileprocs.c for an explanation
4092 * of this error code logic */
4093 afs_uint32 now = FT_ApproxTime();
4094 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4097 *client_ec = VRESTARTING;
4106 #ifdef AFS_DEMAND_ATTACH_FS
4108 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
4109 * not VolOpRunningUnknown (attach2 would have converted it to Online
4113 /* only valid before/during demand attachment */
4114 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
4116 /* deny getvolume due to running mutually exclusive vol op */
4117 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
4119 * volume cannot remain online during this volume operation.
4122 if (vp->specialStatus) {
4124 * special status codes outrank normal VOFFLINE code
4126 *ec = vp->specialStatus;
4128 *client_ec = vp->specialStatus;
4132 /* see CheckVnode() in afsfileprocs.c for an explanation
4133 * of this error code logic */
4134 afs_uint32 now = FT_ApproxTime();
4135 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
4138 *client_ec = VRESTARTING;
4143 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4144 FreeVolumeHeader(vp);
4148 #endif /* AFS_DEMAND_ATTACH_FS */
4150 LoadVolumeHeader(ec, vp);
4153 /* Only log the error if it was a totally unexpected error. Simply
4154 * a missing inode is likely to be caused by the volume being deleted */
4155 if (errno != ENXIO || LogLevel)
4156 Log("Volume %u: couldn't reread volume header\n",
4158 #ifdef AFS_DEMAND_ATTACH_FS
4159 if (VCanScheduleSalvage()) {
4160 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4165 #else /* AFS_DEMAND_ATTACH_FS */
4168 #endif /* AFS_DEMAND_ATTACH_FS */
4173 if (vp->shuttingDown) {
4180 if (programType == fileServer) {
4182 if (vp->goingOffline) {
4183 if (timeout && VTimedOut(timeout)) {
4184 /* we've timed out; don't wait for the vol */
4187 #ifdef AFS_DEMAND_ATTACH_FS
4188 /* wait for the volume to go offline */
4189 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4190 VTimedWaitStateChange_r(vp, timeout, NULL);
4192 #elif defined(AFS_PTHREAD_ENV)
4193 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4194 #else /* AFS_PTHREAD_ENV */
4195 /* LWP has no timed wait, so the caller better not be
4197 osi_Assert(!timeout);
4198 LWP_WaitProcess(VPutVolume);
4199 #endif /* AFS_PTHREAD_ENV */
4203 if (vp->specialStatus) {
4205 *ec = vp->specialStatus;
4206 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4209 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4220 #ifdef AFS_DEMAND_ATTACH_FS
4221 /* if no error, bump nUsers */
4224 VLRU_UpdateAccess_r(vp);
4227 VCancelReservation_r(rvp);
4230 if (client_ec && !*client_ec) {
4233 #else /* AFS_DEMAND_ATTACH_FS */
4234 /* if no error, bump nUsers */
4241 #endif /* AFS_DEMAND_ATTACH_FS */
4244 osi_Assert(vp || *ec);
4249 /***************************************************/
4250 /* Volume offline/detach routines */
4251 /***************************************************/
4253 /* caller MUST hold a heavyweight ref on vp */
4254 #ifdef AFS_DEMAND_ATTACH_FS
4256 VTakeOffline_r(Volume * vp)
4260 osi_Assert(vp->nUsers > 0);
4261 osi_Assert(programType == fileServer);
4263 VCreateReservation_r(vp);
4264 VWaitExclusiveState_r(vp);
4266 vp->goingOffline = 1;
4267 V_needsSalvaged(vp) = 1;
4269 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4270 VCancelReservation_r(vp);
4272 #else /* AFS_DEMAND_ATTACH_FS */
4274 VTakeOffline_r(Volume * vp)
4276 osi_Assert(vp->nUsers > 0);
4277 osi_Assert(programType == fileServer);
4279 vp->goingOffline = 1;
4280 V_needsSalvaged(vp) = 1;
4282 #endif /* AFS_DEMAND_ATTACH_FS */
4285 VTakeOffline(Volume * vp)
4293 * force a volume offline.
4295 * @param[in] vp volume object pointer
4296 * @param[in] flags flags (see note below)
4298 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4299 * used when VUpdateVolume_r needs to call VForceOffline_r
4300 * (which in turn would normally call VUpdateVolume_r)
4302 * @see VUpdateVolume_r
4304 * @pre VOL_LOCK must be held.
4305 * for DAFS, caller must hold ref.
4307 * @note for DAFS, it _is safe_ to call this function from an
4310 * @post needsSalvaged flag is set.
4311 * for DAFS, salvage is requested.
4312 * no further references to the volume through the volume
4313 * package will be honored.
4314 * all file descriptor and vnode caches are invalidated.
4316 * @warning this is a heavy-handed interface. it results in
4317 * a volume going offline regardless of the current
4318 * reference count state.
4320 * @internal volume package internal use only
4323 VForceOffline_r(Volume * vp, int flags)
4327 #ifdef AFS_DEMAND_ATTACH_FS
4328 VChangeState_r(vp, VOL_STATE_ERROR);
4333 strcpy(V_offlineMessage(vp),
4334 "Forced offline due to internal error: volume needs to be salvaged");
4335 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4338 vp->goingOffline = 0;
4339 V_needsSalvaged(vp) = 1;
4340 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4341 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4344 #ifdef AFS_DEMAND_ATTACH_FS
4345 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4346 #endif /* AFS_DEMAND_ATTACH_FS */
4348 #ifdef AFS_PTHREAD_ENV
4349 CV_BROADCAST(&vol_put_volume_cond);
4350 #else /* AFS_PTHREAD_ENV */
4351 LWP_NoYieldSignal(VPutVolume);
4352 #endif /* AFS_PTHREAD_ENV */
4354 VReleaseVolumeHandles_r(vp);
4358 * force a volume offline.
4360 * @param[in] vp volume object pointer
4362 * @see VForceOffline_r
4365 VForceOffline(Volume * vp)
4368 VForceOffline_r(vp, 0);
4373 * Iterate over the RX calls associated with a volume, and interrupt them.
4375 * @param[in] vp The volume whose RX calls we want to scan
4377 * @pre VOL_LOCK held
4380 VScanCalls_r(struct Volume *vp)
4382 struct VCallByVol *cbv, *ncbv;
4384 #ifdef AFS_DEMAND_ATTACH_FS
4385 VolState state_save;
4388 if (queue_IsEmpty(&vp->rx_call_list))
4389 return; /* no calls to interrupt */
4390 if (!vol_opts.interrupt_rxcall)
4391 return; /* we have no function with which to interrupt calls */
4392 err = VIsGoingOffline_r(vp);
4394 return; /* we're not going offline anymore */
4396 #ifdef AFS_DEMAND_ATTACH_FS
4397 VWaitExclusiveState_r(vp);
4398 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4400 #endif /* AFS_DEMAND_ATTACH_FS */
4402 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4404 struct rx_peer *peer;
4406 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4408 Log("Offlining volume %lu while client %s:%u is trying to read "
4409 "from it; kicking client off with error %ld\n",
4410 (long unsigned) vp->hashid,
4411 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4412 (unsigned) ntohs(rx_PortOf(peer)),
4415 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4418 #ifdef AFS_DEMAND_ATTACH_FS
4420 VChangeState_r(vp, state_save);
4421 #endif /* AFS_DEMAND_ATTACH_FS */
4424 #ifdef AFS_DEMAND_ATTACH_FS
4426 * Wait for a vp to go offline.
4428 * @param[out] ec 1 if a salvage on the volume has been requested and
4429 * salvok == 0, 0 otherwise
4430 * @param[in] vp The volume to wait for
4431 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4432 * has been requested to salvage. Otherwise we keep waiting
4433 * until the volume has gone offline.
4435 * @pre VOL_LOCK held
4436 * @pre caller holds a lightweight ref on vp
4441 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4443 struct timespec timeout_ts;
4444 const struct timespec *ts;
4447 ts = VOfflineTimeout(&timeout_ts);
4451 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4452 if (!salvok && vp->salvage.requested) {
4456 VTimedWaitStateChange_r(vp, ts, &timedout);
4459 /* we didn't time out, so the volume must be offline, so we're done */
4463 /* If we got here, we timed out waiting for the volume to go offline.
4464 * Kick off the accessing RX calls and wait again */
4468 while (!VIsOfflineState(V_attachState(vp))) {
4469 if (!salvok && vp->salvage.requested) {
4474 VWaitStateChange_r(vp);
4478 #else /* AFS_DEMAND_ATTACH_FS */
4481 * Wait for a volume to go offline.
4483 * @pre VOL_LOCK held
4485 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4488 VWaitForOffline_r(Error *ec, VolumeId volid)
4491 const struct timespec *ts;
4492 #ifdef AFS_PTHREAD_ENV
4493 struct timespec timeout_ts;
4496 ts = VOfflineTimeout(&timeout_ts);
4498 vp = GetVolume(ec, NULL, volid, NULL, ts);
4500 /* error occurred so bad that we can't even get a vp; we have no
4501 * information on the vol so we don't know whether to wait, so just
4505 if (!VIsGoingOffline_r(vp)) {
4506 /* volume is no longer going offline, so we're done */
4511 /* If we got here, we timed out waiting for the volume to go offline.
4512 * Kick off the accessing RX calls and wait again */
4518 vp = VGetVolume_r(ec, volid);
4520 /* In case it was reattached... */
4524 #endif /* !AFS_DEMAND_ATTACH_FS */
4526 /* The opposite of VAttachVolume. The volume header is written to disk, with
4527 the inUse bit turned off. A copy of the header is maintained in memory,
4528 however (which is why this is VOffline, not VDetach).
4531 VOffline_r(Volume * vp, char *message)
4534 #ifndef AFS_DEMAND_ATTACH_FS
4535 VolumeId vid = V_id(vp);
4538 osi_Assert(programType != volumeUtility && programType != volumeServer);
4543 if (V_offlineMessage(vp)[0] == '\0')
4544 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4545 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4547 vp->goingOffline = 1;
4548 #ifdef AFS_DEMAND_ATTACH_FS
4549 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4550 VCreateReservation_r(vp);
4552 VWaitForOfflineByVp_r(&error, vp, 1);
4553 VCancelReservation_r(vp);
4554 #else /* AFS_DEMAND_ATTACH_FS */
4556 VWaitForOffline_r(&error, vid);
4557 #endif /* AFS_DEMAND_ATTACH_FS */
4560 #ifdef AFS_DEMAND_ATTACH_FS
4562 * Take a volume offline in order to perform a volume operation.
4564 * @param[inout] ec address in which to store error code
4565 * @param[in] vp volume object pointer
4566 * @param[in] message volume offline status message
4569 * - VOL_LOCK is held
4570 * - caller MUST hold a heavyweight ref on vp
4573 * - volume is taken offline
4574 * - if possible, volume operation is promoted to running state
4575 * - on failure, *ec is set to nonzero
4577 * @note Although this function does not return any value, it may
4578 * still fail to promote our pending volume operation to
4579 * a running state. Any caller MUST check the value of *ec,
4580 * and MUST NOT blindly assume success.
4582 * @warning if the caller does not hold a lightweight ref on vp,
4583 * then it MUST NOT reference vp after this function
4584 * returns to the caller.
4586 * @internal volume package internal use only
4589 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4592 osi_Assert(vp->pending_vol_op);
4598 if (V_offlineMessage(vp)[0] == '\0')
4599 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4600 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4602 vp->goingOffline = 1;
4603 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4604 VCreateReservation_r(vp);
4607 if (vp->pending_vol_op->com.programType != salvageServer) {
4608 /* do not give corrupted volumes to the volserver */
4613 VWaitForOfflineByVp_r(ec, vp, salvok);
4615 VCancelReservation_r(vp);
4617 #endif /* AFS_DEMAND_ATTACH_FS */
4620 VOffline(Volume * vp, char *message)
4623 VOffline_r(vp, message);
4627 /* This gets used for the most part by utility routines that don't want
4628 * to keep all the volume headers around. Generally, the file server won't
4629 * call this routine, because then the offline message in the volume header
4630 * (or other information) won't be available to clients. For NAMEI, also
4631 * close the file handles. However, the fileserver does call this during
4632 * an attach following a volume operation.
4635 VDetachVolume_r(Error * ec, Volume * vp)
4637 #ifdef FSSYNC_BUILD_CLIENT
4639 struct DiskPartition64 *tpartp;
4640 int notifyServer = 0;
4641 int useDone = FSYNC_VOL_ON;
4643 if (VCanUseFSSYNC()) {
4644 notifyServer = vp->needsPutBack;
4645 if (V_destroyMe(vp) == DESTROY_ME)
4646 useDone = FSYNC_VOL_LEAVE_OFF;
4647 #ifdef AFS_DEMAND_ATTACH_FS
4648 else if (!V_blessed(vp) || !V_inService(vp))
4649 useDone = FSYNC_VOL_LEAVE_OFF;
4652 tpartp = vp->partition;
4654 #endif /* FSSYNC_BUILD_CLIENT */
4656 *ec = 0; /* always "succeeds" */
4657 DeleteVolumeFromHashTable(vp);
4658 vp->shuttingDown = 1;
4659 #ifdef AFS_DEMAND_ATTACH_FS
4660 DeleteVolumeFromVByPList_r(vp);
4662 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4664 if (programType != fileServer)
4666 #endif /* AFS_DEMAND_ATTACH_FS */
4668 /* Will be detached sometime in the future--this is OK since volume is offline */
4670 /* XXX the following code should really be moved to VCheckDetach() since the volume
4671 * is not technically detached until the refcounts reach zero
4673 #ifdef FSSYNC_BUILD_CLIENT
4674 if (VCanUseFSSYNC() && notifyServer) {
4675 if (notifyServer == VOL_PUTBACK_DELETE) {
4676 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4677 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4678 * to signify a deleted volume. */
4679 useDone = FSYNC_VOL_DONE;
4682 * Note: The server is not notified in the case of a bogus volume
4683 * explicitly to make it possible to create a volume, do a partial
4684 * restore, then abort the operation without ever putting the volume
4685 * online. This is essential in the case of a volume move operation
4686 * between two partitions on the same server. In that case, there
4687 * would be two instances of the same volume, one of them bogus,
4688 * which the file server would attempt to put on line
4690 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4691 /* XXX this code path is only hit by volume utilities, thus
4692 * V_BreakVolumeCallbacks will always be NULL. if we really
4693 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4695 /* Dettaching it so break all callbacks on it */
4696 if (V_BreakVolumeCallbacks) {
4697 Log("volume %u detached; breaking all call backs\n", volume);
4698 (*V_BreakVolumeCallbacks) (volume);
4702 #endif /* FSSYNC_BUILD_CLIENT */
4706 VDetachVolume(Error * ec, Volume * vp)
4709 VDetachVolume_r(ec, vp);
4714 /***************************************************/
4715 /* Volume fd/inode handle closing routines */
4716 /***************************************************/
4718 /* For VDetachVolume, we close all cached file descriptors, but keep
4719 * the Inode handles in case we need to read from a busy volume.
4721 /* for demand attach, caller MUST hold ref count on vp */
4723 VCloseVolumeHandles_r(Volume * vp)
4725 #ifdef AFS_DEMAND_ATTACH_FS
4726 VolState state_save;
4728 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4733 DFlushVolume(vp->hashid);
4735 #ifdef AFS_DEMAND_ATTACH_FS
4739 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4740 VCloseVnodeFiles_r(vp);
4742 #ifdef AFS_DEMAND_ATTACH_FS
4746 /* Too time consuming and unnecessary for the volserver */
4747 if (programType == fileServer) {
4748 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4749 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4750 IH_CONDSYNC(vp->diskDataHandle);
4752 IH_CONDSYNC(vp->linkHandle);
4753 #endif /* AFS_NT40_ENV */
4756 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4757 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4758 IH_REALLYCLOSE(vp->diskDataHandle);
4759 IH_REALLYCLOSE(vp->linkHandle);
4761 #ifdef AFS_DEMAND_ATTACH_FS
4762 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4767 VChangeState_r(vp, state_save);
4771 /* For both VForceOffline and VOffline, we close all relevant handles.
4772 * For VOffline, if we re-attach the volume, the files may possible be
4773 * different than before.
4775 /* for demand attach, caller MUST hold a ref count on vp */
4777 VReleaseVolumeHandles_r(Volume * vp)
4779 #ifdef AFS_DEMAND_ATTACH_FS
4780 VolState state_save;
4782 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4787 DFlushVolume(vp->hashid);
4789 #ifdef AFS_DEMAND_ATTACH_FS
4793 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4795 #ifdef AFS_DEMAND_ATTACH_FS
4799 /* Too time consuming and unnecessary for the volserver */
4800 if (programType == fileServer) {
4801 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4802 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4803 IH_CONDSYNC(vp->diskDataHandle);
4805 IH_CONDSYNC(vp->linkHandle);
4806 #endif /* AFS_NT40_ENV */
4809 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4810 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4811 IH_RELEASE(vp->diskDataHandle);
4812 IH_RELEASE(vp->linkHandle);
4814 #ifdef AFS_DEMAND_ATTACH_FS
4815 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4820 VChangeState_r(vp, state_save);
4825 /***************************************************/
4826 /* Volume write and fsync routines */
4827 /***************************************************/
4830 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4832 #ifdef AFS_DEMAND_ATTACH_FS
4833 VolState state_save;
4835 if (flags & VOL_UPDATE_WAIT) {
4836 VCreateReservation_r(vp);
4837 VWaitExclusiveState_r(vp);
4842 if (programType == fileServer)
4844 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4845 200 : V_nextVnodeUnique(vp));
4847 #ifdef AFS_DEMAND_ATTACH_FS
4848 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4852 WriteVolumeHeader_r(ec, vp);
4854 #ifdef AFS_DEMAND_ATTACH_FS
4856 VChangeState_r(vp, state_save);
4857 if (flags & VOL_UPDATE_WAIT) {
4858 VCancelReservation_r(vp);
4863 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4864 V_id(vp), V_name(vp));
4865 /* try to update on-disk header,
4866 * while preventing infinite recursion */
4867 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4868 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4874 VUpdateVolume(Error * ec, Volume * vp)
4877 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4882 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4886 #ifdef AFS_DEMAND_ATTACH_FS
4887 VolState state_save;
4890 if (flags & VOL_SYNC_WAIT) {
4891 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4893 VUpdateVolume_r(ec, vp, 0);
4896 #ifdef AFS_DEMAND_ATTACH_FS
4897 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4900 fdP = IH_OPEN(V_diskDataHandle(vp));
4901 osi_Assert(fdP != NULL);
4902 code = FDH_SYNC(fdP);
4903 osi_Assert(code == 0);
4905 #ifdef AFS_DEMAND_ATTACH_FS
4907 VChangeState_r(vp, state_save);
4913 VSyncVolume(Error * ec, Volume * vp)
4916 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4921 /***************************************************/
4922 /* Volume dealloaction routines */
4923 /***************************************************/
4925 #ifdef AFS_DEMAND_ATTACH_FS
4927 FreeVolume(Volume * vp)
4929 /* free the heap space, iff it's safe.
4930 * otherwise, pull it out of the hash table, so it
4931 * will get deallocated when all refs to it go away */
4932 if (!VCheckFree(vp)) {
4933 DeleteVolumeFromHashTable(vp);
4934 DeleteVolumeFromVByPList_r(vp);
4936 /* make sure we invalidate the header cache entry */
4937 FreeVolumeHeader(vp);
4940 #endif /* AFS_DEMAND_ATTACH_FS */
4943 ReallyFreeVolume(Volume * vp)
4948 #ifdef AFS_DEMAND_ATTACH_FS
4950 VChangeState_r(vp, VOL_STATE_FREED);
4951 if (vp->pending_vol_op)
4952 free(vp->pending_vol_op);
4953 #endif /* AFS_DEMAND_ATTACH_FS */
4954 for (i = 0; i < nVNODECLASSES; i++)
4955 if (vp->vnodeIndex[i].bitmap)
4956 free(vp->vnodeIndex[i].bitmap);
4957 FreeVolumeHeader(vp);
4958 #ifndef AFS_DEMAND_ATTACH_FS
4959 DeleteVolumeFromHashTable(vp);
4960 #endif /* AFS_DEMAND_ATTACH_FS */
4964 /* check to see if we should shutdown this volume
4965 * returns 1 if volume was freed, 0 otherwise */
4966 #ifdef AFS_DEMAND_ATTACH_FS
4968 VCheckDetach(Volume * vp)
4973 if (vp->nUsers || vp->nWaiters)
4976 if (vp->shuttingDown) {
4978 if ((programType != fileServer) &&
4979 (V_inUse(vp) == programType) &&
4980 ((V_checkoutMode(vp) == V_VOLUPD) ||
4981 (V_checkoutMode(vp) == V_SECRETLY) ||
4982 ((V_checkoutMode(vp) == V_CLONE) &&
4983 (VolumeWriteable(vp))))) {
4985 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4987 Log("VCheckDetach: volume header update for volume %u "
4988 "failed with errno %d\n", vp->hashid, errno);
4991 VReleaseVolumeHandles_r(vp);
4993 ReallyFreeVolume(vp);
4994 if (programType == fileServer) {
4995 CV_BROADCAST(&vol_put_volume_cond);
5000 #else /* AFS_DEMAND_ATTACH_FS */
5002 VCheckDetach(Volume * vp)
5010 if (vp->shuttingDown) {
5012 if ((programType != fileServer) &&
5013 (V_inUse(vp) == programType) &&
5014 ((V_checkoutMode(vp) == V_VOLUPD) ||
5015 (V_checkoutMode(vp) == V_SECRETLY) ||
5016 ((V_checkoutMode(vp) == V_CLONE) &&
5017 (VolumeWriteable(vp))))) {
5019 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5021 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5025 VReleaseVolumeHandles_r(vp);
5026 ReallyFreeVolume(vp);
5027 if (programType == fileServer) {
5028 #if defined(AFS_PTHREAD_ENV)
5029 CV_BROADCAST(&vol_put_volume_cond);
5030 #else /* AFS_PTHREAD_ENV */
5031 LWP_NoYieldSignal(VPutVolume);
5032 #endif /* AFS_PTHREAD_ENV */
5037 #endif /* AFS_DEMAND_ATTACH_FS */
5039 /* check to see if we should offline this volume
5040 * return 1 if volume went offline, 0 otherwise */
5041 #ifdef AFS_DEMAND_ATTACH_FS
5043 VCheckOffline(Volume * vp)
5047 if (vp->goingOffline && !vp->nUsers) {
5049 osi_Assert(programType == fileServer);
5050 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5051 (V_attachState(vp) != VOL_STATE_FREED) &&
5052 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5053 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5054 (V_attachState(vp) != VOL_STATE_DELETED));
5058 * VOL_STATE_GOING_OFFLINE
5059 * VOL_STATE_SHUTTING_DOWN
5060 * VIsErrorState(V_attachState(vp))
5061 * VIsExclusiveState(V_attachState(vp))
5064 VCreateReservation_r(vp);
5065 VChangeState_r(vp, VOL_STATE_OFFLINING);
5068 /* must clear the goingOffline flag before we drop the glock */
5069 vp->goingOffline = 0;
5074 /* perform async operations */
5075 VUpdateVolume_r(&error, vp, 0);
5076 VCloseVolumeHandles_r(vp);
5079 if (V_offlineMessage(vp)[0]) {
5080 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5081 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5082 V_offlineMessage(vp));
5084 Log("VOffline: Volume %lu (%s) is now offline\n",
5085 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5089 /* invalidate the volume header cache entry */
5090 FreeVolumeHeader(vp);
5092 /* if nothing changed state to error or salvaging,
5093 * drop state to unattached */
5094 if (!VIsErrorState(V_attachState(vp))) {
5095 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5097 VCancelReservation_r(vp);
5098 /* no usage of vp is safe beyond this point */
5102 #else /* AFS_DEMAND_ATTACH_FS */
5104 VCheckOffline(Volume * vp)
5108 if (vp->goingOffline && !vp->nUsers) {
5110 osi_Assert(programType == fileServer);
5113 vp->goingOffline = 0;
5115 VUpdateVolume_r(&error, vp, 0);
5116 VCloseVolumeHandles_r(vp);
5118 if (V_offlineMessage(vp)[0]) {
5119 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5120 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5121 V_offlineMessage(vp));
5123 Log("VOffline: Volume %lu (%s) is now offline\n",
5124 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5127 FreeVolumeHeader(vp);
5128 #ifdef AFS_PTHREAD_ENV
5129 CV_BROADCAST(&vol_put_volume_cond);
5130 #else /* AFS_PTHREAD_ENV */
5131 LWP_NoYieldSignal(VPutVolume);
5132 #endif /* AFS_PTHREAD_ENV */
5136 #endif /* AFS_DEMAND_ATTACH_FS */
5138 /***************************************************/
5139 /* demand attach fs ref counting routines */
5140 /***************************************************/
5142 #ifdef AFS_DEMAND_ATTACH_FS
5143 /* the following two functions handle reference counting for
5144 * asynchronous operations on volume structs.
5146 * their purpose is to prevent a VDetachVolume or VShutdown
5147 * from free()ing the Volume struct during an async i/o op */
5149 /* register with the async volume op ref counter */
5150 /* VCreateReservation_r moved into inline code header because it
5151 * is now needed in vnode.c -- tkeiser 11/20/2007
5155 * decrement volume-package internal refcount.
5157 * @param vp volume object pointer
5159 * @internal volume package internal use only
5162 * @arg VOL_LOCK is held
5163 * @arg lightweight refcount held
5165 * @post volume waiters refcount is decremented; volume may
5166 * have been deallocated/shutdown/offlined/salvaged/
5167 * whatever during the process
5169 * @warning once you have tossed your last reference (you can acquire
5170 * lightweight refs recursively) it is NOT SAFE to reference
5171 * a volume object pointer ever again
5173 * @see VCreateReservation_r
5175 * @note DEMAND_ATTACH_FS only
5178 VCancelReservation_r(Volume * vp)
5180 osi_Assert(--vp->nWaiters >= 0);
5181 if (vp->nWaiters == 0) {
5183 if (!VCheckDetach(vp)) {
5190 /* check to see if we should free this volume now
5191 * return 1 if volume was freed, 0 otherwise */
5193 VCheckFree(Volume * vp)
5196 if ((vp->nUsers == 0) &&
5197 (vp->nWaiters == 0) &&
5198 !(V_attachFlags(vp) & (VOL_IN_HASH |
5202 ReallyFreeVolume(vp);
5207 #endif /* AFS_DEMAND_ATTACH_FS */
5210 /***************************************************/
5211 /* online volume operations routines */
5212 /***************************************************/
5214 #ifdef AFS_DEMAND_ATTACH_FS
5216 * register a volume operation on a given volume.
5218 * @param[in] vp volume object
5219 * @param[in] vopinfo volume operation info object
5221 * @pre VOL_LOCK is held
5223 * @post volume operation info object attached to volume object.
5224 * volume operation statistics updated.
5226 * @note by "attached" we mean a copy of the passed in object is made
5228 * @internal volume package internal use only
5231 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5233 FSSYNC_VolOp_info * info;
5235 /* attach a vol op info node to the volume struct */
5236 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5237 osi_Assert(info != NULL);
5238 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5239 vp->pending_vol_op = info;
5242 vp->stats.last_vol_op = FT_ApproxTime();
5243 vp->stats.vol_ops++;
5244 IncUInt64(&VStats.vol_ops);
5250 * deregister the volume operation attached to this volume.
5252 * @param[in] vp volume object pointer
5254 * @pre VOL_LOCK is held
5256 * @post the volume operation info object is detached from the volume object
5258 * @internal volume package internal use only
5261 VDeregisterVolOp_r(Volume * vp)
5263 if (vp->pending_vol_op) {
5264 free(vp->pending_vol_op);
5265 vp->pending_vol_op = NULL;
5269 #endif /* AFS_DEMAND_ATTACH_FS */
5272 * determine whether it is safe to leave a volume online during
5273 * the volume operation described by the vopinfo object.
5275 * @param[in] vp volume object
5276 * @param[in] vopinfo volume operation info object
5278 * @return whether it is safe to leave volume online
5279 * @retval 0 it is NOT SAFE to leave the volume online
5280 * @retval 1 it is safe to leave the volume online during the operation
5283 * @arg VOL_LOCK is held
5284 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5285 * this condition is met)
5287 * @internal volume package internal use only
5290 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5292 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5293 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5294 (vopinfo->com.reason == V_READONLY ||
5295 (!VolumeWriteable(vp) &&
5296 (vopinfo->com.reason == V_CLONE ||
5297 vopinfo->com.reason == V_DUMP)))));
5301 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5304 * @param[in] vp volume object
5305 * @param[in] vopinfo volume operation info object
5307 * @return whether it is safe to leave volume online
5308 * @retval 0 it is NOT SAFE to leave the volume online
5309 * @retval 1 it is safe to leave the volume online during the operation
5310 * @retval -1 unsure; volume header is required in order to know whether or
5311 * not is is safe to leave the volume online
5313 * @pre VOL_LOCK is held
5315 * @internal volume package internal use only
5318 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5320 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5321 * assume that we don't know VolumeWriteable; return -1 if the answer
5322 * depends on VolumeWriteable */
5324 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5327 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5328 vopinfo->com.reason == V_READONLY) {
5332 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5333 (vopinfo->com.reason == V_CLONE ||
5334 vopinfo->com.reason == V_DUMP)) {
5336 /* must know VolumeWriteable */
5343 * determine whether VBUSY should be set during this volume operation.
5345 * @param[in] vp volume object
5346 * @param[in] vopinfo volume operation info object
5348 * @return whether VBUSY should be set
5349 * @retval 0 VBUSY does NOT need to be set
5350 * @retval 1 VBUSY SHOULD be set
5352 * @pre VOL_LOCK is held
5354 * @internal volume package internal use only
5357 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5359 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5360 vopinfo->com.reason == FSYNC_SALVAGE) ||
5361 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5362 (vopinfo->com.reason == V_CLONE ||
5363 vopinfo->com.reason == V_DUMP)));
5367 /***************************************************/
5368 /* online salvager routines */
5369 /***************************************************/
5370 #if defined(AFS_DEMAND_ATTACH_FS)
5373 * offline a volume to let it be salvaged.
5375 * @param[in] vp Volume to offline
5377 * @return whether we offlined the volume successfully
5378 * @retval 0 volume was not offlined
5379 * @retval 1 volume is now offline
5381 * @note This is similar to VCheckOffline, but slightly different. We do not
5382 * deal with vp->goingOffline, and we try to avoid touching the volume
5383 * header except just to set needsSalvaged
5385 * @pre VOL_LOCK held
5386 * @pre vp->nUsers == 0
5387 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5390 VOfflineForSalvage_r(struct Volume *vp)
5394 VCreateReservation_r(vp);
5395 VWaitExclusiveState_r(vp);
5397 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5398 /* Someone's using the volume, or someone got to scheduling the salvage
5399 * before us. I don't think either of these should be possible, as we
5400 * should gain no new heavyweight references while we're trying to
5401 * salvage, but just to be sure... */
5402 VCancelReservation_r(vp);
5406 VChangeState_r(vp, VOL_STATE_OFFLINING);
5410 V_needsSalvaged(vp) = 1;
5411 /* ignore error; updating needsSalvaged is just best effort */
5412 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5414 VCloseVolumeHandles_r(vp);
5416 FreeVolumeHeader(vp);
5418 /* volume has been effectively offlined; we can mark it in the SALVAGING
5419 * state now, which lets FSSYNC give it away */
5420 VChangeState_r(vp, VOL_STATE_SALVAGING);
5422 VCancelReservation_r(vp);
5428 * check whether a salvage needs to be performed on this volume.
5430 * @param[in] vp pointer to volume object
5432 * @return status code
5433 * @retval 0 no salvage scheduled
5434 * @retval 1 a salvage has been scheduled with the salvageserver
5436 * @pre VOL_LOCK is held
5438 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5439 * then a salvage will be requested
5441 * @note this is one of the event handlers called by VCancelReservation_r
5443 * @note the caller must check if the volume needs to be freed after calling
5444 * this; the volume may not have any references or be on any lists after
5445 * we return, and we do not free it
5447 * @see VCancelReservation_r
5449 * @internal volume package internal use only.
5452 VCheckSalvage(Volume * vp)
5455 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5458 if (!vp->salvage.requested) {
5462 /* prevent recursion; some of the code below creates and removes
5463 * lightweight refs, which can call VCheckSalvage */
5464 if (vp->salvage.scheduling) {
5467 vp->salvage.scheduling = 1;
5469 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5470 if (!VOfflineForSalvage_r(vp)) {
5471 vp->salvage.scheduling = 0;
5476 if (vp->salvage.requested) {
5477 VScheduleSalvage_r(vp);
5480 vp->salvage.scheduling = 0;
5481 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5486 * request volume salvage.
5488 * @param[out] ec computed client error code
5489 * @param[in] vp volume object pointer
5490 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5491 * @param[in] flags see flags note below
5494 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
5495 * to be invalidated.
5497 * @pre VOL_LOCK is held.
5499 * @post volume state is changed.
5500 * for fileserver, salvage will be requested once refcount reaches zero.
5502 * @return operation status code
5503 * @retval 0 volume salvage will occur
5504 * @retval 1 volume salvage could not be scheduled
5508 * @note in the fileserver, this call does not synchronously schedule a volume
5509 * salvage. rather, it sets volume state so that when volume refcounts
5510 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5511 * nUsers and nWaiters must be zero.
5513 * @internal volume package internal use only.
5516 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5520 * for DAFS volume utilities that are not supposed to schedule salvages,
5521 * just transition to error state instead
5523 if (!VCanScheduleSalvage()) {
5524 VChangeState_r(vp, VOL_STATE_ERROR);
5529 if (programType != fileServer && !VCanUseFSSYNC()) {
5530 VChangeState_r(vp, VOL_STATE_ERROR);
5535 if (!vp->salvage.requested) {
5536 vp->salvage.requested = 1;
5537 vp->salvage.reason = reason;
5538 vp->stats.last_salvage = FT_ApproxTime();
5540 /* Note that it is not possible for us to reach this point if a
5541 * salvage is already running on this volume (even if the fileserver
5542 * was restarted during the salvage). If a salvage were running, the
5543 * salvager would have write-locked the volume header file, so when
5544 * we tried to lock the volume header, the lock would have failed,
5545 * and we would have failed during attachment prior to calling
5546 * VRequestSalvage. So we know that we can schedule salvages without
5547 * fear of a salvage already running for this volume. */
5549 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5551 /* if we don't need to offline the volume, we can go directly
5552 * to SALVAGING. SALVAGING says the volume is offline and is
5553 * either salvaging or ready to be handed to the salvager.
5554 * SALVAGE_REQ says that we want to salvage the volume, but we
5555 * are waiting for it to go offline first. */
5556 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5557 VChangeState_r(vp, VOL_STATE_SALVAGING);
5559 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5560 if (vp->nUsers == 0) {
5561 /* normally VOfflineForSalvage_r would be called from
5562 * PutVolume et al when nUsers reaches 0, but if
5563 * it's already 0, just do it ourselves, since PutVolume
5564 * isn't going to get called */
5565 VOfflineForSalvage_r(vp);
5570 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5572 /* make sure neither VScheduleSalvage_r nor
5573 * VUpdateSalvagePriority_r try to schedule another salvage */
5574 vp->salvage.requested = vp->salvage.scheduled = 0;
5576 VChangeState_r(vp, VOL_STATE_ERROR);
5580 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
5581 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
5582 so that the the next VAttachVolumeByVp_r() invocation
5583 of attach2() will pull in a cached header
5584 entry and fail, then load a fresh one from disk and attach
5587 FreeVolumeHeader(vp);
5594 * update salvageserver scheduling priority for a volume.
5596 * @param[in] vp pointer to volume object
5598 * @return operation status
5600 * @retval 1 request denied, or SALVSYNC communications failure
5602 * @pre VOL_LOCK is held.
5604 * @post in-core salvage priority counter is incremented. if at least
5605 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5606 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5607 * to update its priority queue. if no salvage is scheduled,
5608 * this function is a no-op.
5610 * @note DAFS fileserver only
5612 * @note this should be called whenever a VGetVolume fails due to a
5613 * pending salvage request
5615 * @todo should set exclusive state and drop glock around salvsync call
5617 * @internal volume package internal use only.
5620 VUpdateSalvagePriority_r(Volume * vp)
5624 #ifdef SALVSYNC_BUILD_CLIENT
5629 now = FT_ApproxTime();
5631 /* update the salvageserver priority queue occasionally so that
5632 * frequently requested volumes get moved to the head of the queue
5634 if ((vp->salvage.scheduled) &&
5635 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5636 code = SALVSYNC_SalvageVolume(vp->hashid,
5637 VPartitionPath(vp->partition),
5642 vp->stats.last_salvage_req = now;
5643 if (code != SYNC_OK) {
5647 #endif /* SALVSYNC_BUILD_CLIENT */
5652 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5654 /* A couple of little helper functions. These return true if we tried to
5655 * use this mechanism to schedule a salvage, false if we haven't tried.
5656 * If we did try a salvage then the results are contained in code.
5660 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5661 #ifdef SALVSYNC_BUILD_CLIENT
5662 if (VCanUseSALVSYNC()) {
5663 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5664 afs_printable_uint32_lu(vp->hashid), partName);
5666 /* can't use V_id() since there's no guarantee
5667 * we have the disk data header at this point */
5668 *code = SALVSYNC_SalvageVolume(vp->hashid,
5681 try_FSSYNC(Volume *vp, char *partName, int *code) {
5682 #ifdef FSSYNC_BUILD_CLIENT
5683 if (VCanUseFSSYNC()) {
5684 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5685 afs_printable_uint32_lu(vp->hashid), partName);
5688 * If we aren't the fileserver, tell the fileserver the volume
5689 * needs to be salvaged. We could directly tell the
5690 * salvageserver, but the fileserver keeps track of some stats
5691 * related to salvages, and handles some other salvage-related
5692 * complications for us.
5694 *code = FSYNC_VolOp(vp->hashid, partName,
5695 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5698 #endif /* FSSYNC_BUILD_CLIENT */
5703 * schedule a salvage with the salvage server or fileserver.
5705 * @param[in] vp pointer to volume object
5707 * @return operation status
5708 * @retval 0 salvage scheduled successfully
5709 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5712 * @arg VOL_LOCK is held.
5713 * @arg nUsers and nWaiters should be zero.
5715 * @post salvageserver or fileserver is sent a salvage request
5717 * @note If we are the fileserver, the request will be sent to the salvage
5718 * server over SALVSYNC. If we are not the fileserver, the request will be
5719 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5721 * @note the caller must check if the volume needs to be freed after calling
5722 * this; the volume may not have any references or be on any lists after
5723 * we return, and we do not free it
5727 * @internal volume package internal use only.
5730 VScheduleSalvage_r(Volume * vp)
5734 VolState state_save;
5735 VThreadOptions_t * thread_opts;
5738 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5740 if (vp->nWaiters || vp->nUsers) {
5744 /* prevent endless salvage,attach,salvage,attach,... loops */
5745 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5749 * don't perform salvsync ops on certain threads
5751 thread_opts = pthread_getspecific(VThread_key);
5752 if (thread_opts == NULL) {
5753 thread_opts = &VThread_defaults;
5755 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5759 if (vp->salvage.scheduled) {
5763 VCreateReservation_r(vp);
5764 VWaitExclusiveState_r(vp);
5767 * XXX the scheduling process should really be done asynchronously
5768 * to avoid fssync deadlocks
5770 if (!vp->salvage.scheduled) {
5771 /* if we haven't previously scheduled a salvage, do so now
5773 * set the volume to an exclusive state and drop the lock
5774 * around the SALVSYNC call
5776 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5777 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5780 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5781 try_FSSYNC(vp, partName, &code));
5784 VChangeState_r(vp, state_save);
5786 if (code == SYNC_OK) {
5787 vp->salvage.scheduled = 1;
5788 vp->stats.last_salvage_req = FT_ApproxTime();
5789 if (VCanUseSALVSYNC()) {
5790 /* don't record these stats for non-fileservers; let the
5791 * fileserver take care of these */
5792 vp->stats.salvages++;
5793 IncUInt64(&VStats.salvages);
5798 case SYNC_BAD_COMMAND:
5799 case SYNC_COM_ERROR:
5802 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5803 "denied\n", afs_printable_uint32_lu(vp->hashid));
5806 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5807 "received unknown protocol error %d\n",
5808 afs_printable_uint32_lu(vp->hashid), code);
5812 if (VCanUseFSSYNC()) {
5813 VChangeState_r(vp, VOL_STATE_ERROR);
5818 /* NB: this is cancelling the reservation we obtained above, but we do
5819 * not call VCancelReservation_r, since that may trigger the vp dtor,
5820 * possibly free'ing the vp. We need to keep the vp around after
5821 * this, as the caller may reference vp without any refs. Instead, it
5822 * is the duty of the caller to inspect 'vp' after we return to see if
5823 * needs to be freed. */
5824 osi_Assert(--vp->nWaiters >= 0);
5827 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5829 #ifdef SALVSYNC_BUILD_CLIENT
5832 * connect to the salvageserver SYNC service.
5834 * @return operation status
5838 * @post connection to salvageserver SYNC service established
5840 * @see VConnectSALV_r
5841 * @see VDisconnectSALV
5842 * @see VReconnectSALV
5849 retVal = VConnectSALV_r();
5855 * connect to the salvageserver SYNC service.
5857 * @return operation status
5861 * @pre VOL_LOCK is held.
5863 * @post connection to salvageserver SYNC service established
5866 * @see VDisconnectSALV_r
5867 * @see VReconnectSALV_r
5868 * @see SALVSYNC_clientInit
5870 * @internal volume package internal use only.
5873 VConnectSALV_r(void)
5875 return SALVSYNC_clientInit();
5879 * disconnect from the salvageserver SYNC service.
5881 * @return operation status
5884 * @pre client should have a live connection to the salvageserver
5886 * @post connection to salvageserver SYNC service destroyed
5888 * @see VDisconnectSALV_r
5890 * @see VReconnectSALV
5893 VDisconnectSALV(void)
5896 VDisconnectSALV_r();
5902 * disconnect from the salvageserver SYNC service.
5904 * @return operation status
5908 * @arg VOL_LOCK is held.
5909 * @arg client should have a live connection to the salvageserver.
5911 * @post connection to salvageserver SYNC service destroyed
5913 * @see VDisconnectSALV
5914 * @see VConnectSALV_r
5915 * @see VReconnectSALV_r
5916 * @see SALVSYNC_clientFinis
5918 * @internal volume package internal use only.
5921 VDisconnectSALV_r(void)
5923 return SALVSYNC_clientFinis();
5927 * disconnect and then re-connect to the salvageserver SYNC service.
5929 * @return operation status
5933 * @pre client should have a live connection to the salvageserver
5935 * @post old connection is dropped, and a new one is established
5938 * @see VDisconnectSALV
5939 * @see VReconnectSALV_r
5942 VReconnectSALV(void)
5946 retVal = VReconnectSALV_r();
5952 * disconnect and then re-connect to the salvageserver SYNC service.
5954 * @return operation status
5959 * @arg VOL_LOCK is held.
5960 * @arg client should have a live connection to the salvageserver.
5962 * @post old connection is dropped, and a new one is established
5964 * @see VConnectSALV_r
5965 * @see VDisconnectSALV
5966 * @see VReconnectSALV
5967 * @see SALVSYNC_clientReconnect
5969 * @internal volume package internal use only.
5972 VReconnectSALV_r(void)
5974 return SALVSYNC_clientReconnect();
5976 #endif /* SALVSYNC_BUILD_CLIENT */
5977 #endif /* AFS_DEMAND_ATTACH_FS */
5980 /***************************************************/
5981 /* FSSYNC routines */
5982 /***************************************************/
5984 /* This must be called by any volume utility which needs to run while the
5985 file server is also running. This is separated from VInitVolumePackage2 so
5986 that a utility can fork--and each of the children can independently
5987 initialize communication with the file server */
5988 #ifdef FSSYNC_BUILD_CLIENT
5990 * connect to the fileserver SYNC service.
5992 * @return operation status
5997 * @arg VInit must equal 2.
5998 * @arg Program Type must not be fileserver or salvager.
6000 * @post connection to fileserver SYNC service established
6003 * @see VDisconnectFS
6004 * @see VChildProcReconnectFS
6011 retVal = VConnectFS_r();
6017 * connect to the fileserver SYNC service.
6019 * @return operation status
6024 * @arg VInit must equal 2.
6025 * @arg Program Type must not be fileserver or salvager.
6026 * @arg VOL_LOCK is held.
6028 * @post connection to fileserver SYNC service established
6031 * @see VDisconnectFS_r
6032 * @see VChildProcReconnectFS_r
6034 * @internal volume package internal use only.
6040 osi_Assert((VInit == 2) &&
6041 (programType != fileServer) &&
6042 (programType != salvager));
6043 rc = FSYNC_clientInit();
6051 * disconnect from the fileserver SYNC service.
6054 * @arg client should have a live connection to the fileserver.
6055 * @arg VOL_LOCK is held.
6056 * @arg Program Type must not be fileserver or salvager.
6058 * @post connection to fileserver SYNC service destroyed
6060 * @see VDisconnectFS
6062 * @see VChildProcReconnectFS_r
6064 * @internal volume package internal use only.
6067 VDisconnectFS_r(void)
6069 osi_Assert((programType != fileServer) &&
6070 (programType != salvager));
6071 FSYNC_clientFinis();
6076 * disconnect from the fileserver SYNC service.
6079 * @arg client should have a live connection to the fileserver.
6080 * @arg Program Type must not be fileserver or salvager.
6082 * @post connection to fileserver SYNC service destroyed
6084 * @see VDisconnectFS_r
6086 * @see VChildProcReconnectFS
6097 * connect to the fileserver SYNC service from a child process following a fork.
6099 * @return operation status
6104 * @arg VOL_LOCK is held.
6105 * @arg current FSYNC handle is shared with a parent process
6107 * @post current FSYNC handle is discarded and a new connection to the
6108 * fileserver SYNC service is established
6110 * @see VChildProcReconnectFS
6112 * @see VDisconnectFS_r
6114 * @internal volume package internal use only.
6117 VChildProcReconnectFS_r(void)
6119 return FSYNC_clientChildProcReconnect();
6123 * connect to the fileserver SYNC service from a child process following a fork.
6125 * @return operation status
6129 * @pre current FSYNC handle is shared with a parent process
6131 * @post current FSYNC handle is discarded and a new connection to the
6132 * fileserver SYNC service is established
6134 * @see VChildProcReconnectFS_r
6136 * @see VDisconnectFS
6139 VChildProcReconnectFS(void)
6143 ret = VChildProcReconnectFS_r();
6147 #endif /* FSSYNC_BUILD_CLIENT */
6150 /***************************************************/
6151 /* volume bitmap routines */
6152 /***************************************************/
6155 * allocate a vnode bitmap number for the vnode
6157 * @param[out] ec error code
6158 * @param[in] vp volume object pointer
6159 * @param[in] index vnode index number for the vnode
6160 * @param[in] flags flag values described in note
6162 * @note for DAFS, flags parameter controls locking behavior.
6163 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6164 * will create a reservation and block on any other exclusive
6165 * operations. Otherwise, this function assumes the caller
6166 * already has exclusive access to vp, and we just change the
6169 * @pre VOL_LOCK held
6171 * @return bit number allocated
6177 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6178 struct vnodeIndex *index, int flags)
6182 #ifdef AFS_DEMAND_ATTACH_FS
6183 VolState state_save;
6184 #endif /* AFS_DEMAND_ATTACH_FS */
6188 /* This test is probably redundant */
6189 if (!VolumeWriteable(vp)) {
6190 *ec = (bit32) VREADONLY;
6194 #ifdef AFS_DEMAND_ATTACH_FS
6195 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6196 VCreateReservation_r(vp);
6197 VWaitExclusiveState_r(vp);
6199 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6200 #endif /* AFS_DEMAND_ATTACH_FS */
6203 if ((programType == fileServer) && !index->bitmap) {
6205 #ifndef AFS_DEMAND_ATTACH_FS
6206 /* demand attach fs uses the volume state to avoid races.
6207 * specialStatus field is not used at all */
6209 if (vp->specialStatus == VBUSY) {
6210 if (vp->goingOffline) { /* vos dump waiting for the volume to
6211 * go offline. We probably come here
6212 * from AddNewReadableResidency */
6215 while (vp->specialStatus == VBUSY) {
6216 #ifdef AFS_PTHREAD_ENV
6220 #else /* !AFS_PTHREAD_ENV */
6222 #endif /* !AFS_PTHREAD_ENV */
6226 #endif /* !AFS_DEMAND_ATTACH_FS */
6228 if (!index->bitmap) {
6229 #ifndef AFS_DEMAND_ATTACH_FS
6230 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6231 #endif /* AFS_DEMAND_ATTACH_FS */
6232 for (i = 0; i < nVNODECLASSES; i++) {
6233 VGetBitmap_r(ec, vp, i);
6235 #ifdef AFS_DEMAND_ATTACH_FS
6236 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
6237 #else /* AFS_DEMAND_ATTACH_FS */
6238 DeleteVolumeFromHashTable(vp);
6239 vp->shuttingDown = 1; /* Let who has it free it. */
6240 vp->specialStatus = 0;
6241 #endif /* AFS_DEMAND_ATTACH_FS */
6245 #ifndef AFS_DEMAND_ATTACH_FS
6247 vp->specialStatus = 0; /* Allow others to have access. */
6248 #endif /* AFS_DEMAND_ATTACH_FS */
6251 #endif /* BITMAP_LATER */
6253 #ifdef AFS_DEMAND_ATTACH_FS
6255 #endif /* AFS_DEMAND_ATTACH_FS */
6256 bp = index->bitmap + index->bitmapOffset;
6257 ep = index->bitmap + index->bitmapSize;
6259 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6261 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6264 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6266 ret = ((bp - index->bitmap) * 8 + o);
6267 #ifdef AFS_DEMAND_ATTACH_FS
6269 #endif /* AFS_DEMAND_ATTACH_FS */
6272 bp += sizeof(bit32) /* i.e. 4 */ ;
6274 /* No bit map entry--must grow bitmap */
6276 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6277 osi_Assert(bp != NULL);
6279 bp += index->bitmapSize;
6280 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6281 index->bitmapOffset = index->bitmapSize;
6282 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6284 ret = index->bitmapOffset * 8;
6285 #ifdef AFS_DEMAND_ATTACH_FS
6287 #endif /* AFS_DEMAND_ATTACH_FS */
6290 #ifdef AFS_DEMAND_ATTACH_FS
6291 VChangeState_r(vp, state_save);
6292 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6293 VCancelReservation_r(vp);
6295 #endif /* AFS_DEMAND_ATTACH_FS */
6300 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6304 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6310 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6311 unsigned bitNumber, int flags)
6313 unsigned int offset;
6317 #ifdef AFS_DEMAND_ATTACH_FS
6318 if (flags & VOL_FREE_BITMAP_WAIT) {
6319 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6320 * state, so ensure we're not in an exclusive volume state when we update
6322 VCreateReservation_r(vp);
6323 VWaitExclusiveState_r(vp);
6330 #endif /* BITMAP_LATER */
6332 offset = bitNumber >> 3;
6333 if (offset >= index->bitmapSize) {
6337 if (offset < index->bitmapOffset)
6338 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6339 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6342 #ifdef AFS_DEMAND_ATTACH_FS
6343 VCancelReservation_r(vp);
6345 return; /* make the compiler happy for non-DAFS */
6349 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6353 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6357 /* this function will drop the glock internally.
6358 * for old pthread fileservers, this is safe thanks to vbusy.
6360 * for demand attach fs, caller must have already called
6361 * VCreateReservation_r and VWaitExclusiveState_r */
6363 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6365 StreamHandle_t *file;
6366 afs_sfsize_t nVnodes, size;
6367 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6368 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6369 struct VnodeDiskObject *vnode;
6370 unsigned int unique = 0;
6374 #endif /* BITMAP_LATER */
6375 #ifdef AFS_DEMAND_ATTACH_FS
6376 VolState state_save;
6377 #endif /* AFS_DEMAND_ATTACH_FS */
6381 #ifdef AFS_DEMAND_ATTACH_FS
6382 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6383 #endif /* AFS_DEMAND_ATTACH_FS */
6386 fdP = IH_OPEN(vip->handle);
6387 osi_Assert(fdP != NULL);
6388 file = FDH_FDOPEN(fdP, "r");
6389 osi_Assert(file != NULL);
6390 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6391 osi_Assert(vnode != NULL);
6392 size = OS_SIZE(fdP->fd_fd);
6393 osi_Assert(size != -1);
6394 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6396 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6397 * a few files can be created in this volume,
6398 * the whole thing is rounded up to nearest 4
6399 * bytes, because the bit map allocator likes
6402 BitMap = (byte *) calloc(1, vip->bitmapSize);
6403 osi_Assert(BitMap != NULL);
6404 #else /* BITMAP_LATER */
6405 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6406 osi_Assert(vip->bitmap != NULL);
6407 vip->bitmapOffset = 0;
6408 #endif /* BITMAP_LATER */
6409 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6411 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6412 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6414 if (vnode->type != vNull) {
6415 if (vnode->vnodeMagic != vcp->magic) {
6416 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6421 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6422 #else /* BITMAP_LATER */
6423 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6424 #endif /* BITMAP_LATER */
6425 if (unique <= vnode->uniquifier)
6426 unique = vnode->uniquifier + 1;
6428 #ifndef AFS_PTHREAD_ENV
6429 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6432 #endif /* !AFS_PTHREAD_ENV */
6435 if (vp->nextVnodeUnique < unique) {
6436 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6439 /* Paranoia, partly justified--I think fclose after fdopen
6440 * doesn't seem to close fd. In any event, the documentation
6441 * doesn't specify, so it's safer to close it twice.
6449 /* There may have been a racing condition with some other thread, both
6450 * creating the bitmaps for this volume. If the other thread was faster
6451 * the pointer to bitmap should already be filled and we can free ours.
6453 if (vip->bitmap == NULL) {
6454 vip->bitmap = BitMap;
6455 vip->bitmapOffset = 0;
6457 free((byte *) BitMap);
6458 #endif /* BITMAP_LATER */
6459 #ifdef AFS_DEMAND_ATTACH_FS
6460 VChangeState_r(vp, state_save);
6461 #endif /* AFS_DEMAND_ATTACH_FS */
6465 /***************************************************/
6466 /* Volume Path and Volume Number utility routines */
6467 /***************************************************/
6470 * find the first occurrence of a volume header file and return the path.
6472 * @param[out] ec outbound error code
6473 * @param[in] volumeId volume id to find
6474 * @param[out] partitionp pointer to disk partition path string
6475 * @param[out] namep pointer to volume header file name string
6477 * @post path to first occurrence of volume header is returned in partitionp
6478 * and namep, or ec is set accordingly.
6480 * @warning this function is NOT re-entrant -- partitionp and namep point to
6481 * static data segments
6483 * @note if a volume utility inadvertently leaves behind a stale volume header
6484 * on a vice partition, it is possible for callers to get the wrong one,
6485 * depending on the order of the disk partition linked list.
6489 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6491 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6492 char path[VMAXPATHLEN];
6494 struct DiskPartition64 *dp;
6497 name[0] = OS_DIRSEPC;
6498 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
6499 for (dp = DiskPartitionList; dp; dp = dp->next) {
6500 struct afs_stat_st status;
6501 strcpy(path, VPartitionPath(dp));
6503 if (afs_stat(path, &status) == 0) {
6504 strcpy(partition, dp->name);
6511 *partitionp = *namep = NULL;
6513 *partitionp = partition;
6519 * extract a volume number from a volume header filename string.
6521 * @param[in] name volume header filename string
6523 * @return volume number
6525 * @note the string must be of the form VFORMAT. the only permissible
6526 * deviation is a leading OS_DIRSEPC character.
6531 VolumeNumber(char *name)
6533 if (*name == OS_DIRSEPC)
6535 return strtoul(name + 1, NULL, 10);
6539 * compute the volume header filename.
6541 * @param[in] volumeId
6543 * @return volume header filename
6545 * @post volume header filename string is constructed
6547 * @warning this function is NOT re-entrant -- the returned string is
6548 * stored in a static char array. see VolumeExternalName_r
6549 * for a re-entrant equivalent.
6551 * @see VolumeExternalName_r
6553 * @deprecated due to the above re-entrancy warning, this interface should
6554 * be considered deprecated. Please use VolumeExternalName_r
6558 VolumeExternalName(VolumeId volumeId)
6560 static char name[VMAXPATHLEN];
6561 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6566 * compute the volume header filename.
6568 * @param[in] volumeId
6569 * @param[inout] name array in which to store filename
6570 * @param[in] len length of name array
6572 * @return result code from afs_snprintf
6574 * @see VolumeExternalName
6577 * @note re-entrant equivalent of VolumeExternalName
6580 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6582 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6586 /***************************************************/
6587 /* Volume Usage Statistics routines */
6588 /***************************************************/
6590 #if OPENAFS_VOL_STATS
6591 #define OneDay (86400) /* 24 hours' worth of seconds */
6593 #define OneDay (24*60*60) /* 24 hours */
6594 #endif /* OPENAFS_VOL_STATS */
6597 Midnight(time_t t) {
6598 struct tm local, *l;
6601 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6602 l = localtime_r(&t, &local);
6608 /* the following is strictly speaking problematic on the
6609 switching day to daylight saving time, after the switch,
6610 as tm_isdst does not match. Similarly, on the looong day when
6611 switching back the OneDay check will not do what naively expected!
6612 The effects are minor, though, and more a matter of interpreting
6614 #ifndef AFS_PTHREAD_ENV
6617 local.tm_hour = local.tm_min=local.tm_sec = 0;
6618 midnight = mktime(&local);
6619 if (midnight != (time_t) -1) return(midnight);
6621 return( (t/OneDay)*OneDay );
6625 /*------------------------------------------------------------------------
6626 * [export] VAdjustVolumeStatistics
6629 * If we've passed midnight, we need to update all the day use
6630 * statistics as well as zeroing the detailed volume statistics
6631 * (if we are implementing them).
6634 * vp : Pointer to the volume structure describing the lucky
6635 * volume being considered for update.
6641 * Nothing interesting.
6645 *------------------------------------------------------------------------*/
6648 VAdjustVolumeStatistics_r(Volume * vp)
6650 unsigned int now = FT_ApproxTime();
6652 if (now - V_dayUseDate(vp) > OneDay) {
6655 ndays = (now - V_dayUseDate(vp)) / OneDay;
6656 for (i = 6; i > ndays - 1; i--)
6657 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6658 for (i = 0; i < ndays - 1 && i < 7; i++)
6659 V_weekUse(vp)[i] = 0;
6661 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6663 V_dayUseDate(vp) = Midnight(now);
6665 #if OPENAFS_VOL_STATS
6667 * All we need to do is bzero the entire VOL_STATS_BYTES of
6668 * the detailed volume statistics area.
6670 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6671 #endif /* OPENAFS_VOL_STATS */
6674 /*It's been more than a day of collection */
6676 * Always return happily.
6679 } /*VAdjustVolumeStatistics */
6682 VAdjustVolumeStatistics(Volume * vp)
6686 retVal = VAdjustVolumeStatistics_r(vp);
6692 VBumpVolumeUsage_r(Volume * vp)
6694 unsigned int now = FT_ApproxTime();
6695 V_accessDate(vp) = now;
6696 if (now - V_dayUseDate(vp) > OneDay)
6697 VAdjustVolumeStatistics_r(vp);
6699 * Save the volume header image to disk after every 128 bumps to dayUse.
6701 if ((V_dayUse(vp)++ & 127) == 0) {
6703 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6708 VBumpVolumeUsage(Volume * vp)
6711 VBumpVolumeUsage_r(vp);
6716 VSetDiskUsage_r(void)
6718 #ifndef AFS_DEMAND_ATTACH_FS
6719 static int FifteenMinuteCounter = 0;
6723 /* NOTE: Don't attempt to access the partitions list until the
6724 * initialization level indicates that all volumes are attached,
6725 * which implies that all partitions are initialized. */
6726 #ifdef AFS_PTHREAD_ENV
6727 VOL_CV_WAIT(&vol_vinit_cond);
6728 #else /* AFS_PTHREAD_ENV */
6730 #endif /* AFS_PTHREAD_ENV */
6733 VResetDiskUsage_r();
6735 #ifndef AFS_DEMAND_ATTACH_FS
6736 if (++FifteenMinuteCounter == 3) {
6737 FifteenMinuteCounter = 0;
6740 #endif /* !AFS_DEMAND_ATTACH_FS */
6752 /***************************************************/
6753 /* Volume Update List routines */
6754 /***************************************************/
6756 /* The number of minutes that a volume hasn't been updated before the
6757 * "Dont salvage" flag in the volume header will be turned on */
6758 #define SALVAGE_INTERVAL (10*60)
6763 * volume update list functionality has been moved into the VLRU
6764 * the DONT_SALVAGE flag is now set during VLRU demotion
6767 #ifndef AFS_DEMAND_ATTACH_FS
6768 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6769 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6770 static int updateSize = 0; /* number of entries possible */
6771 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6772 #endif /* !AFS_DEMAND_ATTACH_FS */
6775 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6778 vp->updateTime = FT_ApproxTime();
6779 if (V_dontSalvage(vp) == 0)
6781 V_dontSalvage(vp) = 0;
6782 VSyncVolume_r(ec, vp, 0);
6783 #ifdef AFS_DEMAND_ATTACH_FS
6784 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6785 #else /* !AFS_DEMAND_ATTACH_FS */
6788 if (UpdateList == NULL) {
6789 updateSize = UPDATE_LIST_SIZE;
6790 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6792 if (nUpdatedVolumes == updateSize) {
6794 if (updateSize > 524288) {
6795 Log("warning: there is likely a bug in the volume update scanner\n");
6799 (VolumeId *) realloc(UpdateList,
6800 sizeof(VolumeId) * updateSize);
6803 osi_Assert(UpdateList != NULL);
6804 UpdateList[nUpdatedVolumes++] = V_id(vp);
6805 #endif /* !AFS_DEMAND_ATTACH_FS */
6808 #ifndef AFS_DEMAND_ATTACH_FS
6810 VScanUpdateList(void)
6815 afs_uint32 now = FT_ApproxTime();
6816 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6817 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6819 UpdateList[i - gap] = UpdateList[i];
6821 /* XXX this routine needlessly messes up the Volume LRU by
6822 * breaking the LRU temporal-locality assumptions.....
6823 * we should use a special volume header allocator here */
6824 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6827 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6828 V_dontSalvage(vp) = DONT_SALVAGE;
6829 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6837 #ifndef AFS_PTHREAD_ENV
6839 #endif /* !AFS_PTHREAD_ENV */
6841 nUpdatedVolumes -= gap;
6843 #endif /* !AFS_DEMAND_ATTACH_FS */
6846 /***************************************************/
6847 /* Volume LRU routines */
6848 /***************************************************/
6853 * with demand attach fs, we attempt to soft detach(1)
6854 * volumes which have not been accessed in a long time
6855 * in order to speed up fileserver shutdown
6857 * (1) by soft detach we mean a process very similar
6858 * to VOffline, except the final state of the
6859 * Volume will be VOL_STATE_PREATTACHED, instead
6860 * of the usual VOL_STATE_UNATTACHED
6862 #ifdef AFS_DEMAND_ATTACH_FS
6864 /* implementation is reminiscent of a generational GC
6866 * queue 0 is newly attached volumes. this queue is
6867 * sorted by attach timestamp
6869 * queue 1 is volumes that have been around a bit
6870 * longer than queue 0. this queue is sorted by
6873 * queue 2 is volumes tha have been around the longest.
6874 * this queue is unsorted
6876 * queue 3 is volumes that have been marked as
6877 * candidates for soft detachment. this queue is
6880 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6881 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6884 * definition of a VLRU queue.
6887 volatile struct rx_queue q;
6894 * main VLRU data structure.
6897 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6900 /** time interval (in seconds) between promotion passes for
6901 * each young generation queue. */
6902 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6904 /** time interval (in seconds) between soft detach candidate
6905 * scans for each generation queue.
6907 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6908 * we perform a soft detach pass. */
6909 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6911 /* scheduler state */
6912 int next_idx; /**< next queue to receive attention */
6913 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6914 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6916 int scanner_state; /**< state of scanner thread */
6917 pthread_cond_t cv; /**< state transition CV */
6920 /** global VLRU state */
6921 static struct VLRU volume_LRU;
6924 * defined states for VLRU scanner thread.
6927 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6928 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6929 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6930 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6931 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6932 } vlru_thread_state_t;
6934 /* vlru disk data header stuff */
6935 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6936 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6938 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6939 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6942 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6943 * soft detachment. */
6944 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6946 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6947 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6949 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6950 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6952 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6953 static afs_uint32 VLRU_enabled = 1;
6955 /* queue synchronization routines */
6956 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6957 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6958 static void VLRU_Wait_r(struct VLRU_q * q);
6961 * set VLRU subsystem tunable parameters.
6963 * @param[in] option tunable option to modify
6964 * @param[in] val new value for tunable parameter
6966 * @pre @c VInitVolumePackage2 has not yet been called.
6968 * @post tunable parameter is modified
6972 * @note valid option parameters are:
6973 * @arg @c VLRU_SET_THRESH
6974 * set the period of inactivity after which
6975 * volumes are eligible for soft detachment
6976 * @arg @c VLRU_SET_INTERVAL
6977 * set the time interval between calls
6978 * to the volume LRU "garbage collector"
6979 * @arg @c VLRU_SET_MAX
6980 * set the max number of volumes to deallocate
6984 VLRU_SetOptions(int option, afs_uint32 val)
6986 if (option == VLRU_SET_THRESH) {
6987 VLRU_offline_thresh = val;
6988 } else if (option == VLRU_SET_INTERVAL) {
6989 VLRU_offline_interval = val;
6990 } else if (option == VLRU_SET_MAX) {
6991 VLRU_offline_max = val;
6992 } else if (option == VLRU_SET_ENABLED) {
6995 VLRU_ComputeConstants();
6999 * compute VLRU internal timing parameters.
7001 * @post VLRU scanner thread internal timing parameters are computed
7003 * @note computes internal timing parameters based upon user-modifiable
7004 * tunable parameters.
7008 * @internal volume package internal use only.
7011 VLRU_ComputeConstants(void)
7013 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7015 /* compute the candidate scan interval */
7016 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7018 /* compute the promotion intervals */
7019 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7020 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7023 /* compute the gen 0 scan interval */
7024 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7026 /* compute the gen 0 scan interval */
7027 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7032 * initialize VLRU subsystem.
7034 * @pre this function has not yet been called
7036 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7040 * @internal volume package internal use only.
7046 pthread_attr_t attrs;
7049 if (!VLRU_enabled) {
7050 Log("VLRU: disabled\n");
7054 /* initialize each of the VLRU queues */
7055 for (i = 0; i < VLRU_QUEUES; i++) {
7056 queue_Init(&volume_LRU.q[i]);
7057 volume_LRU.q[i].len = 0;
7058 volume_LRU.q[i].busy = 0;
7059 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7062 /* setup the timing constants */
7063 VLRU_ComputeConstants();
7065 /* XXX put inside LogLevel check? */
7066 Log("VLRU: starting scanner with the following configuration parameters:\n");
7067 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7068 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7069 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7070 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7071 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7072 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7074 /* start up the VLRU scanner */
7075 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7076 if (programType == fileServer) {
7077 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7078 osi_Assert(pthread_attr_init(&attrs) == 0);
7079 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7080 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7085 * initialize the VLRU-related fields of a newly allocated volume object.
7087 * @param[in] vp pointer to volume object
7090 * @arg @c VOL_LOCK is held.
7091 * @arg volume object is not on a VLRU queue.
7093 * @post VLRU fields are initialized to indicate that volume object is not
7094 * currently registered with the VLRU subsystem
7098 * @internal volume package interal use only.
7101 VLRU_Init_Node_r(Volume * vp)
7106 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7107 vp->vlru.idx = VLRU_QUEUE_INVALID;
7111 * add a volume object to a VLRU queue.
7113 * @param[in] vp pointer to volume object
7116 * @arg @c VOL_LOCK is held.
7117 * @arg caller MUST hold a lightweight ref on @p vp.
7118 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7120 * @post the volume object is added to the appropriate VLRU queue
7122 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7123 * then the volume is added to that queue. Otherwise, the value
7124 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7125 * volume is added to the NEW generation queue.
7127 * @note @c VOL_LOCK may be dropped internally
7129 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7130 * during the add operation, and is restored to the previous
7131 * state prior to return.
7135 * @internal volume package internal use only.
7138 VLRU_Add_r(Volume * vp)
7141 VolState state_save;
7146 if (queue_IsOnQueue(&vp->vlru))
7149 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7152 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7153 idx = VLRU_QUEUE_NEW;
7156 VLRU_Wait_r(&volume_LRU.q[idx]);
7158 /* repeat check since VLRU_Wait_r may have dropped
7160 if (queue_IsNotOnQueue(&vp->vlru)) {
7162 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7163 volume_LRU.q[idx].len++;
7164 V_attachFlags(vp) |= VOL_ON_VLRU;
7165 vp->stats.last_promote = FT_ApproxTime();
7168 VChangeState_r(vp, state_save);
7172 * delete a volume object from a VLRU queue.
7174 * @param[in] vp pointer to volume object
7177 * @arg @c VOL_LOCK is held.
7178 * @arg caller MUST hold a lightweight ref on @p vp.
7179 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7181 * @post volume object is removed from the VLRU queue
7183 * @note @c VOL_LOCK may be dropped internally
7187 * @todo We should probably set volume state to something exlcusive
7188 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7190 * @internal volume package internal use only.
7193 VLRU_Delete_r(Volume * vp)
7200 if (queue_IsNotOnQueue(&vp->vlru))
7206 if (idx == VLRU_QUEUE_INVALID)
7208 VLRU_Wait_r(&volume_LRU.q[idx]);
7209 } while (idx != vp->vlru.idx);
7211 /* now remove from the VLRU and update
7212 * the appropriate counter */
7213 queue_Remove(&vp->vlru);
7214 volume_LRU.q[idx].len--;
7215 vp->vlru.idx = VLRU_QUEUE_INVALID;
7216 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7220 * tell the VLRU subsystem that a volume was just accessed.
7222 * @param[in] vp pointer to volume object
7225 * @arg @c VOL_LOCK is held
7226 * @arg caller MUST hold a lightweight ref on @p vp
7227 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7229 * @post volume VLRU access statistics are updated. If the volume was on
7230 * the VLRU soft detach candidate queue, it is moved to the NEW
7233 * @note @c VOL_LOCK may be dropped internally
7237 * @internal volume package internal use only.
7240 VLRU_UpdateAccess_r(Volume * vp)
7242 Volume * rvp = NULL;
7247 if (queue_IsNotOnQueue(&vp->vlru))
7250 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7252 /* update the access timestamp */
7253 vp->stats.last_get = FT_ApproxTime();
7256 * if the volume is on the soft detach candidate
7257 * list, we need to safely move it back to a
7258 * regular generation. this has to be done
7259 * carefully so we don't race against the scanner
7263 /* if this volume is on the soft detach candidate queue,
7264 * then grab exclusive access to the necessary queues */
7265 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7267 VCreateReservation_r(rvp);
7269 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7270 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7271 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7272 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7275 /* make sure multiple threads don't race to update */
7276 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7277 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7281 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7282 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7283 VCancelReservation_r(rvp);
7288 * switch a volume between two VLRU queues.
7290 * @param[in] vp pointer to volume object
7291 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7292 * @param[in] append controls whether the volume will be appended or
7293 * prepended to the queue. A nonzero value means it will
7294 * be appended; zero means it will be prepended.
7296 * @pre The new (and old, if applicable) queue(s) must either be owned
7297 * exclusively by the calling thread for asynchronous manipulation,
7298 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7299 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7300 * for further details of the queue asynchronous processing mechanism.
7302 * @post If the volume object was already on a VLRU queue, it is
7303 * removed from the queue. Depending on the value of the append
7304 * parameter, the volume object is either appended or prepended
7305 * to the VLRU queue referenced by the new_idx parameter.
7309 * @see VLRU_BeginExclusive_r
7310 * @see VLRU_EndExclusive_r
7313 * @internal volume package internal use only.
7316 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7318 if (queue_IsNotOnQueue(&vp->vlru))
7321 queue_Remove(&vp->vlru);
7322 volume_LRU.q[vp->vlru.idx].len--;
7324 /* put the volume back on the correct generational queue */
7326 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7328 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7331 volume_LRU.q[new_idx].len++;
7332 vp->vlru.idx = new_idx;
7336 * VLRU background thread.
7338 * The VLRU Scanner Thread is responsible for periodically scanning through
7339 * each VLRU queue looking for volumes which should be moved to another
7340 * queue, or soft detached.
7342 * @param[in] args unused thread arguments parameter
7344 * @return unused thread return value
7345 * @retval NULL always
7347 * @internal volume package internal use only.
7350 VLRU_ScannerThread(void * args)
7352 afs_uint32 now, min_delay, delay;
7353 int i, min_idx, min_op, overdue, state;
7355 /* set t=0 for promotion cycle to be
7356 * fileserver startup */
7357 now = FT_ApproxTime();
7358 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7359 volume_LRU.last_promotion[i] = now;
7362 /* don't start the scanner until VLRU_offline_thresh
7363 * plus a small delay for VInitVolumePackage2 to finish
7366 sleep(VLRU_offline_thresh + 60);
7368 /* set t=0 for scan cycle to be now */
7369 now = FT_ApproxTime();
7370 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7371 volume_LRU.last_scan[i] = now;
7375 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7376 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7379 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7380 /* check to see if we've been asked to pause */
7381 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7382 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7383 CV_BROADCAST(&volume_LRU.cv);
7385 VOL_CV_WAIT(&volume_LRU.cv);
7386 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7389 /* scheduling can happen outside the glock */
7392 /* figure out what is next on the schedule */
7394 /* figure out a potential schedule for the new generation first */
7396 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7399 if (min_delay > volume_LRU.scan_interval[0]) {
7400 /* unsigned overflow -- we're overdue to run this scan */
7405 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7407 i = VLRU_QUEUE_CANDIDATE;
7408 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7409 if (delay < min_delay) {
7413 if (delay > volume_LRU.scan_interval[i]) {
7414 /* unsigned overflow -- we're overdue to run this scan */
7421 /* if we're still not overdue for something, figure out schedules for promotions */
7422 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7423 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7424 if (delay < min_delay) {
7429 if (delay > volume_LRU.promotion_interval[i]) {
7430 /* unsigned overflow -- we're overdue to run this promotion */
7439 /* sleep as needed */
7444 /* do whatever is next */
7447 VLRU_Promote_r(min_idx);
7448 VLRU_Demote_r(min_idx+1);
7450 VLRU_Scan_r(min_idx);
7452 now = FT_ApproxTime();
7455 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7457 /* signal that scanner is down */
7458 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7459 CV_BROADCAST(&volume_LRU.cv);
7465 * promote volumes from one VLRU generation to the next.
7467 * This routine scans a VLRU generation looking for volumes which are
7468 * eligible to be promoted to the next generation. All volumes which
7469 * meet the eligibility requirement are promoted.
7471 * Promotion eligibility is based upon meeting both of the following
7474 * @arg The volume has been accessed since the last promotion:
7475 * @c (vp->stats.last_get >= vp->stats.last_promote)
7476 * @arg The last promotion occurred at least
7477 * @c volume_LRU.promotion_interval[idx] seconds ago
7479 * As a performance optimization, promotions are "globbed". In other
7480 * words, we promote arbitrarily large contiguous sublists of elements
7483 * @param[in] idx VLRU queue index to scan
7487 * @internal VLRU internal use only.
7490 VLRU_Promote_r(int idx)
7492 int len, chaining, promote;
7493 afs_uint32 now, thresh;
7494 struct rx_queue *qp, *nqp;
7495 Volume * vp, *start = NULL, *end = NULL;
7497 /* get exclusive access to two chains, and drop the glock */
7498 VLRU_Wait_r(&volume_LRU.q[idx]);
7499 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7500 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7501 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7504 thresh = volume_LRU.promotion_interval[idx];
7505 now = FT_ApproxTime();
7508 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7509 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7510 promote = (((vp->stats.last_promote + thresh) <= now) &&
7511 (vp->stats.last_get >= vp->stats.last_promote));
7519 /* promote and prepend chain */
7520 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7534 /* promote and prepend */
7535 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7539 volume_LRU.q[idx].len -= len;
7540 volume_LRU.q[idx+1].len += len;
7543 /* release exclusive access to the two chains */
7545 volume_LRU.last_promotion[idx] = now;
7546 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7547 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7550 /* run the demotions */
7552 VLRU_Demote_r(int idx)
7555 int len, chaining, demote;
7556 afs_uint32 now, thresh;
7557 struct rx_queue *qp, *nqp;
7558 Volume * vp, *start = NULL, *end = NULL;
7559 Volume ** salv_flag_vec = NULL;
7560 int salv_vec_offset = 0;
7562 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7564 /* get exclusive access to two chains, and drop the glock */
7565 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7566 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7567 VLRU_Wait_r(&volume_LRU.q[idx]);
7568 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7571 /* no big deal if this allocation fails */
7572 if (volume_LRU.q[idx].len) {
7573 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7576 now = FT_ApproxTime();
7577 thresh = volume_LRU.promotion_interval[idx-1];
7580 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7581 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7582 demote = (((vp->stats.last_promote + thresh) <= now) &&
7583 (vp->stats.last_get < (now - thresh)));
7585 /* we now do volume update list DONT_SALVAGE flag setting during
7586 * demotion passes */
7587 if (salv_flag_vec &&
7588 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7590 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7591 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7592 salv_flag_vec[salv_vec_offset++] = vp;
7593 VCreateReservation_r(vp);
7602 /* demote and append chain */
7603 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7617 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7621 volume_LRU.q[idx].len -= len;
7622 volume_LRU.q[idx-1].len += len;
7625 /* release exclusive access to the two chains */
7627 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7628 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7630 /* now go back and set the DONT_SALVAGE flags as appropriate */
7631 if (salv_flag_vec) {
7633 for (i = 0; i < salv_vec_offset; i++) {
7634 vp = salv_flag_vec[i];
7635 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7636 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7637 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7640 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7641 V_dontSalvage(vp) = DONT_SALVAGE;
7642 VUpdateVolume_r(&ec, vp, 0);
7646 VCancelReservation_r(vp);
7648 free(salv_flag_vec);
7652 /* run a pass of the VLRU GC scanner */
7654 VLRU_Scan_r(int idx)
7656 afs_uint32 now, thresh;
7657 struct rx_queue *qp, *nqp;
7661 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7663 /* gain exclusive access to the idx VLRU */
7664 VLRU_Wait_r(&volume_LRU.q[idx]);
7665 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7667 if (idx != VLRU_QUEUE_CANDIDATE) {
7668 /* gain exclusive access to the candidate VLRU */
7669 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7670 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7673 now = FT_ApproxTime();
7674 thresh = now - VLRU_offline_thresh;
7676 /* perform candidate selection and soft detaching */
7677 if (idx == VLRU_QUEUE_CANDIDATE) {
7678 /* soft detach some volumes from the candidate pool */
7682 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7683 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7684 if (i >= VLRU_offline_max) {
7687 /* check timestamp to see if it's a candidate for soft detaching */
7688 if (vp->stats.last_get <= thresh) {
7690 if (VCheckSoftDetach(vp, thresh))
7696 /* scan for volumes to become soft detach candidates */
7697 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7698 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7700 /* check timestamp to see if it's a candidate for soft detaching */
7701 if (vp->stats.last_get <= thresh) {
7702 VCheckSoftDetachCandidate(vp, thresh);
7705 if (!(i&0x7f)) { /* lock coarsening optimization */
7713 /* relinquish exclusive access to the VLRU chains */
7717 volume_LRU.last_scan[idx] = now;
7718 if (idx != VLRU_QUEUE_CANDIDATE) {
7719 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7721 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7724 /* check whether volume is safe to soft detach
7725 * caller MUST NOT hold a ref count on vp */
7727 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7731 if (vp->nUsers || vp->nWaiters)
7734 if (vp->stats.last_get <= thresh) {
7735 ret = VSoftDetachVolume_r(vp, thresh);
7741 /* check whether volume should be made a
7742 * soft detach candidate */
7744 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7747 if (vp->nUsers || vp->nWaiters)
7752 osi_Assert(idx == VLRU_QUEUE_NEW);
7754 if (vp->stats.last_get <= thresh) {
7755 /* move to candidate pool */
7756 queue_Remove(&vp->vlru);
7757 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7758 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7759 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7760 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7768 /* begin exclusive access on VLRU */
7770 VLRU_BeginExclusive_r(struct VLRU_q * q)
7772 osi_Assert(q->busy == 0);
7776 /* end exclusive access on VLRU */
7778 VLRU_EndExclusive_r(struct VLRU_q * q)
7780 osi_Assert(q->busy);
7782 CV_BROADCAST(&q->cv);
7785 /* wait for another thread to end exclusive access on VLRU */
7787 VLRU_Wait_r(struct VLRU_q * q)
7790 VOL_CV_WAIT(&q->cv);
7795 * volume soft detach
7797 * caller MUST NOT hold a ref count on vp */
7799 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7804 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7806 ts_save = vp->stats.last_get;
7807 if (ts_save > thresh)
7810 if (vp->nUsers || vp->nWaiters)
7813 if (VIsExclusiveState(V_attachState(vp))) {
7817 switch (V_attachState(vp)) {
7818 case VOL_STATE_UNATTACHED:
7819 case VOL_STATE_PREATTACHED:
7820 case VOL_STATE_ERROR:
7821 case VOL_STATE_GOING_OFFLINE:
7822 case VOL_STATE_SHUTTING_DOWN:
7823 case VOL_STATE_SALVAGING:
7824 case VOL_STATE_DELETED:
7825 volume_LRU.q[vp->vlru.idx].len--;
7827 /* create and cancel a reservation to
7828 * give the volume an opportunity to
7830 VCreateReservation_r(vp);
7831 queue_Remove(&vp->vlru);
7832 vp->vlru.idx = VLRU_QUEUE_INVALID;
7833 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7834 VCancelReservation_r(vp);
7840 /* hold the volume and take it offline.
7841 * no need for reservations, as VHold_r
7842 * takes care of that internally. */
7843 if (VHold_r(vp) == 0) {
7844 /* vhold drops the glock, so now we should
7845 * check to make sure we aren't racing against
7846 * other threads. if we are racing, offlining vp
7847 * would be wasteful, and block the scanner for a while
7851 (vp->shuttingDown) ||
7852 (vp->goingOffline) ||
7853 (vp->stats.last_get != ts_save)) {
7854 /* looks like we're racing someone else. bail */
7858 /* pull it off the VLRU */
7859 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7860 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7861 queue_Remove(&vp->vlru);
7862 vp->vlru.idx = VLRU_QUEUE_INVALID;
7863 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7865 /* take if offline */
7866 VOffline_r(vp, "volume has been soft detached");
7868 /* invalidate the volume header cache */
7869 FreeVolumeHeader(vp);
7872 IncUInt64(&VStats.soft_detaches);
7873 vp->stats.soft_detaches++;
7875 /* put in pre-attached state so demand
7876 * attacher can work on it */
7877 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7883 #endif /* AFS_DEMAND_ATTACH_FS */
7886 /***************************************************/
7887 /* Volume Header Cache routines */
7888 /***************************************************/
7891 * volume header cache.
7893 struct volume_hdr_LRU_t volume_hdr_LRU;
7896 * initialize the volume header cache.
7898 * @param[in] howMany number of header cache entries to preallocate
7900 * @pre VOL_LOCK held. Function has never been called before.
7902 * @post howMany cache entries are allocated, initialized, and added
7903 * to the LRU list. Header cache statistics are initialized.
7905 * @note only applicable to fileServer program type. Should only be
7906 * called once during volume package initialization.
7908 * @internal volume package internal use only.
7911 VInitVolumeHeaderCache(afs_uint32 howMany)
7913 struct volHeader *hp;
7914 if (programType != fileServer)
7916 queue_Init(&volume_hdr_LRU);
7917 volume_hdr_LRU.stats.free = 0;
7918 volume_hdr_LRU.stats.used = howMany;
7919 volume_hdr_LRU.stats.attached = 0;
7920 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7921 osi_Assert(hp != NULL);
7924 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7925 * to ensure they have the right values
7927 ReleaseVolumeHeader(hp++);
7931 * get a volume header and attach it to the volume object.
7933 * @param[in] vp pointer to volume object
7935 * @return cache entry status
7936 * @retval 0 volume header was newly attached; cache data is invalid
7937 * @retval 1 volume header was previously attached; cache data is valid
7939 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7941 * @post volume header attached to volume object. if necessary, header cache
7942 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7944 * @note VOL_LOCK may be dropped
7946 * @warning this interface does not load header data from disk. it merely
7947 * attaches a header object to the volume object, and may sync the old
7948 * header cache data out to disk in the process.
7950 * @internal volume package internal use only.
7953 GetVolumeHeader(Volume * vp)
7956 struct volHeader *hd;
7958 static int everLogged = 0;
7960 #ifdef AFS_DEMAND_ATTACH_FS
7961 VolState vp_save = 0, back_save = 0;
7963 /* XXX debug 9/19/05 we've apparently got
7964 * a ref counting bug somewhere that's
7965 * breaking the nUsers == 0 => header on LRU
7967 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7968 Log("nUsers == 0, but header not on LRU\n");
7973 old = (vp->header != NULL); /* old == volume already has a header */
7975 if (programType != fileServer) {
7976 /* for volume utilities, we allocate volHeaders as needed */
7978 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7979 osi_Assert(hd != NULL);
7982 #ifdef AFS_DEMAND_ATTACH_FS
7983 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7987 /* for the fileserver, we keep a volume header cache */
7989 /* the header we previously dropped in the lru is
7990 * still available. pull it off the lru and return */
7993 osi_Assert(hd->back == vp);
7994 #ifdef AFS_DEMAND_ATTACH_FS
7995 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7998 /* we need to grab a new element off the LRU */
7999 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8000 /* grab an element and pull off of LRU */
8001 hd = queue_First(&volume_hdr_LRU, volHeader);
8004 /* LRU is empty, so allocate a new volHeader
8005 * this is probably indicative of a leak, so let the user know */
8006 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
8007 osi_Assert(hd != NULL);
8009 Log("****Allocated more volume headers, probably leak****\n");
8012 volume_hdr_LRU.stats.free++;
8015 /* this header used to belong to someone else.
8016 * we'll need to check if the header needs to
8017 * be sync'd out to disk */
8019 #ifdef AFS_DEMAND_ATTACH_FS
8020 /* if hd->back were in an exclusive state, then
8021 * its volHeader would not be on the LRU... */
8022 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8025 if (hd->diskstuff.inUse) {
8026 /* volume was in use, so we'll need to sync
8027 * its header to disk */
8029 #ifdef AFS_DEMAND_ATTACH_FS
8030 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8031 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8032 VCreateReservation_r(hd->back);
8036 WriteVolumeHeader_r(&error, hd->back);
8037 /* Ignore errors; catch them later */
8039 #ifdef AFS_DEMAND_ATTACH_FS
8044 hd->back->header = NULL;
8045 #ifdef AFS_DEMAND_ATTACH_FS
8046 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8048 if (hd->diskstuff.inUse) {
8049 VChangeState_r(hd->back, back_save);
8050 VCancelReservation_r(hd->back);
8051 VChangeState_r(vp, vp_save);
8055 volume_hdr_LRU.stats.attached++;
8059 #ifdef AFS_DEMAND_ATTACH_FS
8060 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8063 volume_hdr_LRU.stats.free--;
8064 volume_hdr_LRU.stats.used++;
8066 IncUInt64(&VStats.hdr_gets);
8067 #ifdef AFS_DEMAND_ATTACH_FS
8068 IncUInt64(&vp->stats.hdr_gets);
8069 vp->stats.last_hdr_get = FT_ApproxTime();
8076 * make sure volume header is attached and contains valid cache data.
8078 * @param[out] ec outbound error code
8079 * @param[in] vp pointer to volume object
8081 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8083 * @post header cache entry attached, and loaded with valid data, or
8084 * *ec is nonzero, and the header is released back into the LRU.
8086 * @internal volume package internal use only.
8089 LoadVolumeHeader(Error * ec, Volume * vp)
8091 #ifdef AFS_DEMAND_ATTACH_FS
8092 VolState state_save;
8096 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8097 IncUInt64(&VStats.hdr_loads);
8098 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8101 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8102 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8104 IncUInt64(&vp->stats.hdr_loads);
8105 now = FT_ApproxTime();
8109 V_attachFlags(vp) |= VOL_HDR_LOADED;
8110 vp->stats.last_hdr_load = now;
8112 VChangeState_r(vp, state_save);
8114 #else /* AFS_DEMAND_ATTACH_FS */
8116 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8117 IncUInt64(&VStats.hdr_loads);
8119 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8120 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8123 #endif /* AFS_DEMAND_ATTACH_FS */
8125 /* maintain (nUsers==0) => header in LRU invariant */
8126 FreeVolumeHeader(vp);
8131 * release a header cache entry back into the LRU list.
8133 * @param[in] hd pointer to volume header cache object
8135 * @pre VOL_LOCK held.
8137 * @post header cache object appended onto end of LRU list.
8139 * @note only applicable to fileServer program type.
8141 * @note used to place a header cache entry back into the
8142 * LRU pool without invalidating it as a cache entry.
8144 * @internal volume package internal use only.
8147 ReleaseVolumeHeader(struct volHeader *hd)
8149 if (programType != fileServer)
8151 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8153 queue_Append(&volume_hdr_LRU, hd);
8154 #ifdef AFS_DEMAND_ATTACH_FS
8156 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8159 volume_hdr_LRU.stats.free++;
8160 volume_hdr_LRU.stats.used--;
8164 * free/invalidate a volume header cache entry.
8166 * @param[in] vp pointer to volume object
8168 * @pre VOL_LOCK is held.
8170 * @post For fileserver, header cache entry is returned to LRU, and it is
8171 * invalidated as a cache entry. For volume utilities, the header
8172 * cache entry is freed.
8174 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8175 * whenever it is necessary to invalidate the header cache entry.
8177 * @see ReleaseVolumeHeader
8179 * @internal volume package internal use only.
8182 FreeVolumeHeader(Volume * vp)
8184 struct volHeader *hd = vp->header;
8187 if (programType == fileServer) {
8188 ReleaseVolumeHeader(hd);
8193 #ifdef AFS_DEMAND_ATTACH_FS
8194 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8196 volume_hdr_LRU.stats.attached--;
8201 /***************************************************/
8202 /* Volume Hash Table routines */
8203 /***************************************************/
8206 * set size of volume object hash table.
8208 * @param[in] logsize log(2) of desired hash table size
8210 * @return operation status
8212 * @retval -1 failure
8214 * @pre MUST be called prior to VInitVolumePackage2
8216 * @post Volume Hash Table will have 2^logsize buckets
8219 VSetVolHashSize(int logsize)
8221 /* 64 to 268435456 hash buckets seems like a reasonable range */
8222 if ((logsize < 6 ) || (logsize > 28)) {
8227 VolumeHashTable.Size = 1 << logsize;
8228 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8230 /* we can't yet support runtime modification of this
8231 * parameter. we'll need a configuration rwlock to
8232 * make runtime modification feasible.... */
8239 * initialize dynamic data structures for volume hash table.
8241 * @post hash table is allocated, and fields are initialized.
8243 * @internal volume package internal use only.
8246 VInitVolumeHash(void)
8250 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8251 sizeof(VolumeHashChainHead));
8252 osi_Assert(VolumeHashTable.Table != NULL);
8254 for (i=0; i < VolumeHashTable.Size; i++) {
8255 queue_Init(&VolumeHashTable.Table[i]);
8256 #ifdef AFS_DEMAND_ATTACH_FS
8257 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8258 #endif /* AFS_DEMAND_ATTACH_FS */
8263 * add a volume object to the hash table.
8265 * @param[in] vp pointer to volume object
8266 * @param[in] hashid hash of volume id
8268 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8271 * @post volume is added to hash chain.
8273 * @internal volume package internal use only.
8275 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8276 * asynchronous hash chain reordering to finish.
8279 AddVolumeToHashTable(Volume * vp, int hashid)
8281 VolumeHashChainHead * head;
8283 if (queue_IsOnQueue(vp))
8286 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8288 #ifdef AFS_DEMAND_ATTACH_FS
8289 /* wait for the hash chain to become available */
8292 V_attachFlags(vp) |= VOL_IN_HASH;
8293 vp->chainCacheCheck = ++head->cacheCheck;
8294 #endif /* AFS_DEMAND_ATTACH_FS */
8297 vp->hashid = hashid;
8298 queue_Append(head, vp);
8299 vp->vnodeHashOffset = VolumeHashOffset_r();
8303 * delete a volume object from the hash table.
8305 * @param[in] vp pointer to volume object
8307 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8310 * @post volume is removed from hash chain.
8312 * @internal volume package internal use only.
8314 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8315 * asynchronous hash chain reordering to finish.
8318 DeleteVolumeFromHashTable(Volume * vp)
8320 VolumeHashChainHead * head;
8322 if (!queue_IsOnQueue(vp))
8325 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8327 #ifdef AFS_DEMAND_ATTACH_FS
8328 /* wait for the hash chain to become available */
8331 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8333 #endif /* AFS_DEMAND_ATTACH_FS */
8337 /* do NOT reset hashid to zero, as the online
8338 * salvager package may need to know the volume id
8339 * after the volume is removed from the hash */
8343 * lookup a volume object in the hash table given a volume id.
8345 * @param[out] ec error code return
8346 * @param[in] volumeId volume id
8347 * @param[in] hint volume object which we believe could be the correct
8350 * @return volume object pointer
8351 * @retval NULL no such volume id is registered with the hash table.
8353 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8356 * @post volume object with the given id is returned. volume object and
8357 * hash chain access statistics are updated. hash chain may have
8360 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8361 * asynchronous hash chain reordering operation to finish, or
8362 * in order for us to perform an asynchronous chain reordering.
8364 * @note Hash chain reorderings occur when the access count for the
8365 * volume object being looked up exceeds the sum of the previous
8366 * node's (the node ahead of it in the hash chain linked list)
8367 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8369 * @note For DAFS, the hint parameter allows us to short-circuit if the
8370 * cacheCheck fields match between the hash chain head and the
8371 * hint volume object.
8374 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8378 #ifdef AFS_DEMAND_ATTACH_FS
8381 VolumeHashChainHead * head;
8384 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8386 #ifdef AFS_DEMAND_ATTACH_FS
8387 /* wait for the hash chain to become available */
8390 /* check to see if we can short circuit without walking the hash chain */
8391 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8392 IncUInt64(&hint->stats.hash_short_circuits);
8395 #endif /* AFS_DEMAND_ATTACH_FS */
8397 /* someday we need to either do per-chain locks, RWlocks,
8398 * or both for volhash access.
8399 * (and move to a data structure with better cache locality) */
8401 /* search the chain for this volume id */
8402 for(queue_Scan(head, vp, np, Volume)) {
8404 if ((vp->hashid == volumeId)) {
8409 if (queue_IsEnd(head, vp)) {
8413 #ifdef AFS_DEMAND_ATTACH_FS
8414 /* update hash chain statistics */
8417 FillInt64(lks, 0, looks);
8418 AddUInt64(head->looks, lks, &head->looks);
8419 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8420 IncUInt64(&head->gets);
8425 IncUInt64(&vp->stats.hash_lookups);
8427 /* for demand attach fileserver, we permit occasional hash chain reordering
8428 * so that frequently looked up volumes move towards the head of the chain */
8429 pp = queue_Prev(vp, Volume);
8430 if (!queue_IsEnd(head, pp)) {
8431 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8432 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8433 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8434 VReorderHash_r(head, pp, vp);
8438 /* update the short-circuit cache check */
8439 vp->chainCacheCheck = head->cacheCheck;
8441 #endif /* AFS_DEMAND_ATTACH_FS */
8446 #ifdef AFS_DEMAND_ATTACH_FS
8447 /* perform volume hash chain reordering.
8449 * advance a subchain beginning at vp ahead of
8450 * the adjacent subchain ending at pp */
8452 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8454 Volume *tp, *np, *lp;
8455 afs_uint64 move_thresh;
8457 /* this should never be called if the chain is already busy, so
8458 * no need to wait for other exclusive chain ops to finish */
8460 /* this is a rather heavy set of operations,
8461 * so let's set the chain busy flag and drop
8463 VHashBeginExclusive_r(head);
8466 /* scan forward in the chain from vp looking for the last element
8467 * in the chain we want to advance */
8468 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8469 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8470 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8471 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8475 lp = queue_Prev(tp, Volume);
8477 /* scan backwards from pp to determine where to splice and
8478 * insert the subchain we're advancing */
8479 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8480 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8484 tp = queue_Next(tp, Volume);
8486 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8487 queue_MoveChainBefore(tp,vp,lp);
8490 IncUInt64(&VStats.hash_reorders);
8492 IncUInt64(&head->reorders);
8494 /* wake up any threads waiting for the hash chain */
8495 VHashEndExclusive_r(head);
8499 /* demand-attach fs volume hash
8500 * asynchronous exclusive operations */
8503 * begin an asynchronous exclusive operation on a volume hash chain.
8505 * @param[in] head pointer to volume hash chain head object
8507 * @pre VOL_LOCK held. hash chain is quiescent.
8509 * @post hash chain marked busy.
8511 * @note this interface is used in conjunction with VHashEndExclusive_r and
8512 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8513 * volume hash chain. Its main use case is hash chain reordering, which
8514 * has the potential to be a highly latent operation.
8516 * @see VHashEndExclusive_r
8521 * @internal volume package internal use only.
8524 VHashBeginExclusive_r(VolumeHashChainHead * head)
8526 osi_Assert(head->busy == 0);
8531 * relinquish exclusive ownership of a volume hash chain.
8533 * @param[in] head pointer to volume hash chain head object
8535 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8537 * @post hash chain is marked quiescent. threads awaiting use of
8538 * chain are awakened.
8540 * @see VHashBeginExclusive_r
8545 * @internal volume package internal use only.
8548 VHashEndExclusive_r(VolumeHashChainHead * head)
8550 osi_Assert(head->busy);
8552 CV_BROADCAST(&head->chain_busy_cv);
8556 * wait for all asynchronous operations on a hash chain to complete.
8558 * @param[in] head pointer to volume hash chain head object
8560 * @pre VOL_LOCK held.
8562 * @post hash chain object is quiescent.
8564 * @see VHashBeginExclusive_r
8565 * @see VHashEndExclusive_r
8569 * @note This interface should be called before any attempt to
8570 * traverse the hash chain. It is permissible for a thread
8571 * to gain exclusive access to the chain, and then perform
8572 * latent operations on the chain asynchronously wrt the
8575 * @warning if waiting is necessary, VOL_LOCK is dropped
8577 * @internal volume package internal use only.
8580 VHashWait_r(VolumeHashChainHead * head)
8582 while (head->busy) {
8583 VOL_CV_WAIT(&head->chain_busy_cv);
8586 #endif /* AFS_DEMAND_ATTACH_FS */
8589 /***************************************************/
8590 /* Volume by Partition List routines */
8591 /***************************************************/
8594 * demand attach fileserver adds a
8595 * linked list of volumes to each
8596 * partition object, thus allowing
8597 * for quick enumeration of all
8598 * volumes on a partition
8601 #ifdef AFS_DEMAND_ATTACH_FS
8603 * add a volume to its disk partition VByPList.
8605 * @param[in] vp pointer to volume object
8607 * @pre either the disk partition VByPList is owned exclusively
8608 * by the calling thread, or the list is quiescent and
8611 * @post volume is added to disk partition VByPList
8615 * @warning it is the caller's responsibility to ensure list
8618 * @see VVByPListWait_r
8619 * @see VVByPListBeginExclusive_r
8620 * @see VVByPListEndExclusive_r
8622 * @internal volume package internal use only.
8625 AddVolumeToVByPList_r(Volume * vp)
8627 if (queue_IsNotOnQueue(&vp->vol_list)) {
8628 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8629 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8630 vp->partition->vol_list.len++;
8635 * delete a volume from its disk partition VByPList.
8637 * @param[in] vp pointer to volume object
8639 * @pre either the disk partition VByPList is owned exclusively
8640 * by the calling thread, or the list is quiescent and
8643 * @post volume is removed from the disk partition VByPList
8647 * @warning it is the caller's responsibility to ensure list
8650 * @see VVByPListWait_r
8651 * @see VVByPListBeginExclusive_r
8652 * @see VVByPListEndExclusive_r
8654 * @internal volume package internal use only.
8657 DeleteVolumeFromVByPList_r(Volume * vp)
8659 if (queue_IsOnQueue(&vp->vol_list)) {
8660 queue_Remove(&vp->vol_list);
8661 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8662 vp->partition->vol_list.len--;
8667 * begin an asynchronous exclusive operation on a VByPList.
8669 * @param[in] dp pointer to disk partition object
8671 * @pre VOL_LOCK held. VByPList is quiescent.
8673 * @post VByPList marked busy.
8675 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8676 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8679 * @see VVByPListEndExclusive_r
8680 * @see VVByPListWait_r
8684 * @internal volume package internal use only.
8686 /* take exclusive control over the list */
8688 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8690 osi_Assert(dp->vol_list.busy == 0);
8691 dp->vol_list.busy = 1;
8695 * relinquish exclusive ownership of a VByPList.
8697 * @param[in] dp pointer to disk partition object
8699 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8701 * @post VByPList is marked quiescent. threads awaiting use of
8702 * the list are awakened.
8704 * @see VVByPListBeginExclusive_r
8705 * @see VVByPListWait_r
8709 * @internal volume package internal use only.
8712 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8714 osi_Assert(dp->vol_list.busy);
8715 dp->vol_list.busy = 0;
8716 CV_BROADCAST(&dp->vol_list.cv);
8720 * wait for all asynchronous operations on a VByPList to complete.
8722 * @param[in] dp pointer to disk partition object
8724 * @pre VOL_LOCK is held.
8726 * @post disk partition's VByP list is quiescent
8730 * @note This interface should be called before any attempt to
8731 * traverse the VByPList. It is permissible for a thread
8732 * to gain exclusive access to the list, and then perform
8733 * latent operations on the list asynchronously wrt the
8736 * @warning if waiting is necessary, VOL_LOCK is dropped
8738 * @see VVByPListEndExclusive_r
8739 * @see VVByPListBeginExclusive_r
8741 * @internal volume package internal use only.
8744 VVByPListWait_r(struct DiskPartition64 * dp)
8746 while (dp->vol_list.busy) {
8747 VOL_CV_WAIT(&dp->vol_list.cv);
8750 #endif /* AFS_DEMAND_ATTACH_FS */
8752 /***************************************************/
8753 /* Volume Cache Statistics routines */
8754 /***************************************************/
8757 VPrintCacheStats_r(void)
8759 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8760 struct VnodeClassInfo *vcp;
8761 vcp = &VnodeClassInfo[vLarge];
8762 Log("Large vnode cache, %d entries, %d allocs, %d gets (%d reads), %d writes\n", vcp->cacheSize, vcp->allocs, vcp->gets, vcp->reads, vcp->writes);
8763 vcp = &VnodeClassInfo[vSmall];
8764 Log("Small vnode cache,%d entries, %d allocs, %d gets (%d reads), %d writes\n", vcp->cacheSize, vcp->allocs, vcp->gets, vcp->reads, vcp->writes);
8765 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8766 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8767 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8768 VStats.hdr_cache_size, get_lo, load_lo);
8772 VPrintCacheStats(void)
8775 VPrintCacheStats_r();
8779 #ifdef AFS_DEMAND_ATTACH_FS
8781 UInt64ToDouble(afs_uint64 * x)
8783 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8785 SplitInt64(*x, h, l);
8786 return (((double)h) * c32) + ((double) l);
8790 DoubleToPrintable(double x, char * buf, int len)
8792 static double billion = 1000000000.0;
8795 y[0] = (afs_uint32) (x / (billion * billion));
8796 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8797 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8800 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8802 snprintf(buf, len, "%d%09d", y[1], y[2]);
8804 snprintf(buf, len, "%d", y[2]);
8810 struct VLRUExtStatsEntry {
8814 struct VLRUExtStats {
8820 } queue_info[VLRU_QUEUE_INVALID];
8821 struct VLRUExtStatsEntry * vec;
8825 * add a 256-entry fudge factor onto the vector in case state changes
8826 * out from under us.
8828 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8831 * collect extended statistics for the VLRU subsystem.
8833 * @param[out] stats pointer to stats structure to be populated
8834 * @param[in] nvols number of volumes currently known to exist
8836 * @pre VOL_LOCK held
8838 * @post stats->vec allocated and populated
8840 * @return operation status
8845 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8847 afs_uint32 cur, idx, len;
8848 struct rx_queue * qp, * nqp;
8850 struct VLRUExtStatsEntry * vec;
8852 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8853 vec = stats->vec = calloc(len,
8854 sizeof(struct VLRUExtStatsEntry));
8860 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8861 VLRU_Wait_r(&volume_LRU.q[idx]);
8862 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8865 stats->queue_info[idx].start = cur;
8867 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8869 /* out of space in vec */
8872 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8873 vec[cur].volid = vp->hashid;
8877 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8880 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8888 #define ENUMTOSTRING(en) #en
8889 #define ENUMCASE(en) \
8890 case en: return ENUMTOSTRING(en)
8893 vlru_idx_to_string(int idx)
8896 ENUMCASE(VLRU_QUEUE_NEW);
8897 ENUMCASE(VLRU_QUEUE_MID);
8898 ENUMCASE(VLRU_QUEUE_OLD);
8899 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8900 ENUMCASE(VLRU_QUEUE_HELD);
8901 ENUMCASE(VLRU_QUEUE_INVALID);
8903 return "**UNKNOWN**";
8908 VPrintExtendedCacheStats_r(int flags)
8911 afs_uint32 vol_sum = 0;
8918 struct stats looks, gets, reorders, len;
8919 struct stats ch_looks, ch_gets, ch_reorders;
8921 VolumeHashChainHead *head;
8923 struct VLRUExtStats vlru_stats;
8925 /* zero out stats */
8926 memset(&looks, 0, sizeof(struct stats));
8927 memset(&gets, 0, sizeof(struct stats));
8928 memset(&reorders, 0, sizeof(struct stats));
8929 memset(&len, 0, sizeof(struct stats));
8930 memset(&ch_looks, 0, sizeof(struct stats));
8931 memset(&ch_gets, 0, sizeof(struct stats));
8932 memset(&ch_reorders, 0, sizeof(struct stats));
8934 for (i = 0; i < VolumeHashTable.Size; i++) {
8935 head = &VolumeHashTable.Table[i];
8938 VHashBeginExclusive_r(head);
8941 ch_looks.sum = UInt64ToDouble(&head->looks);
8942 ch_gets.sum = UInt64ToDouble(&head->gets);
8943 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8945 /* update global statistics */
8947 looks.sum += ch_looks.sum;
8948 gets.sum += ch_gets.sum;
8949 reorders.sum += ch_reorders.sum;
8950 len.sum += (double)head->len;
8951 vol_sum += head->len;
8954 len.min = (double) head->len;
8955 len.max = (double) head->len;
8956 looks.min = ch_looks.sum;
8957 looks.max = ch_looks.sum;
8958 gets.min = ch_gets.sum;
8959 gets.max = ch_gets.sum;
8960 reorders.min = ch_reorders.sum;
8961 reorders.max = ch_reorders.sum;
8963 if (((double)head->len) < len.min)
8964 len.min = (double) head->len;
8965 if (((double)head->len) > len.max)
8966 len.max = (double) head->len;
8967 if (ch_looks.sum < looks.min)
8968 looks.min = ch_looks.sum;
8969 else if (ch_looks.sum > looks.max)
8970 looks.max = ch_looks.sum;
8971 if (ch_gets.sum < gets.min)
8972 gets.min = ch_gets.sum;
8973 else if (ch_gets.sum > gets.max)
8974 gets.max = ch_gets.sum;
8975 if (ch_reorders.sum < reorders.min)
8976 reorders.min = ch_reorders.sum;
8977 else if (ch_reorders.sum > reorders.max)
8978 reorders.max = ch_reorders.sum;
8982 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8983 /* compute detailed per-chain stats */
8984 struct stats hdr_loads, hdr_gets;
8985 double v_looks, v_loads, v_gets;
8987 /* initialize stats with data from first element in chain */
8988 vp = queue_First(head, Volume);
8989 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8990 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8991 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8992 ch_gets.min = ch_gets.max = v_looks;
8993 hdr_loads.min = hdr_loads.max = v_loads;
8994 hdr_gets.min = hdr_gets.max = v_gets;
8995 hdr_loads.sum = hdr_gets.sum = 0;
8997 vp = queue_Next(vp, Volume);
8999 /* pull in stats from remaining elements in chain */
9000 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9001 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9002 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9003 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9005 hdr_loads.sum += v_loads;
9006 hdr_gets.sum += v_gets;
9008 if (v_looks < ch_gets.min)
9009 ch_gets.min = v_looks;
9010 else if (v_looks > ch_gets.max)
9011 ch_gets.max = v_looks;
9013 if (v_loads < hdr_loads.min)
9014 hdr_loads.min = v_loads;
9015 else if (v_loads > hdr_loads.max)
9016 hdr_loads.max = v_loads;
9018 if (v_gets < hdr_gets.min)
9019 hdr_gets.min = v_gets;
9020 else if (v_gets > hdr_gets.max)
9021 hdr_gets.max = v_gets;
9024 /* compute per-chain averages */
9025 ch_gets.avg = ch_gets.sum / ((double)head->len);
9026 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9027 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9029 /* dump per-chain stats */
9030 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9032 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9033 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9034 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9035 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9036 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9037 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9038 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9039 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9040 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9041 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9042 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9043 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9044 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9045 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9046 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9047 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9048 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9049 } else if (flags & VOL_STATS_PER_CHAIN) {
9050 /* dump simple per-chain stats */
9051 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9053 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9054 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9055 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9059 VHashEndExclusive_r(head);
9064 /* compute global averages */
9065 len.avg = len.sum / ((double)VolumeHashTable.Size);
9066 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9067 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9068 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9070 /* dump global stats */
9071 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9072 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9073 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9074 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9075 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9076 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9077 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9078 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9079 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9080 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9081 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9082 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9083 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9084 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9085 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9086 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9087 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9088 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9089 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9090 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9091 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9093 /* print extended disk related statistics */
9095 struct DiskPartition64 * diskP;
9096 afs_uint32 vol_count[VOLMAXPARTS+1];
9097 byte part_exists[VOLMAXPARTS+1];
9101 memset(vol_count, 0, sizeof(vol_count));
9102 memset(part_exists, 0, sizeof(part_exists));
9106 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9108 vol_count[id] = diskP->vol_list.len;
9109 part_exists[id] = 1;
9113 for (i = 0; i <= VOLMAXPARTS; i++) {
9114 if (part_exists[i]) {
9115 /* XXX while this is currently safe, it is a violation
9116 * of the VGetPartitionById_r interface contract. */
9117 diskP = VGetPartitionById_r(i, 0);
9119 Log("Partition %s has %d online volumes\n",
9120 VPartitionPath(diskP), diskP->vol_list.len);
9127 /* print extended VLRU statistics */
9128 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9129 afs_uint32 idx, cur, lpos;
9134 Log("VLRU State Dump:\n\n");
9136 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9137 Log("\t%s:\n", vlru_idx_to_string(idx));
9140 for (cur = vlru_stats.queue_info[idx].start;
9141 cur < vlru_stats.queue_info[idx].len;
9143 line[lpos++] = vlru_stats.vec[cur].volid;
9145 Log("\t\t%u, %u, %u, %u, %u,\n",
9146 line[0], line[1], line[2], line[3], line[4]);
9155 Log("\t\t%u, %u, %u, %u, %u\n",
9156 line[0], line[1], line[2], line[3], line[4]);
9161 free(vlru_stats.vec);
9168 VPrintExtendedCacheStats(int flags)
9171 VPrintExtendedCacheStats_r(flags);
9174 #endif /* AFS_DEMAND_ATTACH_FS */
9177 VCanScheduleSalvage(void)
9179 return vol_opts.canScheduleSalvage;
9185 return vol_opts.canUseFSSYNC;
9189 VCanUseSALVSYNC(void)
9191 return vol_opts.canUseSALVSYNC;
9195 VCanUnsafeAttach(void)
9197 return vol_opts.unsafe_attach;