4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
24 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
25 * Copyright (c) 2014 Integros [integros.com]
28 #include <sys/zfs_context.h>
30 #include <sys/dmu_tx.h>
31 #include <sys/space_map.h>
32 #include <sys/metaslab_impl.h>
33 #include <sys/vdev_impl.h>
35 #include <sys/spa_impl.h>
36 #include <sys/zfeature.h>
37 #include <sys/vdev_indirect_mapping.h>
39 SYSCTL_DECL(_vfs_zfs);
40 SYSCTL_NODE(_vfs_zfs, OID_AUTO, metaslab, CTLFLAG_RW, 0, "ZFS metaslab");
42 #define GANG_ALLOCATION(flags) \
43 ((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER))
45 uint64_t metaslab_aliquot = 512ULL << 10;
46 uint64_t metaslab_gang_bang = SPA_MAXBLOCKSIZE + 1; /* force gang blocks */
47 SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, gang_bang, CTLFLAG_RWTUN,
48 &metaslab_gang_bang, 0,
49 "Force gang block allocation for blocks larger than or equal to this value");
52 * The in-core space map representation is more compact than its on-disk form.
53 * The zfs_condense_pct determines how much more compact the in-core
54 * space map representation must be before we compact it on-disk.
55 * Values should be greater than or equal to 100.
57 int zfs_condense_pct = 200;
58 SYSCTL_INT(_vfs_zfs, OID_AUTO, condense_pct, CTLFLAG_RWTUN,
60 "Condense on-disk spacemap when it is more than this many percents"
61 " of in-memory counterpart");
64 * Condensing a metaslab is not guaranteed to actually reduce the amount of
65 * space used on disk. In particular, a space map uses data in increments of
66 * MAX(1 << ashift, space_map_blksize), so a metaslab might use the
67 * same number of blocks after condensing. Since the goal of condensing is to
68 * reduce the number of IOPs required to read the space map, we only want to
69 * condense when we can be sure we will reduce the number of blocks used by the
70 * space map. Unfortunately, we cannot precisely compute whether or not this is
71 * the case in metaslab_should_condense since we are holding ms_lock. Instead,
72 * we apply the following heuristic: do not condense a spacemap unless the
73 * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
76 int zfs_metaslab_condense_block_threshold = 4;
79 * The zfs_mg_noalloc_threshold defines which metaslab groups should
80 * be eligible for allocation. The value is defined as a percentage of
81 * free space. Metaslab groups that have more free space than
82 * zfs_mg_noalloc_threshold are always eligible for allocations. Once
83 * a metaslab group's free space is less than or equal to the
84 * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
85 * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
86 * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
87 * groups are allowed to accept allocations. Gang blocks are always
88 * eligible to allocate on any metaslab group. The default value of 0 means
89 * no metaslab group will be excluded based on this criterion.
91 int zfs_mg_noalloc_threshold = 0;
92 SYSCTL_INT(_vfs_zfs, OID_AUTO, mg_noalloc_threshold, CTLFLAG_RWTUN,
93 &zfs_mg_noalloc_threshold, 0,
94 "Percentage of metaslab group size that should be free"
95 " to make it eligible for allocation");
98 * Metaslab groups are considered eligible for allocations if their
99 * fragmenation metric (measured as a percentage) is less than or equal to
100 * zfs_mg_fragmentation_threshold. If a metaslab group exceeds this threshold
101 * then it will be skipped unless all metaslab groups within the metaslab
102 * class have also crossed this threshold.
104 int zfs_mg_fragmentation_threshold = 85;
105 SYSCTL_INT(_vfs_zfs, OID_AUTO, mg_fragmentation_threshold, CTLFLAG_RWTUN,
106 &zfs_mg_fragmentation_threshold, 0,
107 "Percentage of metaslab group size that should be considered "
108 "eligible for allocations unless all metaslab groups within the metaslab class "
109 "have also crossed this threshold");
112 * Allow metaslabs to keep their active state as long as their fragmentation
113 * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
114 * active metaslab that exceeds this threshold will no longer keep its active
115 * status allowing better metaslabs to be selected.
117 int zfs_metaslab_fragmentation_threshold = 70;
118 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, fragmentation_threshold, CTLFLAG_RWTUN,
119 &zfs_metaslab_fragmentation_threshold, 0,
120 "Maximum percentage of metaslab fragmentation level to keep their active state");
123 * When set will load all metaslabs when pool is first opened.
125 int metaslab_debug_load = 0;
126 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, debug_load, CTLFLAG_RWTUN,
127 &metaslab_debug_load, 0,
128 "Load all metaslabs when pool is first opened");
131 * When set will prevent metaslabs from being unloaded.
133 int metaslab_debug_unload = 0;
134 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, debug_unload, CTLFLAG_RWTUN,
135 &metaslab_debug_unload, 0,
136 "Prevent metaslabs from being unloaded");
139 * Minimum size which forces the dynamic allocator to change
140 * it's allocation strategy. Once the space map cannot satisfy
141 * an allocation of this size then it switches to using more
142 * aggressive strategy (i.e search by size rather than offset).
144 uint64_t metaslab_df_alloc_threshold = SPA_OLD_MAXBLOCKSIZE;
145 SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, df_alloc_threshold, CTLFLAG_RWTUN,
146 &metaslab_df_alloc_threshold, 0,
147 "Minimum size which forces the dynamic allocator to change it's allocation strategy");
150 * The minimum free space, in percent, which must be available
151 * in a space map to continue allocations in a first-fit fashion.
152 * Once the space map's free space drops below this level we dynamically
153 * switch to using best-fit allocations.
155 int metaslab_df_free_pct = 4;
156 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, df_free_pct, CTLFLAG_RWTUN,
157 &metaslab_df_free_pct, 0,
158 "The minimum free space, in percent, which must be available in a "
159 "space map to continue allocations in a first-fit fashion");
162 * A metaslab is considered "free" if it contains a contiguous
163 * segment which is greater than metaslab_min_alloc_size.
165 uint64_t metaslab_min_alloc_size = DMU_MAX_ACCESS;
166 SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, min_alloc_size, CTLFLAG_RWTUN,
167 &metaslab_min_alloc_size, 0,
168 "A metaslab is considered \"free\" if it contains a contiguous "
169 "segment which is greater than vfs.zfs.metaslab.min_alloc_size");
172 * Percentage of all cpus that can be used by the metaslab taskq.
174 int metaslab_load_pct = 50;
175 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, load_pct, CTLFLAG_RWTUN,
176 &metaslab_load_pct, 0,
177 "Percentage of cpus that can be used by the metaslab taskq");
180 * Determines how many txgs a metaslab may remain loaded without having any
181 * allocations from it. As long as a metaslab continues to be used we will
184 int metaslab_unload_delay = TXG_SIZE * 2;
185 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, unload_delay, CTLFLAG_RWTUN,
186 &metaslab_unload_delay, 0,
187 "Number of TXGs that an unused metaslab can be kept in memory");
190 * Max number of metaslabs per group to preload.
192 int metaslab_preload_limit = SPA_DVAS_PER_BP;
193 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, preload_limit, CTLFLAG_RWTUN,
194 &metaslab_preload_limit, 0,
195 "Max number of metaslabs per group to preload");
198 * Enable/disable preloading of metaslab.
200 boolean_t metaslab_preload_enabled = B_TRUE;
201 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, preload_enabled, CTLFLAG_RWTUN,
202 &metaslab_preload_enabled, 0,
203 "Max number of metaslabs per group to preload");
206 * Enable/disable fragmentation weighting on metaslabs.
208 boolean_t metaslab_fragmentation_factor_enabled = B_TRUE;
209 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, fragmentation_factor_enabled, CTLFLAG_RWTUN,
210 &metaslab_fragmentation_factor_enabled, 0,
211 "Enable fragmentation weighting on metaslabs");
214 * Enable/disable lba weighting (i.e. outer tracks are given preference).
216 boolean_t metaslab_lba_weighting_enabled = B_TRUE;
217 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, lba_weighting_enabled, CTLFLAG_RWTUN,
218 &metaslab_lba_weighting_enabled, 0,
219 "Enable LBA weighting (i.e. outer tracks are given preference)");
222 * Enable/disable metaslab group biasing.
224 boolean_t metaslab_bias_enabled = B_TRUE;
225 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, bias_enabled, CTLFLAG_RWTUN,
226 &metaslab_bias_enabled, 0,
227 "Enable metaslab group biasing");
230 * Enable/disable remapping of indirect DVAs to their concrete vdevs.
232 boolean_t zfs_remap_blkptr_enable = B_TRUE;
235 * Enable/disable segment-based metaslab selection.
237 boolean_t zfs_metaslab_segment_weight_enabled = B_TRUE;
240 * When using segment-based metaslab selection, we will continue
241 * allocating from the active metaslab until we have exhausted
242 * zfs_metaslab_switch_threshold of its buckets.
244 int zfs_metaslab_switch_threshold = 2;
247 * Internal switch to enable/disable the metaslab allocation tracing
250 boolean_t metaslab_trace_enabled = B_TRUE;
253 * Maximum entries that the metaslab allocation tracing facility will keep
254 * in a given list when running in non-debug mode. We limit the number
255 * of entries in non-debug mode to prevent us from using up too much memory.
256 * The limit should be sufficiently large that we don't expect any allocation
257 * to every exceed this value. In debug mode, the system will panic if this
258 * limit is ever reached allowing for further investigation.
260 uint64_t metaslab_trace_max_entries = 5000;
262 static uint64_t metaslab_weight(metaslab_t *);
263 static void metaslab_set_fragmentation(metaslab_t *);
264 static void metaslab_free_impl(vdev_t *, uint64_t, uint64_t, uint64_t);
265 static void metaslab_check_free_impl(vdev_t *, uint64_t, uint64_t);
267 kmem_cache_t *metaslab_alloc_trace_cache;
270 * ==========================================================================
272 * ==========================================================================
275 metaslab_class_create(spa_t *spa, metaslab_ops_t *ops)
277 metaslab_class_t *mc;
279 mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
284 mutex_init(&mc->mc_lock, NULL, MUTEX_DEFAULT, NULL);
285 refcount_create_tracked(&mc->mc_alloc_slots);
291 metaslab_class_destroy(metaslab_class_t *mc)
293 ASSERT(mc->mc_rotor == NULL);
294 ASSERT(mc->mc_alloc == 0);
295 ASSERT(mc->mc_deferred == 0);
296 ASSERT(mc->mc_space == 0);
297 ASSERT(mc->mc_dspace == 0);
299 refcount_destroy(&mc->mc_alloc_slots);
300 mutex_destroy(&mc->mc_lock);
301 kmem_free(mc, sizeof (metaslab_class_t));
305 metaslab_class_validate(metaslab_class_t *mc)
307 metaslab_group_t *mg;
311 * Must hold one of the spa_config locks.
313 ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
314 spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
316 if ((mg = mc->mc_rotor) == NULL)
321 ASSERT(vd->vdev_mg != NULL);
322 ASSERT3P(vd->vdev_top, ==, vd);
323 ASSERT3P(mg->mg_class, ==, mc);
324 ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
325 } while ((mg = mg->mg_next) != mc->mc_rotor);
331 metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
332 int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
334 atomic_add_64(&mc->mc_alloc, alloc_delta);
335 atomic_add_64(&mc->mc_deferred, defer_delta);
336 atomic_add_64(&mc->mc_space, space_delta);
337 atomic_add_64(&mc->mc_dspace, dspace_delta);
341 metaslab_class_minblocksize_update(metaslab_class_t *mc)
343 metaslab_group_t *mg;
345 uint64_t minashift = UINT64_MAX;
347 if ((mg = mc->mc_rotor) == NULL) {
348 mc->mc_minblocksize = SPA_MINBLOCKSIZE;
354 if (vd->vdev_ashift < minashift)
355 minashift = vd->vdev_ashift;
356 } while ((mg = mg->mg_next) != mc->mc_rotor);
358 mc->mc_minblocksize = 1ULL << minashift;
362 metaslab_class_get_alloc(metaslab_class_t *mc)
364 return (mc->mc_alloc);
368 metaslab_class_get_deferred(metaslab_class_t *mc)
370 return (mc->mc_deferred);
374 metaslab_class_get_space(metaslab_class_t *mc)
376 return (mc->mc_space);
380 metaslab_class_get_dspace(metaslab_class_t *mc)
382 return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
386 metaslab_class_get_minblocksize(metaslab_class_t *mc)
388 return (mc->mc_minblocksize);
392 metaslab_class_histogram_verify(metaslab_class_t *mc)
394 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
398 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
401 mc_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
404 for (int c = 0; c < rvd->vdev_children; c++) {
405 vdev_t *tvd = rvd->vdev_child[c];
406 metaslab_group_t *mg = tvd->vdev_mg;
409 * Skip any holes, uninitialized top-levels, or
410 * vdevs that are not in this metalab class.
412 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
413 mg->mg_class != mc) {
417 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
418 mc_hist[i] += mg->mg_histogram[i];
421 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
422 VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
424 kmem_free(mc_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
428 * Calculate the metaslab class's fragmentation metric. The metric
429 * is weighted based on the space contribution of each metaslab group.
430 * The return value will be a number between 0 and 100 (inclusive), or
431 * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
432 * zfs_frag_table for more information about the metric.
435 metaslab_class_fragmentation(metaslab_class_t *mc)
437 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
438 uint64_t fragmentation = 0;
440 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
442 for (int c = 0; c < rvd->vdev_children; c++) {
443 vdev_t *tvd = rvd->vdev_child[c];
444 metaslab_group_t *mg = tvd->vdev_mg;
447 * Skip any holes, uninitialized top-levels,
448 * or vdevs that are not in this metalab class.
450 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
451 mg->mg_class != mc) {
456 * If a metaslab group does not contain a fragmentation
457 * metric then just bail out.
459 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
460 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
461 return (ZFS_FRAG_INVALID);
465 * Determine how much this metaslab_group is contributing
466 * to the overall pool fragmentation metric.
468 fragmentation += mg->mg_fragmentation *
469 metaslab_group_get_space(mg);
471 fragmentation /= metaslab_class_get_space(mc);
473 ASSERT3U(fragmentation, <=, 100);
474 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
475 return (fragmentation);
479 * Calculate the amount of expandable space that is available in
480 * this metaslab class. If a device is expanded then its expandable
481 * space will be the amount of allocatable space that is currently not
482 * part of this metaslab class.
485 metaslab_class_expandable_space(metaslab_class_t *mc)
487 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
490 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
491 for (int c = 0; c < rvd->vdev_children; c++) {
493 vdev_t *tvd = rvd->vdev_child[c];
494 metaslab_group_t *mg = tvd->vdev_mg;
496 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
497 mg->mg_class != mc) {
502 * Calculate if we have enough space to add additional
503 * metaslabs. We report the expandable space in terms
504 * of the metaslab size since that's the unit of expansion.
505 * Adjust by efi system partition size.
507 tspace = tvd->vdev_max_asize - tvd->vdev_asize;
508 if (tspace > mc->mc_spa->spa_bootsize) {
509 tspace -= mc->mc_spa->spa_bootsize;
511 space += P2ALIGN(tspace, 1ULL << tvd->vdev_ms_shift);
513 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
518 metaslab_compare(const void *x1, const void *x2)
520 const metaslab_t *m1 = x1;
521 const metaslab_t *m2 = x2;
523 if (m1->ms_weight < m2->ms_weight)
525 if (m1->ms_weight > m2->ms_weight)
529 * If the weights are identical, use the offset to force uniqueness.
531 if (m1->ms_start < m2->ms_start)
533 if (m1->ms_start > m2->ms_start)
536 ASSERT3P(m1, ==, m2);
542 * Verify that the space accounting on disk matches the in-core range_trees.
545 metaslab_verify_space(metaslab_t *msp, uint64_t txg)
547 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
548 uint64_t allocated = 0;
549 uint64_t sm_free_space, msp_free_space;
551 ASSERT(MUTEX_HELD(&msp->ms_lock));
553 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
557 * We can only verify the metaslab space when we're called
558 * from syncing context with a loaded metaslab that has an allocated
559 * space map. Calling this in non-syncing context does not
560 * provide a consistent view of the metaslab since we're performing
561 * allocations in the future.
563 if (txg != spa_syncing_txg(spa) || msp->ms_sm == NULL ||
567 sm_free_space = msp->ms_size - space_map_allocated(msp->ms_sm) -
568 space_map_alloc_delta(msp->ms_sm);
571 * Account for future allocations since we would have already
572 * deducted that space from the ms_freetree.
574 for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
576 range_tree_space(msp->ms_alloctree[(txg + t) & TXG_MASK]);
579 msp_free_space = range_tree_space(msp->ms_tree) + allocated +
580 msp->ms_deferspace + range_tree_space(msp->ms_freedtree);
582 VERIFY3U(sm_free_space, ==, msp_free_space);
586 * ==========================================================================
588 * ==========================================================================
591 * Update the allocatable flag and the metaslab group's capacity.
592 * The allocatable flag is set to true if the capacity is below
593 * the zfs_mg_noalloc_threshold or has a fragmentation value that is
594 * greater than zfs_mg_fragmentation_threshold. If a metaslab group
595 * transitions from allocatable to non-allocatable or vice versa then the
596 * metaslab group's class is updated to reflect the transition.
599 metaslab_group_alloc_update(metaslab_group_t *mg)
601 vdev_t *vd = mg->mg_vd;
602 metaslab_class_t *mc = mg->mg_class;
603 vdev_stat_t *vs = &vd->vdev_stat;
604 boolean_t was_allocatable;
605 boolean_t was_initialized;
607 ASSERT(vd == vd->vdev_top);
608 ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_READER), ==,
611 mutex_enter(&mg->mg_lock);
612 was_allocatable = mg->mg_allocatable;
613 was_initialized = mg->mg_initialized;
615 mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
618 mutex_enter(&mc->mc_lock);
621 * If the metaslab group was just added then it won't
622 * have any space until we finish syncing out this txg.
623 * At that point we will consider it initialized and available
624 * for allocations. We also don't consider non-activated
625 * metaslab groups (e.g. vdevs that are in the middle of being removed)
626 * to be initialized, because they can't be used for allocation.
628 mg->mg_initialized = metaslab_group_initialized(mg);
629 if (!was_initialized && mg->mg_initialized) {
631 } else if (was_initialized && !mg->mg_initialized) {
632 ASSERT3U(mc->mc_groups, >, 0);
635 if (mg->mg_initialized)
636 mg->mg_no_free_space = B_FALSE;
639 * A metaslab group is considered allocatable if it has plenty
640 * of free space or is not heavily fragmented. We only take
641 * fragmentation into account if the metaslab group has a valid
642 * fragmentation metric (i.e. a value between 0 and 100).
644 mg->mg_allocatable = (mg->mg_activation_count > 0 &&
645 mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
646 (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
647 mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
650 * The mc_alloc_groups maintains a count of the number of
651 * groups in this metaslab class that are still above the
652 * zfs_mg_noalloc_threshold. This is used by the allocating
653 * threads to determine if they should avoid allocations to
654 * a given group. The allocator will avoid allocations to a group
655 * if that group has reached or is below the zfs_mg_noalloc_threshold
656 * and there are still other groups that are above the threshold.
657 * When a group transitions from allocatable to non-allocatable or
658 * vice versa we update the metaslab class to reflect that change.
659 * When the mc_alloc_groups value drops to 0 that means that all
660 * groups have reached the zfs_mg_noalloc_threshold making all groups
661 * eligible for allocations. This effectively means that all devices
662 * are balanced again.
664 if (was_allocatable && !mg->mg_allocatable)
665 mc->mc_alloc_groups--;
666 else if (!was_allocatable && mg->mg_allocatable)
667 mc->mc_alloc_groups++;
668 mutex_exit(&mc->mc_lock);
670 mutex_exit(&mg->mg_lock);
674 metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
676 metaslab_group_t *mg;
678 mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
679 mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
680 avl_create(&mg->mg_metaslab_tree, metaslab_compare,
681 sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
684 mg->mg_activation_count = 0;
685 mg->mg_initialized = B_FALSE;
686 mg->mg_no_free_space = B_TRUE;
687 refcount_create_tracked(&mg->mg_alloc_queue_depth);
689 mg->mg_taskq = taskq_create("metaslab_group_taskq", metaslab_load_pct,
690 minclsyspri, 10, INT_MAX, TASKQ_THREADS_CPU_PCT);
696 metaslab_group_destroy(metaslab_group_t *mg)
698 ASSERT(mg->mg_prev == NULL);
699 ASSERT(mg->mg_next == NULL);
701 * We may have gone below zero with the activation count
702 * either because we never activated in the first place or
703 * because we're done, and possibly removing the vdev.
705 ASSERT(mg->mg_activation_count <= 0);
707 taskq_destroy(mg->mg_taskq);
708 avl_destroy(&mg->mg_metaslab_tree);
709 mutex_destroy(&mg->mg_lock);
710 refcount_destroy(&mg->mg_alloc_queue_depth);
711 kmem_free(mg, sizeof (metaslab_group_t));
715 metaslab_group_activate(metaslab_group_t *mg)
717 metaslab_class_t *mc = mg->mg_class;
718 metaslab_group_t *mgprev, *mgnext;
720 ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER), !=, 0);
722 ASSERT(mc->mc_rotor != mg);
723 ASSERT(mg->mg_prev == NULL);
724 ASSERT(mg->mg_next == NULL);
725 ASSERT(mg->mg_activation_count <= 0);
727 if (++mg->mg_activation_count <= 0)
730 mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
731 metaslab_group_alloc_update(mg);
733 if ((mgprev = mc->mc_rotor) == NULL) {
737 mgnext = mgprev->mg_next;
738 mg->mg_prev = mgprev;
739 mg->mg_next = mgnext;
740 mgprev->mg_next = mg;
741 mgnext->mg_prev = mg;
744 metaslab_class_minblocksize_update(mc);
748 * Passivate a metaslab group and remove it from the allocation rotor.
749 * Callers must hold both the SCL_ALLOC and SCL_ZIO lock prior to passivating
750 * a metaslab group. This function will momentarily drop spa_config_locks
751 * that are lower than the SCL_ALLOC lock (see comment below).
754 metaslab_group_passivate(metaslab_group_t *mg)
756 metaslab_class_t *mc = mg->mg_class;
757 spa_t *spa = mc->mc_spa;
758 metaslab_group_t *mgprev, *mgnext;
759 int locks = spa_config_held(spa, SCL_ALL, RW_WRITER);
761 ASSERT3U(spa_config_held(spa, SCL_ALLOC | SCL_ZIO, RW_WRITER), ==,
762 (SCL_ALLOC | SCL_ZIO));
764 if (--mg->mg_activation_count != 0) {
765 ASSERT(mc->mc_rotor != mg);
766 ASSERT(mg->mg_prev == NULL);
767 ASSERT(mg->mg_next == NULL);
768 ASSERT(mg->mg_activation_count < 0);
773 * The spa_config_lock is an array of rwlocks, ordered as
774 * follows (from highest to lowest):
775 * SCL_CONFIG > SCL_STATE > SCL_L2ARC > SCL_ALLOC >
776 * SCL_ZIO > SCL_FREE > SCL_VDEV
777 * (For more information about the spa_config_lock see spa_misc.c)
778 * The higher the lock, the broader its coverage. When we passivate
779 * a metaslab group, we must hold both the SCL_ALLOC and the SCL_ZIO
780 * config locks. However, the metaslab group's taskq might be trying
781 * to preload metaslabs so we must drop the SCL_ZIO lock and any
782 * lower locks to allow the I/O to complete. At a minimum,
783 * we continue to hold the SCL_ALLOC lock, which prevents any future
784 * allocations from taking place and any changes to the vdev tree.
786 spa_config_exit(spa, locks & ~(SCL_ZIO - 1), spa);
787 taskq_wait(mg->mg_taskq);
788 spa_config_enter(spa, locks & ~(SCL_ZIO - 1), spa, RW_WRITER);
789 metaslab_group_alloc_update(mg);
791 mgprev = mg->mg_prev;
792 mgnext = mg->mg_next;
797 mc->mc_rotor = mgnext;
798 mgprev->mg_next = mgnext;
799 mgnext->mg_prev = mgprev;
804 metaslab_class_minblocksize_update(mc);
808 metaslab_group_initialized(metaslab_group_t *mg)
810 vdev_t *vd = mg->mg_vd;
811 vdev_stat_t *vs = &vd->vdev_stat;
813 return (vs->vs_space != 0 && mg->mg_activation_count > 0);
817 metaslab_group_get_space(metaslab_group_t *mg)
819 return ((1ULL << mg->mg_vd->vdev_ms_shift) * mg->mg_vd->vdev_ms_count);
823 metaslab_group_histogram_verify(metaslab_group_t *mg)
826 vdev_t *vd = mg->mg_vd;
827 uint64_t ashift = vd->vdev_ashift;
830 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
833 mg_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
836 ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE, >=,
837 SPACE_MAP_HISTOGRAM_SIZE + ashift);
839 for (int m = 0; m < vd->vdev_ms_count; m++) {
840 metaslab_t *msp = vd->vdev_ms[m];
842 if (msp->ms_sm == NULL)
845 for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
846 mg_hist[i + ashift] +=
847 msp->ms_sm->sm_phys->smp_histogram[i];
850 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i ++)
851 VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
853 kmem_free(mg_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
857 metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
859 metaslab_class_t *mc = mg->mg_class;
860 uint64_t ashift = mg->mg_vd->vdev_ashift;
862 ASSERT(MUTEX_HELD(&msp->ms_lock));
863 if (msp->ms_sm == NULL)
866 mutex_enter(&mg->mg_lock);
867 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
868 mg->mg_histogram[i + ashift] +=
869 msp->ms_sm->sm_phys->smp_histogram[i];
870 mc->mc_histogram[i + ashift] +=
871 msp->ms_sm->sm_phys->smp_histogram[i];
873 mutex_exit(&mg->mg_lock);
877 metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
879 metaslab_class_t *mc = mg->mg_class;
880 uint64_t ashift = mg->mg_vd->vdev_ashift;
882 ASSERT(MUTEX_HELD(&msp->ms_lock));
883 if (msp->ms_sm == NULL)
886 mutex_enter(&mg->mg_lock);
887 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
888 ASSERT3U(mg->mg_histogram[i + ashift], >=,
889 msp->ms_sm->sm_phys->smp_histogram[i]);
890 ASSERT3U(mc->mc_histogram[i + ashift], >=,
891 msp->ms_sm->sm_phys->smp_histogram[i]);
893 mg->mg_histogram[i + ashift] -=
894 msp->ms_sm->sm_phys->smp_histogram[i];
895 mc->mc_histogram[i + ashift] -=
896 msp->ms_sm->sm_phys->smp_histogram[i];
898 mutex_exit(&mg->mg_lock);
902 metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
904 ASSERT(msp->ms_group == NULL);
905 mutex_enter(&mg->mg_lock);
908 avl_add(&mg->mg_metaslab_tree, msp);
909 mutex_exit(&mg->mg_lock);
911 mutex_enter(&msp->ms_lock);
912 metaslab_group_histogram_add(mg, msp);
913 mutex_exit(&msp->ms_lock);
917 metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
919 mutex_enter(&msp->ms_lock);
920 metaslab_group_histogram_remove(mg, msp);
921 mutex_exit(&msp->ms_lock);
923 mutex_enter(&mg->mg_lock);
924 ASSERT(msp->ms_group == mg);
925 avl_remove(&mg->mg_metaslab_tree, msp);
926 msp->ms_group = NULL;
927 mutex_exit(&mg->mg_lock);
931 metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
934 * Although in principle the weight can be any value, in
935 * practice we do not use values in the range [1, 511].
937 ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
938 ASSERT(MUTEX_HELD(&msp->ms_lock));
940 mutex_enter(&mg->mg_lock);
941 ASSERT(msp->ms_group == mg);
942 avl_remove(&mg->mg_metaslab_tree, msp);
943 msp->ms_weight = weight;
944 avl_add(&mg->mg_metaslab_tree, msp);
945 mutex_exit(&mg->mg_lock);
949 * Calculate the fragmentation for a given metaslab group. We can use
950 * a simple average here since all metaslabs within the group must have
951 * the same size. The return value will be a value between 0 and 100
952 * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
953 * group have a fragmentation metric.
956 metaslab_group_fragmentation(metaslab_group_t *mg)
958 vdev_t *vd = mg->mg_vd;
959 uint64_t fragmentation = 0;
960 uint64_t valid_ms = 0;
962 for (int m = 0; m < vd->vdev_ms_count; m++) {
963 metaslab_t *msp = vd->vdev_ms[m];
965 if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
969 fragmentation += msp->ms_fragmentation;
972 if (valid_ms <= vd->vdev_ms_count / 2)
973 return (ZFS_FRAG_INVALID);
975 fragmentation /= valid_ms;
976 ASSERT3U(fragmentation, <=, 100);
977 return (fragmentation);
981 * Determine if a given metaslab group should skip allocations. A metaslab
982 * group should avoid allocations if its free capacity is less than the
983 * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
984 * zfs_mg_fragmentation_threshold and there is at least one metaslab group
985 * that can still handle allocations. If the allocation throttle is enabled
986 * then we skip allocations to devices that have reached their maximum
987 * allocation queue depth unless the selected metaslab group is the only
988 * eligible group remaining.
991 metaslab_group_allocatable(metaslab_group_t *mg, metaslab_group_t *rotor,
994 spa_t *spa = mg->mg_vd->vdev_spa;
995 metaslab_class_t *mc = mg->mg_class;
998 * We can only consider skipping this metaslab group if it's
999 * in the normal metaslab class and there are other metaslab
1000 * groups to select from. Otherwise, we always consider it eligible
1003 if (mc != spa_normal_class(spa) || mc->mc_groups <= 1)
1007 * If the metaslab group's mg_allocatable flag is set (see comments
1008 * in metaslab_group_alloc_update() for more information) and
1009 * the allocation throttle is disabled then allow allocations to this
1010 * device. However, if the allocation throttle is enabled then
1011 * check if we have reached our allocation limit (mg_alloc_queue_depth)
1012 * to determine if we should allow allocations to this metaslab group.
1013 * If all metaslab groups are no longer considered allocatable
1014 * (mc_alloc_groups == 0) or we're trying to allocate the smallest
1015 * gang block size then we allow allocations on this metaslab group
1016 * regardless of the mg_allocatable or throttle settings.
1018 if (mg->mg_allocatable) {
1019 metaslab_group_t *mgp;
1021 uint64_t qmax = mg->mg_max_alloc_queue_depth;
1023 if (!mc->mc_alloc_throttle_enabled)
1027 * If this metaslab group does not have any free space, then
1028 * there is no point in looking further.
1030 if (mg->mg_no_free_space)
1033 qdepth = refcount_count(&mg->mg_alloc_queue_depth);
1036 * If this metaslab group is below its qmax or it's
1037 * the only allocatable metasable group, then attempt
1038 * to allocate from it.
1040 if (qdepth < qmax || mc->mc_alloc_groups == 1)
1042 ASSERT3U(mc->mc_alloc_groups, >, 1);
1045 * Since this metaslab group is at or over its qmax, we
1046 * need to determine if there are metaslab groups after this
1047 * one that might be able to handle this allocation. This is
1048 * racy since we can't hold the locks for all metaslab
1049 * groups at the same time when we make this check.
1051 for (mgp = mg->mg_next; mgp != rotor; mgp = mgp->mg_next) {
1052 qmax = mgp->mg_max_alloc_queue_depth;
1054 qdepth = refcount_count(&mgp->mg_alloc_queue_depth);
1057 * If there is another metaslab group that
1058 * might be able to handle the allocation, then
1059 * we return false so that we skip this group.
1061 if (qdepth < qmax && !mgp->mg_no_free_space)
1066 * We didn't find another group to handle the allocation
1067 * so we can't skip this metaslab group even though
1068 * we are at or over our qmax.
1072 } else if (mc->mc_alloc_groups == 0 || psize == SPA_MINBLOCKSIZE) {
1079 * ==========================================================================
1080 * Range tree callbacks
1081 * ==========================================================================
1085 * Comparison function for the private size-ordered tree. Tree is sorted
1086 * by size, larger sizes at the end of the tree.
1089 metaslab_rangesize_compare(const void *x1, const void *x2)
1091 const range_seg_t *r1 = x1;
1092 const range_seg_t *r2 = x2;
1093 uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1094 uint64_t rs_size2 = r2->rs_end - r2->rs_start;
1096 if (rs_size1 < rs_size2)
1098 if (rs_size1 > rs_size2)
1101 if (r1->rs_start < r2->rs_start)
1104 if (r1->rs_start > r2->rs_start)
1111 * Create any block allocator specific components. The current allocators
1112 * rely on using both a size-ordered range_tree_t and an array of uint64_t's.
1115 metaslab_rt_create(range_tree_t *rt, void *arg)
1117 metaslab_t *msp = arg;
1119 ASSERT3P(rt->rt_arg, ==, msp);
1120 ASSERT(msp->ms_tree == NULL);
1122 avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
1123 sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
1127 * Destroy the block allocator specific components.
1130 metaslab_rt_destroy(range_tree_t *rt, void *arg)
1132 metaslab_t *msp = arg;
1134 ASSERT3P(rt->rt_arg, ==, msp);
1135 ASSERT3P(msp->ms_tree, ==, rt);
1136 ASSERT0(avl_numnodes(&msp->ms_size_tree));
1138 avl_destroy(&msp->ms_size_tree);
1142 metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg)
1144 metaslab_t *msp = arg;
1146 ASSERT3P(rt->rt_arg, ==, msp);
1147 ASSERT3P(msp->ms_tree, ==, rt);
1148 VERIFY(!msp->ms_condensing);
1149 avl_add(&msp->ms_size_tree, rs);
1153 metaslab_rt_remove(range_tree_t *rt, range_seg_t *rs, void *arg)
1155 metaslab_t *msp = arg;
1157 ASSERT3P(rt->rt_arg, ==, msp);
1158 ASSERT3P(msp->ms_tree, ==, rt);
1159 VERIFY(!msp->ms_condensing);
1160 avl_remove(&msp->ms_size_tree, rs);
1164 metaslab_rt_vacate(range_tree_t *rt, void *arg)
1166 metaslab_t *msp = arg;
1168 ASSERT3P(rt->rt_arg, ==, msp);
1169 ASSERT3P(msp->ms_tree, ==, rt);
1172 * Normally one would walk the tree freeing nodes along the way.
1173 * Since the nodes are shared with the range trees we can avoid
1174 * walking all nodes and just reinitialize the avl tree. The nodes
1175 * will be freed by the range tree, so we don't want to free them here.
1177 avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
1178 sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
1181 static range_tree_ops_t metaslab_rt_ops = {
1183 metaslab_rt_destroy,
1190 * ==========================================================================
1191 * Common allocator routines
1192 * ==========================================================================
1196 * Return the maximum contiguous segment within the metaslab.
1199 metaslab_block_maxsize(metaslab_t *msp)
1201 avl_tree_t *t = &msp->ms_size_tree;
1204 if (t == NULL || (rs = avl_last(t)) == NULL)
1207 return (rs->rs_end - rs->rs_start);
1210 static range_seg_t *
1211 metaslab_block_find(avl_tree_t *t, uint64_t start, uint64_t size)
1213 range_seg_t *rs, rsearch;
1216 rsearch.rs_start = start;
1217 rsearch.rs_end = start + size;
1219 rs = avl_find(t, &rsearch, &where);
1221 rs = avl_nearest(t, where, AVL_AFTER);
1228 * This is a helper function that can be used by the allocator to find
1229 * a suitable block to allocate. This will search the specified AVL
1230 * tree looking for a block that matches the specified criteria.
1233 metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
1236 range_seg_t *rs = metaslab_block_find(t, *cursor, size);
1238 while (rs != NULL) {
1239 uint64_t offset = P2ROUNDUP(rs->rs_start, align);
1241 if (offset + size <= rs->rs_end) {
1242 *cursor = offset + size;
1245 rs = AVL_NEXT(t, rs);
1249 * If we know we've searched the whole map (*cursor == 0), give up.
1250 * Otherwise, reset the cursor to the beginning and try again.
1256 return (metaslab_block_picker(t, cursor, size, align));
1260 * ==========================================================================
1261 * The first-fit block allocator
1262 * ==========================================================================
1265 metaslab_ff_alloc(metaslab_t *msp, uint64_t size)
1268 * Find the largest power of 2 block size that evenly divides the
1269 * requested size. This is used to try to allocate blocks with similar
1270 * alignment from the same area of the metaslab (i.e. same cursor
1271 * bucket) but it does not guarantee that other allocations sizes
1272 * may exist in the same region.
1274 uint64_t align = size & -size;
1275 uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
1276 avl_tree_t *t = &msp->ms_tree->rt_root;
1278 return (metaslab_block_picker(t, cursor, size, align));
1281 static metaslab_ops_t metaslab_ff_ops = {
1286 * ==========================================================================
1287 * Dynamic block allocator -
1288 * Uses the first fit allocation scheme until space get low and then
1289 * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
1290 * and metaslab_df_free_pct to determine when to switch the allocation scheme.
1291 * ==========================================================================
1294 metaslab_df_alloc(metaslab_t *msp, uint64_t size)
1297 * Find the largest power of 2 block size that evenly divides the
1298 * requested size. This is used to try to allocate blocks with similar
1299 * alignment from the same area of the metaslab (i.e. same cursor
1300 * bucket) but it does not guarantee that other allocations sizes
1301 * may exist in the same region.
1303 uint64_t align = size & -size;
1304 uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
1305 range_tree_t *rt = msp->ms_tree;
1306 avl_tree_t *t = &rt->rt_root;
1307 uint64_t max_size = metaslab_block_maxsize(msp);
1308 int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1310 ASSERT(MUTEX_HELD(&msp->ms_lock));
1311 ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
1313 if (max_size < size)
1317 * If we're running low on space switch to using the size
1318 * sorted AVL tree (best-fit).
1320 if (max_size < metaslab_df_alloc_threshold ||
1321 free_pct < metaslab_df_free_pct) {
1322 t = &msp->ms_size_tree;
1326 return (metaslab_block_picker(t, cursor, size, 1ULL));
1329 static metaslab_ops_t metaslab_df_ops = {
1334 * ==========================================================================
1335 * Cursor fit block allocator -
1336 * Select the largest region in the metaslab, set the cursor to the beginning
1337 * of the range and the cursor_end to the end of the range. As allocations
1338 * are made advance the cursor. Continue allocating from the cursor until
1339 * the range is exhausted and then find a new range.
1340 * ==========================================================================
1343 metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
1345 range_tree_t *rt = msp->ms_tree;
1346 avl_tree_t *t = &msp->ms_size_tree;
1347 uint64_t *cursor = &msp->ms_lbas[0];
1348 uint64_t *cursor_end = &msp->ms_lbas[1];
1349 uint64_t offset = 0;
1351 ASSERT(MUTEX_HELD(&msp->ms_lock));
1352 ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&rt->rt_root));
1354 ASSERT3U(*cursor_end, >=, *cursor);
1356 if ((*cursor + size) > *cursor_end) {
1359 rs = avl_last(&msp->ms_size_tree);
1360 if (rs == NULL || (rs->rs_end - rs->rs_start) < size)
1363 *cursor = rs->rs_start;
1364 *cursor_end = rs->rs_end;
1373 static metaslab_ops_t metaslab_cf_ops = {
1378 * ==========================================================================
1379 * New dynamic fit allocator -
1380 * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1381 * contiguous blocks. If no region is found then just use the largest segment
1383 * ==========================================================================
1387 * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1388 * to request from the allocator.
1390 uint64_t metaslab_ndf_clump_shift = 4;
1393 metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
1395 avl_tree_t *t = &msp->ms_tree->rt_root;
1397 range_seg_t *rs, rsearch;
1398 uint64_t hbit = highbit64(size);
1399 uint64_t *cursor = &msp->ms_lbas[hbit - 1];
1400 uint64_t max_size = metaslab_block_maxsize(msp);
1402 ASSERT(MUTEX_HELD(&msp->ms_lock));
1403 ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
1405 if (max_size < size)
1408 rsearch.rs_start = *cursor;
1409 rsearch.rs_end = *cursor + size;
1411 rs = avl_find(t, &rsearch, &where);
1412 if (rs == NULL || (rs->rs_end - rs->rs_start) < size) {
1413 t = &msp->ms_size_tree;
1415 rsearch.rs_start = 0;
1416 rsearch.rs_end = MIN(max_size,
1417 1ULL << (hbit + metaslab_ndf_clump_shift));
1418 rs = avl_find(t, &rsearch, &where);
1420 rs = avl_nearest(t, where, AVL_AFTER);
1424 if ((rs->rs_end - rs->rs_start) >= size) {
1425 *cursor = rs->rs_start + size;
1426 return (rs->rs_start);
1431 static metaslab_ops_t metaslab_ndf_ops = {
1435 metaslab_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
1438 * ==========================================================================
1440 * ==========================================================================
1444 * Wait for any in-progress metaslab loads to complete.
1447 metaslab_load_wait(metaslab_t *msp)
1449 ASSERT(MUTEX_HELD(&msp->ms_lock));
1451 while (msp->ms_loading) {
1452 ASSERT(!msp->ms_loaded);
1453 cv_wait(&msp->ms_load_cv, &msp->ms_lock);
1458 metaslab_load(metaslab_t *msp)
1461 boolean_t success = B_FALSE;
1463 ASSERT(MUTEX_HELD(&msp->ms_lock));
1464 ASSERT(!msp->ms_loaded);
1465 ASSERT(!msp->ms_loading);
1467 msp->ms_loading = B_TRUE;
1469 * Nobody else can manipulate a loading metaslab, so it's now safe
1470 * to drop the lock. This way we don't have to hold the lock while
1471 * reading the spacemap from disk.
1473 mutex_exit(&msp->ms_lock);
1476 * If the space map has not been allocated yet, then treat
1477 * all the space in the metaslab as free and add it to the
1480 if (msp->ms_sm != NULL)
1481 error = space_map_load(msp->ms_sm, msp->ms_tree, SM_FREE);
1483 range_tree_add(msp->ms_tree, msp->ms_start, msp->ms_size);
1485 success = (error == 0);
1487 mutex_enter(&msp->ms_lock);
1488 msp->ms_loading = B_FALSE;
1491 ASSERT3P(msp->ms_group, !=, NULL);
1492 msp->ms_loaded = B_TRUE;
1494 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1495 range_tree_walk(msp->ms_defertree[t],
1496 range_tree_remove, msp->ms_tree);
1498 msp->ms_max_size = metaslab_block_maxsize(msp);
1500 cv_broadcast(&msp->ms_load_cv);
1505 metaslab_unload(metaslab_t *msp)
1507 ASSERT(MUTEX_HELD(&msp->ms_lock));
1508 range_tree_vacate(msp->ms_tree, NULL, NULL);
1509 msp->ms_loaded = B_FALSE;
1510 msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
1511 msp->ms_max_size = 0;
1515 metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object, uint64_t txg,
1518 vdev_t *vd = mg->mg_vd;
1519 objset_t *mos = vd->vdev_spa->spa_meta_objset;
1523 ms = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
1524 mutex_init(&ms->ms_lock, NULL, MUTEX_DEFAULT, NULL);
1525 mutex_init(&ms->ms_sync_lock, NULL, MUTEX_DEFAULT, NULL);
1526 cv_init(&ms->ms_load_cv, NULL, CV_DEFAULT, NULL);
1528 ms->ms_start = id << vd->vdev_ms_shift;
1529 ms->ms_size = 1ULL << vd->vdev_ms_shift;
1532 * We only open space map objects that already exist. All others
1533 * will be opened when we finally allocate an object for it.
1536 error = space_map_open(&ms->ms_sm, mos, object, ms->ms_start,
1537 ms->ms_size, vd->vdev_ashift);
1540 kmem_free(ms, sizeof (metaslab_t));
1544 ASSERT(ms->ms_sm != NULL);
1548 * We create the main range tree here, but we don't create the
1549 * other range trees until metaslab_sync_done(). This serves
1550 * two purposes: it allows metaslab_sync_done() to detect the
1551 * addition of new space; and for debugging, it ensures that we'd
1552 * data fault on any attempt to use this metaslab before it's ready.
1554 ms->ms_tree = range_tree_create(&metaslab_rt_ops, ms);
1555 metaslab_group_add(mg, ms);
1557 metaslab_set_fragmentation(ms);
1560 * If we're opening an existing pool (txg == 0) or creating
1561 * a new one (txg == TXG_INITIAL), all space is available now.
1562 * If we're adding space to an existing pool, the new space
1563 * does not become available until after this txg has synced.
1564 * The metaslab's weight will also be initialized when we sync
1565 * out this txg. This ensures that we don't attempt to allocate
1566 * from it before we have initialized it completely.
1568 if (txg <= TXG_INITIAL)
1569 metaslab_sync_done(ms, 0);
1572 * If metaslab_debug_load is set and we're initializing a metaslab
1573 * that has an allocated space map object then load the its space
1574 * map so that can verify frees.
1576 if (metaslab_debug_load && ms->ms_sm != NULL) {
1577 mutex_enter(&ms->ms_lock);
1578 VERIFY0(metaslab_load(ms));
1579 mutex_exit(&ms->ms_lock);
1583 vdev_dirty(vd, 0, NULL, txg);
1584 vdev_dirty(vd, VDD_METASLAB, ms, txg);
1593 metaslab_fini(metaslab_t *msp)
1595 metaslab_group_t *mg = msp->ms_group;
1597 metaslab_group_remove(mg, msp);
1599 mutex_enter(&msp->ms_lock);
1600 VERIFY(msp->ms_group == NULL);
1601 vdev_space_update(mg->mg_vd, -space_map_allocated(msp->ms_sm),
1603 space_map_close(msp->ms_sm);
1605 metaslab_unload(msp);
1606 range_tree_destroy(msp->ms_tree);
1607 range_tree_destroy(msp->ms_freeingtree);
1608 range_tree_destroy(msp->ms_freedtree);
1610 for (int t = 0; t < TXG_SIZE; t++) {
1611 range_tree_destroy(msp->ms_alloctree[t]);
1614 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1615 range_tree_destroy(msp->ms_defertree[t]);
1618 ASSERT0(msp->ms_deferspace);
1620 mutex_exit(&msp->ms_lock);
1621 cv_destroy(&msp->ms_load_cv);
1622 mutex_destroy(&msp->ms_lock);
1623 mutex_destroy(&msp->ms_sync_lock);
1625 kmem_free(msp, sizeof (metaslab_t));
1628 #define FRAGMENTATION_TABLE_SIZE 17
1631 * This table defines a segment size based fragmentation metric that will
1632 * allow each metaslab to derive its own fragmentation value. This is done
1633 * by calculating the space in each bucket of the spacemap histogram and
1634 * multiplying that by the fragmetation metric in this table. Doing
1635 * this for all buckets and dividing it by the total amount of free
1636 * space in this metaslab (i.e. the total free space in all buckets) gives
1637 * us the fragmentation metric. This means that a high fragmentation metric
1638 * equates to most of the free space being comprised of small segments.
1639 * Conversely, if the metric is low, then most of the free space is in
1640 * large segments. A 10% change in fragmentation equates to approximately
1641 * double the number of segments.
1643 * This table defines 0% fragmented space using 16MB segments. Testing has
1644 * shown that segments that are greater than or equal to 16MB do not suffer
1645 * from drastic performance problems. Using this value, we derive the rest
1646 * of the table. Since the fragmentation value is never stored on disk, it
1647 * is possible to change these calculations in the future.
1649 int zfs_frag_table[FRAGMENTATION_TABLE_SIZE] = {
1669 * Calclate the metaslab's fragmentation metric. A return value
1670 * of ZFS_FRAG_INVALID means that the metaslab has not been upgraded and does
1671 * not support this metric. Otherwise, the return value should be in the
1675 metaslab_set_fragmentation(metaslab_t *msp)
1677 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1678 uint64_t fragmentation = 0;
1680 boolean_t feature_enabled = spa_feature_is_enabled(spa,
1681 SPA_FEATURE_SPACEMAP_HISTOGRAM);
1683 if (!feature_enabled) {
1684 msp->ms_fragmentation = ZFS_FRAG_INVALID;
1689 * A null space map means that the entire metaslab is free
1690 * and thus is not fragmented.
1692 if (msp->ms_sm == NULL) {
1693 msp->ms_fragmentation = 0;
1698 * If this metaslab's space map has not been upgraded, flag it
1699 * so that we upgrade next time we encounter it.
1701 if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
1702 uint64_t txg = spa_syncing_txg(spa);
1703 vdev_t *vd = msp->ms_group->mg_vd;
1706 * If we've reached the final dirty txg, then we must
1707 * be shutting down the pool. We don't want to dirty
1708 * any data past this point so skip setting the condense
1709 * flag. We can retry this action the next time the pool
1712 if (spa_writeable(spa) && txg < spa_final_dirty_txg(spa)) {
1713 msp->ms_condense_wanted = B_TRUE;
1714 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
1715 spa_dbgmsg(spa, "txg %llu, requesting force condense: "
1716 "ms_id %llu, vdev_id %llu", txg, msp->ms_id,
1719 msp->ms_fragmentation = ZFS_FRAG_INVALID;
1723 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1725 uint8_t shift = msp->ms_sm->sm_shift;
1727 int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
1728 FRAGMENTATION_TABLE_SIZE - 1);
1730 if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
1733 space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
1736 ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
1737 fragmentation += space * zfs_frag_table[idx];
1741 fragmentation /= total;
1742 ASSERT3U(fragmentation, <=, 100);
1744 msp->ms_fragmentation = fragmentation;
1748 * Compute a weight -- a selection preference value -- for the given metaslab.
1749 * This is based on the amount of free space, the level of fragmentation,
1750 * the LBA range, and whether the metaslab is loaded.
1753 metaslab_space_weight(metaslab_t *msp)
1755 metaslab_group_t *mg = msp->ms_group;
1756 vdev_t *vd = mg->mg_vd;
1757 uint64_t weight, space;
1759 ASSERT(MUTEX_HELD(&msp->ms_lock));
1760 ASSERT(!vd->vdev_removing);
1763 * The baseline weight is the metaslab's free space.
1765 space = msp->ms_size - space_map_allocated(msp->ms_sm);
1767 if (metaslab_fragmentation_factor_enabled &&
1768 msp->ms_fragmentation != ZFS_FRAG_INVALID) {
1770 * Use the fragmentation information to inversely scale
1771 * down the baseline weight. We need to ensure that we
1772 * don't exclude this metaslab completely when it's 100%
1773 * fragmented. To avoid this we reduce the fragmented value
1776 space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
1779 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
1780 * this metaslab again. The fragmentation metric may have
1781 * decreased the space to something smaller than
1782 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
1783 * so that we can consume any remaining space.
1785 if (space > 0 && space < SPA_MINBLOCKSIZE)
1786 space = SPA_MINBLOCKSIZE;
1791 * Modern disks have uniform bit density and constant angular velocity.
1792 * Therefore, the outer recording zones are faster (higher bandwidth)
1793 * than the inner zones by the ratio of outer to inner track diameter,
1794 * which is typically around 2:1. We account for this by assigning
1795 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
1796 * In effect, this means that we'll select the metaslab with the most
1797 * free bandwidth rather than simply the one with the most free space.
1799 if (metaslab_lba_weighting_enabled) {
1800 weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
1801 ASSERT(weight >= space && weight <= 2 * space);
1805 * If this metaslab is one we're actively using, adjust its
1806 * weight to make it preferable to any inactive metaslab so
1807 * we'll polish it off. If the fragmentation on this metaslab
1808 * has exceed our threshold, then don't mark it active.
1810 if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
1811 msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
1812 weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
1815 WEIGHT_SET_SPACEBASED(weight);
1820 * Return the weight of the specified metaslab, according to the segment-based
1821 * weighting algorithm. The metaslab must be loaded. This function can
1822 * be called within a sync pass since it relies only on the metaslab's
1823 * range tree which is always accurate when the metaslab is loaded.
1826 metaslab_weight_from_range_tree(metaslab_t *msp)
1828 uint64_t weight = 0;
1829 uint32_t segments = 0;
1831 ASSERT(msp->ms_loaded);
1833 for (int i = RANGE_TREE_HISTOGRAM_SIZE - 1; i >= SPA_MINBLOCKSHIFT;
1835 uint8_t shift = msp->ms_group->mg_vd->vdev_ashift;
1836 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
1839 segments += msp->ms_tree->rt_histogram[i];
1842 * The range tree provides more precision than the space map
1843 * and must be downgraded so that all values fit within the
1844 * space map's histogram. This allows us to compare loaded
1845 * vs. unloaded metaslabs to determine which metaslab is
1846 * considered "best".
1851 if (segments != 0) {
1852 WEIGHT_SET_COUNT(weight, segments);
1853 WEIGHT_SET_INDEX(weight, i);
1854 WEIGHT_SET_ACTIVE(weight, 0);
1862 * Calculate the weight based on the on-disk histogram. This should only
1863 * be called after a sync pass has completely finished since the on-disk
1864 * information is updated in metaslab_sync().
1867 metaslab_weight_from_spacemap(metaslab_t *msp)
1869 uint64_t weight = 0;
1871 for (int i = SPACE_MAP_HISTOGRAM_SIZE - 1; i >= 0; i--) {
1872 if (msp->ms_sm->sm_phys->smp_histogram[i] != 0) {
1873 WEIGHT_SET_COUNT(weight,
1874 msp->ms_sm->sm_phys->smp_histogram[i]);
1875 WEIGHT_SET_INDEX(weight, i +
1876 msp->ms_sm->sm_shift);
1877 WEIGHT_SET_ACTIVE(weight, 0);
1885 * Compute a segment-based weight for the specified metaslab. The weight
1886 * is determined by highest bucket in the histogram. The information
1887 * for the highest bucket is encoded into the weight value.
1890 metaslab_segment_weight(metaslab_t *msp)
1892 metaslab_group_t *mg = msp->ms_group;
1893 uint64_t weight = 0;
1894 uint8_t shift = mg->mg_vd->vdev_ashift;
1896 ASSERT(MUTEX_HELD(&msp->ms_lock));
1899 * The metaslab is completely free.
1901 if (space_map_allocated(msp->ms_sm) == 0) {
1902 int idx = highbit64(msp->ms_size) - 1;
1903 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
1905 if (idx < max_idx) {
1906 WEIGHT_SET_COUNT(weight, 1ULL);
1907 WEIGHT_SET_INDEX(weight, idx);
1909 WEIGHT_SET_COUNT(weight, 1ULL << (idx - max_idx));
1910 WEIGHT_SET_INDEX(weight, max_idx);
1912 WEIGHT_SET_ACTIVE(weight, 0);
1913 ASSERT(!WEIGHT_IS_SPACEBASED(weight));
1918 ASSERT3U(msp->ms_sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
1921 * If the metaslab is fully allocated then just make the weight 0.
1923 if (space_map_allocated(msp->ms_sm) == msp->ms_size)
1926 * If the metaslab is already loaded, then use the range tree to
1927 * determine the weight. Otherwise, we rely on the space map information
1928 * to generate the weight.
1930 if (msp->ms_loaded) {
1931 weight = metaslab_weight_from_range_tree(msp);
1933 weight = metaslab_weight_from_spacemap(msp);
1937 * If the metaslab was active the last time we calculated its weight
1938 * then keep it active. We want to consume the entire region that
1939 * is associated with this weight.
1941 if (msp->ms_activation_weight != 0 && weight != 0)
1942 WEIGHT_SET_ACTIVE(weight, WEIGHT_GET_ACTIVE(msp->ms_weight));
1947 * Determine if we should attempt to allocate from this metaslab. If the
1948 * metaslab has a maximum size then we can quickly determine if the desired
1949 * allocation size can be satisfied. Otherwise, if we're using segment-based
1950 * weighting then we can determine the maximum allocation that this metaslab
1951 * can accommodate based on the index encoded in the weight. If we're using
1952 * space-based weights then rely on the entire weight (excluding the weight
1956 metaslab_should_allocate(metaslab_t *msp, uint64_t asize)
1958 boolean_t should_allocate;
1960 if (msp->ms_max_size != 0)
1961 return (msp->ms_max_size >= asize);
1963 if (!WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
1965 * The metaslab segment weight indicates segments in the
1966 * range [2^i, 2^(i+1)), where i is the index in the weight.
1967 * Since the asize might be in the middle of the range, we
1968 * should attempt the allocation if asize < 2^(i+1).
1970 should_allocate = (asize <
1971 1ULL << (WEIGHT_GET_INDEX(msp->ms_weight) + 1));
1973 should_allocate = (asize <=
1974 (msp->ms_weight & ~METASLAB_WEIGHT_TYPE));
1976 return (should_allocate);
1980 metaslab_weight(metaslab_t *msp)
1982 vdev_t *vd = msp->ms_group->mg_vd;
1983 spa_t *spa = vd->vdev_spa;
1986 ASSERT(MUTEX_HELD(&msp->ms_lock));
1989 * If this vdev is in the process of being removed, there is nothing
1990 * for us to do here.
1992 if (vd->vdev_removing)
1995 metaslab_set_fragmentation(msp);
1998 * Update the maximum size if the metaslab is loaded. This will
1999 * ensure that we get an accurate maximum size if newly freed space
2000 * has been added back into the free tree.
2003 msp->ms_max_size = metaslab_block_maxsize(msp);
2006 * Segment-based weighting requires space map histogram support.
2008 if (zfs_metaslab_segment_weight_enabled &&
2009 spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM) &&
2010 (msp->ms_sm == NULL || msp->ms_sm->sm_dbuf->db_size ==
2011 sizeof (space_map_phys_t))) {
2012 weight = metaslab_segment_weight(msp);
2014 weight = metaslab_space_weight(msp);
2020 metaslab_activate(metaslab_t *msp, uint64_t activation_weight)
2022 ASSERT(MUTEX_HELD(&msp->ms_lock));
2024 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
2025 metaslab_load_wait(msp);
2026 if (!msp->ms_loaded) {
2027 int error = metaslab_load(msp);
2029 metaslab_group_sort(msp->ms_group, msp, 0);
2034 msp->ms_activation_weight = msp->ms_weight;
2035 metaslab_group_sort(msp->ms_group, msp,
2036 msp->ms_weight | activation_weight);
2038 ASSERT(msp->ms_loaded);
2039 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
2045 metaslab_passivate(metaslab_t *msp, uint64_t weight)
2047 uint64_t size = weight & ~METASLAB_WEIGHT_TYPE;
2050 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
2051 * this metaslab again. In that case, it had better be empty,
2052 * or we would be leaving space on the table.
2054 ASSERT(size >= SPA_MINBLOCKSIZE ||
2055 range_tree_space(msp->ms_tree) == 0);
2056 ASSERT0(weight & METASLAB_ACTIVE_MASK);
2058 msp->ms_activation_weight = 0;
2059 metaslab_group_sort(msp->ms_group, msp, weight);
2060 ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
2064 * Segment-based metaslabs are activated once and remain active until
2065 * we either fail an allocation attempt (similar to space-based metaslabs)
2066 * or have exhausted the free space in zfs_metaslab_switch_threshold
2067 * buckets since the metaslab was activated. This function checks to see
2068 * if we've exhaused the zfs_metaslab_switch_threshold buckets in the
2069 * metaslab and passivates it proactively. This will allow us to select a
2070 * metaslabs with larger contiguous region if any remaining within this
2071 * metaslab group. If we're in sync pass > 1, then we continue using this
2072 * metaslab so that we don't dirty more block and cause more sync passes.
2075 metaslab_segment_may_passivate(metaslab_t *msp)
2077 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2079 if (WEIGHT_IS_SPACEBASED(msp->ms_weight) || spa_sync_pass(spa) > 1)
2083 * Since we are in the middle of a sync pass, the most accurate
2084 * information that is accessible to us is the in-core range tree
2085 * histogram; calculate the new weight based on that information.
2087 uint64_t weight = metaslab_weight_from_range_tree(msp);
2088 int activation_idx = WEIGHT_GET_INDEX(msp->ms_activation_weight);
2089 int current_idx = WEIGHT_GET_INDEX(weight);
2091 if (current_idx <= activation_idx - zfs_metaslab_switch_threshold)
2092 metaslab_passivate(msp, weight);
2096 metaslab_preload(void *arg)
2098 metaslab_t *msp = arg;
2099 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2101 ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
2103 mutex_enter(&msp->ms_lock);
2104 metaslab_load_wait(msp);
2105 if (!msp->ms_loaded)
2106 (void) metaslab_load(msp);
2107 msp->ms_selected_txg = spa_syncing_txg(spa);
2108 mutex_exit(&msp->ms_lock);
2112 metaslab_group_preload(metaslab_group_t *mg)
2114 spa_t *spa = mg->mg_vd->vdev_spa;
2116 avl_tree_t *t = &mg->mg_metaslab_tree;
2119 if (spa_shutting_down(spa) || !metaslab_preload_enabled) {
2120 taskq_wait(mg->mg_taskq);
2124 mutex_enter(&mg->mg_lock);
2127 * Load the next potential metaslabs
2129 for (msp = avl_first(t); msp != NULL; msp = AVL_NEXT(t, msp)) {
2130 ASSERT3P(msp->ms_group, ==, mg);
2133 * We preload only the maximum number of metaslabs specified
2134 * by metaslab_preload_limit. If a metaslab is being forced
2135 * to condense then we preload it too. This will ensure
2136 * that force condensing happens in the next txg.
2138 if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
2142 VERIFY(taskq_dispatch(mg->mg_taskq, metaslab_preload,
2143 msp, TQ_SLEEP) != 0);
2145 mutex_exit(&mg->mg_lock);
2149 * Determine if the space map's on-disk footprint is past our tolerance
2150 * for inefficiency. We would like to use the following criteria to make
2153 * 1. The size of the space map object should not dramatically increase as a
2154 * result of writing out the free space range tree.
2156 * 2. The minimal on-disk space map representation is zfs_condense_pct/100
2157 * times the size than the free space range tree representation
2158 * (i.e. zfs_condense_pct = 110 and in-core = 1MB, minimal = 1.1MB).
2160 * 3. The on-disk size of the space map should actually decrease.
2162 * Checking the first condition is tricky since we don't want to walk
2163 * the entire AVL tree calculating the estimated on-disk size. Instead we
2164 * use the size-ordered range tree in the metaslab and calculate the
2165 * size required to write out the largest segment in our free tree. If the
2166 * size required to represent that segment on disk is larger than the space
2167 * map object then we avoid condensing this map.
2169 * To determine the second criterion we use a best-case estimate and assume
2170 * each segment can be represented on-disk as a single 64-bit entry. We refer
2171 * to this best-case estimate as the space map's minimal form.
2173 * Unfortunately, we cannot compute the on-disk size of the space map in this
2174 * context because we cannot accurately compute the effects of compression, etc.
2175 * Instead, we apply the heuristic described in the block comment for
2176 * zfs_metaslab_condense_block_threshold - we only condense if the space used
2177 * is greater than a threshold number of blocks.
2180 metaslab_should_condense(metaslab_t *msp)
2182 space_map_t *sm = msp->ms_sm;
2184 uint64_t size, entries, segsz, object_size, optimal_size, record_size;
2185 dmu_object_info_t doi;
2186 uint64_t vdev_blocksize = 1 << msp->ms_group->mg_vd->vdev_ashift;
2188 ASSERT(MUTEX_HELD(&msp->ms_lock));
2189 ASSERT(msp->ms_loaded);
2192 * Use the ms_size_tree range tree, which is ordered by size, to
2193 * obtain the largest segment in the free tree. We always condense
2194 * metaslabs that are empty and metaslabs for which a condense
2195 * request has been made.
2197 rs = avl_last(&msp->ms_size_tree);
2198 if (rs == NULL || msp->ms_condense_wanted)
2202 * Calculate the number of 64-bit entries this segment would
2203 * require when written to disk. If this single segment would be
2204 * larger on-disk than the entire current on-disk structure, then
2205 * clearly condensing will increase the on-disk structure size.
2207 size = (rs->rs_end - rs->rs_start) >> sm->sm_shift;
2208 entries = size / (MIN(size, SM_RUN_MAX));
2209 segsz = entries * sizeof (uint64_t);
2211 optimal_size = sizeof (uint64_t) * avl_numnodes(&msp->ms_tree->rt_root);
2212 object_size = space_map_length(msp->ms_sm);
2214 dmu_object_info_from_db(sm->sm_dbuf, &doi);
2215 record_size = MAX(doi.doi_data_block_size, vdev_blocksize);
2217 return (segsz <= object_size &&
2218 object_size >= (optimal_size * zfs_condense_pct / 100) &&
2219 object_size > zfs_metaslab_condense_block_threshold * record_size);
2223 * Condense the on-disk space map representation to its minimized form.
2224 * The minimized form consists of a small number of allocations followed by
2225 * the entries of the free range tree.
2228 metaslab_condense(metaslab_t *msp, uint64_t txg, dmu_tx_t *tx)
2230 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2231 range_tree_t *condense_tree;
2232 space_map_t *sm = msp->ms_sm;
2234 ASSERT(MUTEX_HELD(&msp->ms_lock));
2235 ASSERT3U(spa_sync_pass(spa), ==, 1);
2236 ASSERT(msp->ms_loaded);
2239 spa_dbgmsg(spa, "condensing: txg %llu, msp[%llu] %p, vdev id %llu, "
2240 "spa %s, smp size %llu, segments %lu, forcing condense=%s", txg,
2241 msp->ms_id, msp, msp->ms_group->mg_vd->vdev_id,
2242 msp->ms_group->mg_vd->vdev_spa->spa_name,
2243 space_map_length(msp->ms_sm), avl_numnodes(&msp->ms_tree->rt_root),
2244 msp->ms_condense_wanted ? "TRUE" : "FALSE");
2246 msp->ms_condense_wanted = B_FALSE;
2249 * Create an range tree that is 100% allocated. We remove segments
2250 * that have been freed in this txg, any deferred frees that exist,
2251 * and any allocation in the future. Removing segments should be
2252 * a relatively inexpensive operation since we expect these trees to
2253 * have a small number of nodes.
2255 condense_tree = range_tree_create(NULL, NULL);
2256 range_tree_add(condense_tree, msp->ms_start, msp->ms_size);
2259 * Remove what's been freed in this txg from the condense_tree.
2260 * Since we're in sync_pass 1, we know that all the frees from
2261 * this txg are in the freeingtree.
2263 range_tree_walk(msp->ms_freeingtree, range_tree_remove, condense_tree);
2265 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2266 range_tree_walk(msp->ms_defertree[t],
2267 range_tree_remove, condense_tree);
2270 for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
2271 range_tree_walk(msp->ms_alloctree[(txg + t) & TXG_MASK],
2272 range_tree_remove, condense_tree);
2276 * We're about to drop the metaslab's lock thus allowing
2277 * other consumers to change it's content. Set the
2278 * metaslab's ms_condensing flag to ensure that
2279 * allocations on this metaslab do not occur while we're
2280 * in the middle of committing it to disk. This is only critical
2281 * for the ms_tree as all other range trees use per txg
2282 * views of their content.
2284 msp->ms_condensing = B_TRUE;
2286 mutex_exit(&msp->ms_lock);
2287 space_map_truncate(sm, tx);
2290 * While we would ideally like to create a space map representation
2291 * that consists only of allocation records, doing so can be
2292 * prohibitively expensive because the in-core free tree can be
2293 * large, and therefore computationally expensive to subtract
2294 * from the condense_tree. Instead we sync out two trees, a cheap
2295 * allocation only tree followed by the in-core free tree. While not
2296 * optimal, this is typically close to optimal, and much cheaper to
2299 space_map_write(sm, condense_tree, SM_ALLOC, tx);
2300 range_tree_vacate(condense_tree, NULL, NULL);
2301 range_tree_destroy(condense_tree);
2303 space_map_write(sm, msp->ms_tree, SM_FREE, tx);
2304 mutex_enter(&msp->ms_lock);
2305 msp->ms_condensing = B_FALSE;
2309 * Write a metaslab to disk in the context of the specified transaction group.
2312 metaslab_sync(metaslab_t *msp, uint64_t txg)
2314 metaslab_group_t *mg = msp->ms_group;
2315 vdev_t *vd = mg->mg_vd;
2316 spa_t *spa = vd->vdev_spa;
2317 objset_t *mos = spa_meta_objset(spa);
2318 range_tree_t *alloctree = msp->ms_alloctree[txg & TXG_MASK];
2320 uint64_t object = space_map_object(msp->ms_sm);
2322 ASSERT(!vd->vdev_ishole);
2325 * This metaslab has just been added so there's no work to do now.
2327 if (msp->ms_freeingtree == NULL) {
2328 ASSERT3P(alloctree, ==, NULL);
2332 ASSERT3P(alloctree, !=, NULL);
2333 ASSERT3P(msp->ms_freeingtree, !=, NULL);
2334 ASSERT3P(msp->ms_freedtree, !=, NULL);
2337 * Normally, we don't want to process a metaslab if there
2338 * are no allocations or frees to perform. However, if the metaslab
2339 * is being forced to condense and it's loaded, we need to let it
2342 if (range_tree_space(alloctree) == 0 &&
2343 range_tree_space(msp->ms_freeingtree) == 0 &&
2344 !(msp->ms_loaded && msp->ms_condense_wanted))
2348 VERIFY(txg <= spa_final_dirty_txg(spa));
2351 * The only state that can actually be changing concurrently with
2352 * metaslab_sync() is the metaslab's ms_tree. No other thread can
2353 * be modifying this txg's alloctree, freeingtree, freedtree, or
2354 * space_map_phys_t. We drop ms_lock whenever we could call
2355 * into the DMU, because the DMU can call down to us
2356 * (e.g. via zio_free()) at any time.
2358 * The spa_vdev_remove_thread() can be reading metaslab state
2359 * concurrently, and it is locked out by the ms_sync_lock. Note
2360 * that the ms_lock is insufficient for this, because it is dropped
2361 * by space_map_write().
2364 tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
2366 if (msp->ms_sm == NULL) {
2367 uint64_t new_object;
2369 new_object = space_map_alloc(mos, tx);
2370 VERIFY3U(new_object, !=, 0);
2372 VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
2373 msp->ms_start, msp->ms_size, vd->vdev_ashift));
2374 ASSERT(msp->ms_sm != NULL);
2377 mutex_enter(&msp->ms_sync_lock);
2378 mutex_enter(&msp->ms_lock);
2381 * Note: metaslab_condense() clears the space map's histogram.
2382 * Therefore we must verify and remove this histogram before
2385 metaslab_group_histogram_verify(mg);
2386 metaslab_class_histogram_verify(mg->mg_class);
2387 metaslab_group_histogram_remove(mg, msp);
2389 if (msp->ms_loaded && spa_sync_pass(spa) == 1 &&
2390 metaslab_should_condense(msp)) {
2391 metaslab_condense(msp, txg, tx);
2393 mutex_exit(&msp->ms_lock);
2394 space_map_write(msp->ms_sm, alloctree, SM_ALLOC, tx);
2395 space_map_write(msp->ms_sm, msp->ms_freeingtree, SM_FREE, tx);
2396 mutex_enter(&msp->ms_lock);
2399 if (msp->ms_loaded) {
2401 * When the space map is loaded, we have an accurate
2402 * histogram in the range tree. This gives us an opportunity
2403 * to bring the space map's histogram up-to-date so we clear
2404 * it first before updating it.
2406 space_map_histogram_clear(msp->ms_sm);
2407 space_map_histogram_add(msp->ms_sm, msp->ms_tree, tx);
2410 * Since we've cleared the histogram we need to add back
2411 * any free space that has already been processed, plus
2412 * any deferred space. This allows the on-disk histogram
2413 * to accurately reflect all free space even if some space
2414 * is not yet available for allocation (i.e. deferred).
2416 space_map_histogram_add(msp->ms_sm, msp->ms_freedtree, tx);
2419 * Add back any deferred free space that has not been
2420 * added back into the in-core free tree yet. This will
2421 * ensure that we don't end up with a space map histogram
2422 * that is completely empty unless the metaslab is fully
2425 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2426 space_map_histogram_add(msp->ms_sm,
2427 msp->ms_defertree[t], tx);
2432 * Always add the free space from this sync pass to the space
2433 * map histogram. We want to make sure that the on-disk histogram
2434 * accounts for all free space. If the space map is not loaded,
2435 * then we will lose some accuracy but will correct it the next
2436 * time we load the space map.
2438 space_map_histogram_add(msp->ms_sm, msp->ms_freeingtree, tx);
2440 metaslab_group_histogram_add(mg, msp);
2441 metaslab_group_histogram_verify(mg);
2442 metaslab_class_histogram_verify(mg->mg_class);
2445 * For sync pass 1, we avoid traversing this txg's free range tree
2446 * and instead will just swap the pointers for freeingtree and
2447 * freedtree. We can safely do this since the freed_tree is
2448 * guaranteed to be empty on the initial pass.
2450 if (spa_sync_pass(spa) == 1) {
2451 range_tree_swap(&msp->ms_freeingtree, &msp->ms_freedtree);
2453 range_tree_vacate(msp->ms_freeingtree,
2454 range_tree_add, msp->ms_freedtree);
2456 range_tree_vacate(alloctree, NULL, NULL);
2458 ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
2459 ASSERT0(range_tree_space(msp->ms_alloctree[TXG_CLEAN(txg) & TXG_MASK]));
2460 ASSERT0(range_tree_space(msp->ms_freeingtree));
2462 mutex_exit(&msp->ms_lock);
2464 if (object != space_map_object(msp->ms_sm)) {
2465 object = space_map_object(msp->ms_sm);
2466 dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
2467 msp->ms_id, sizeof (uint64_t), &object, tx);
2469 mutex_exit(&msp->ms_sync_lock);
2474 * Called after a transaction group has completely synced to mark
2475 * all of the metaslab's free space as usable.
2478 metaslab_sync_done(metaslab_t *msp, uint64_t txg)
2480 metaslab_group_t *mg = msp->ms_group;
2481 vdev_t *vd = mg->mg_vd;
2482 spa_t *spa = vd->vdev_spa;
2483 range_tree_t **defer_tree;
2484 int64_t alloc_delta, defer_delta;
2485 boolean_t defer_allowed = B_TRUE;
2487 ASSERT(!vd->vdev_ishole);
2489 mutex_enter(&msp->ms_lock);
2492 * If this metaslab is just becoming available, initialize its
2493 * range trees and add its capacity to the vdev.
2495 if (msp->ms_freedtree == NULL) {
2496 for (int t = 0; t < TXG_SIZE; t++) {
2497 ASSERT(msp->ms_alloctree[t] == NULL);
2499 msp->ms_alloctree[t] = range_tree_create(NULL, NULL);
2502 ASSERT3P(msp->ms_freeingtree, ==, NULL);
2503 msp->ms_freeingtree = range_tree_create(NULL, NULL);
2505 ASSERT3P(msp->ms_freedtree, ==, NULL);
2506 msp->ms_freedtree = range_tree_create(NULL, NULL);
2508 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2509 ASSERT(msp->ms_defertree[t] == NULL);
2511 msp->ms_defertree[t] = range_tree_create(NULL, NULL);
2514 vdev_space_update(vd, 0, 0, msp->ms_size);
2517 defer_tree = &msp->ms_defertree[txg % TXG_DEFER_SIZE];
2519 uint64_t free_space = metaslab_class_get_space(spa_normal_class(spa)) -
2520 metaslab_class_get_alloc(spa_normal_class(spa));
2521 if (free_space <= spa_get_slop_space(spa) || vd->vdev_removing) {
2522 defer_allowed = B_FALSE;
2526 alloc_delta = space_map_alloc_delta(msp->ms_sm);
2527 if (defer_allowed) {
2528 defer_delta = range_tree_space(msp->ms_freedtree) -
2529 range_tree_space(*defer_tree);
2531 defer_delta -= range_tree_space(*defer_tree);
2534 vdev_space_update(vd, alloc_delta + defer_delta, defer_delta, 0);
2537 * If there's a metaslab_load() in progress, wait for it to complete
2538 * so that we have a consistent view of the in-core space map.
2540 metaslab_load_wait(msp);
2543 * Move the frees from the defer_tree back to the free
2544 * range tree (if it's loaded). Swap the freed_tree and the
2545 * defer_tree -- this is safe to do because we've just emptied out
2548 range_tree_vacate(*defer_tree,
2549 msp->ms_loaded ? range_tree_add : NULL, msp->ms_tree);
2550 if (defer_allowed) {
2551 range_tree_swap(&msp->ms_freedtree, defer_tree);
2553 range_tree_vacate(msp->ms_freedtree,
2554 msp->ms_loaded ? range_tree_add : NULL, msp->ms_tree);
2557 space_map_update(msp->ms_sm);
2559 msp->ms_deferspace += defer_delta;
2560 ASSERT3S(msp->ms_deferspace, >=, 0);
2561 ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
2562 if (msp->ms_deferspace != 0) {
2564 * Keep syncing this metaslab until all deferred frees
2565 * are back in circulation.
2567 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
2571 * Calculate the new weights before unloading any metaslabs.
2572 * This will give us the most accurate weighting.
2574 metaslab_group_sort(mg, msp, metaslab_weight(msp));
2577 * If the metaslab is loaded and we've not tried to load or allocate
2578 * from it in 'metaslab_unload_delay' txgs, then unload it.
2580 if (msp->ms_loaded &&
2581 msp->ms_selected_txg + metaslab_unload_delay < txg) {
2582 for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
2583 VERIFY0(range_tree_space(
2584 msp->ms_alloctree[(txg + t) & TXG_MASK]));
2587 if (!metaslab_debug_unload)
2588 metaslab_unload(msp);
2591 ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
2592 ASSERT0(range_tree_space(msp->ms_freeingtree));
2593 ASSERT0(range_tree_space(msp->ms_freedtree));
2595 mutex_exit(&msp->ms_lock);
2599 metaslab_sync_reassess(metaslab_group_t *mg)
2601 spa_t *spa = mg->mg_class->mc_spa;
2603 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
2604 metaslab_group_alloc_update(mg);
2605 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
2608 * Preload the next potential metaslabs but only on active
2609 * metaslab groups. We can get into a state where the metaslab
2610 * is no longer active since we dirty metaslabs as we remove a
2611 * a device, thus potentially making the metaslab group eligible
2614 if (mg->mg_activation_count > 0) {
2615 metaslab_group_preload(mg);
2617 spa_config_exit(spa, SCL_ALLOC, FTAG);
2621 metaslab_distance(metaslab_t *msp, dva_t *dva)
2623 uint64_t ms_shift = msp->ms_group->mg_vd->vdev_ms_shift;
2624 uint64_t offset = DVA_GET_OFFSET(dva) >> ms_shift;
2625 uint64_t start = msp->ms_id;
2627 if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
2628 return (1ULL << 63);
2631 return ((start - offset) << ms_shift);
2633 return ((offset - start) << ms_shift);
2638 * ==========================================================================
2639 * Metaslab allocation tracing facility
2640 * ==========================================================================
2642 kstat_t *metaslab_trace_ksp;
2643 kstat_named_t metaslab_trace_over_limit;
2646 metaslab_alloc_trace_init(void)
2648 ASSERT(metaslab_alloc_trace_cache == NULL);
2649 metaslab_alloc_trace_cache = kmem_cache_create(
2650 "metaslab_alloc_trace_cache", sizeof (metaslab_alloc_trace_t),
2651 0, NULL, NULL, NULL, NULL, NULL, 0);
2652 metaslab_trace_ksp = kstat_create("zfs", 0, "metaslab_trace_stats",
2653 "misc", KSTAT_TYPE_NAMED, 1, KSTAT_FLAG_VIRTUAL);
2654 if (metaslab_trace_ksp != NULL) {
2655 metaslab_trace_ksp->ks_data = &metaslab_trace_over_limit;
2656 kstat_named_init(&metaslab_trace_over_limit,
2657 "metaslab_trace_over_limit", KSTAT_DATA_UINT64);
2658 kstat_install(metaslab_trace_ksp);
2663 metaslab_alloc_trace_fini(void)
2665 if (metaslab_trace_ksp != NULL) {
2666 kstat_delete(metaslab_trace_ksp);
2667 metaslab_trace_ksp = NULL;
2669 kmem_cache_destroy(metaslab_alloc_trace_cache);
2670 metaslab_alloc_trace_cache = NULL;
2674 * Add an allocation trace element to the allocation tracing list.
2677 metaslab_trace_add(zio_alloc_list_t *zal, metaslab_group_t *mg,
2678 metaslab_t *msp, uint64_t psize, uint32_t dva_id, uint64_t offset)
2680 if (!metaslab_trace_enabled)
2684 * When the tracing list reaches its maximum we remove
2685 * the second element in the list before adding a new one.
2686 * By removing the second element we preserve the original
2687 * entry as a clue to what allocations steps have already been
2690 if (zal->zal_size == metaslab_trace_max_entries) {
2691 metaslab_alloc_trace_t *mat_next;
2693 panic("too many entries in allocation list");
2695 atomic_inc_64(&metaslab_trace_over_limit.value.ui64);
2697 mat_next = list_next(&zal->zal_list, list_head(&zal->zal_list));
2698 list_remove(&zal->zal_list, mat_next);
2699 kmem_cache_free(metaslab_alloc_trace_cache, mat_next);
2702 metaslab_alloc_trace_t *mat =
2703 kmem_cache_alloc(metaslab_alloc_trace_cache, KM_SLEEP);
2704 list_link_init(&mat->mat_list_node);
2707 mat->mat_size = psize;
2708 mat->mat_dva_id = dva_id;
2709 mat->mat_offset = offset;
2710 mat->mat_weight = 0;
2713 mat->mat_weight = msp->ms_weight;
2716 * The list is part of the zio so locking is not required. Only
2717 * a single thread will perform allocations for a given zio.
2719 list_insert_tail(&zal->zal_list, mat);
2722 ASSERT3U(zal->zal_size, <=, metaslab_trace_max_entries);
2726 metaslab_trace_init(zio_alloc_list_t *zal)
2728 list_create(&zal->zal_list, sizeof (metaslab_alloc_trace_t),
2729 offsetof(metaslab_alloc_trace_t, mat_list_node));
2734 metaslab_trace_fini(zio_alloc_list_t *zal)
2736 metaslab_alloc_trace_t *mat;
2738 while ((mat = list_remove_head(&zal->zal_list)) != NULL)
2739 kmem_cache_free(metaslab_alloc_trace_cache, mat);
2740 list_destroy(&zal->zal_list);
2745 * ==========================================================================
2746 * Metaslab block operations
2747 * ==========================================================================
2751 metaslab_group_alloc_increment(spa_t *spa, uint64_t vdev, void *tag, int flags)
2753 if (!(flags & METASLAB_ASYNC_ALLOC) ||
2754 flags & METASLAB_DONT_THROTTLE)
2757 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
2758 if (!mg->mg_class->mc_alloc_throttle_enabled)
2761 (void) refcount_add(&mg->mg_alloc_queue_depth, tag);
2765 metaslab_group_alloc_decrement(spa_t *spa, uint64_t vdev, void *tag, int flags)
2767 if (!(flags & METASLAB_ASYNC_ALLOC) ||
2768 flags & METASLAB_DONT_THROTTLE)
2771 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
2772 if (!mg->mg_class->mc_alloc_throttle_enabled)
2775 (void) refcount_remove(&mg->mg_alloc_queue_depth, tag);
2779 metaslab_group_alloc_verify(spa_t *spa, const blkptr_t *bp, void *tag)
2782 const dva_t *dva = bp->blk_dva;
2783 int ndvas = BP_GET_NDVAS(bp);
2785 for (int d = 0; d < ndvas; d++) {
2786 uint64_t vdev = DVA_GET_VDEV(&dva[d]);
2787 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
2788 VERIFY(refcount_not_held(&mg->mg_alloc_queue_depth, tag));
2794 metaslab_block_alloc(metaslab_t *msp, uint64_t size, uint64_t txg)
2797 range_tree_t *rt = msp->ms_tree;
2798 metaslab_class_t *mc = msp->ms_group->mg_class;
2800 VERIFY(!msp->ms_condensing);
2802 start = mc->mc_ops->msop_alloc(msp, size);
2803 if (start != -1ULL) {
2804 metaslab_group_t *mg = msp->ms_group;
2805 vdev_t *vd = mg->mg_vd;
2807 VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
2808 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
2809 VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
2810 range_tree_remove(rt, start, size);
2812 if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
2813 vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
2815 range_tree_add(msp->ms_alloctree[txg & TXG_MASK], start, size);
2817 /* Track the last successful allocation */
2818 msp->ms_alloc_txg = txg;
2819 metaslab_verify_space(msp, txg);
2823 * Now that we've attempted the allocation we need to update the
2824 * metaslab's maximum block size since it may have changed.
2826 msp->ms_max_size = metaslab_block_maxsize(msp);
2831 metaslab_group_alloc_normal(metaslab_group_t *mg, zio_alloc_list_t *zal,
2832 uint64_t asize, uint64_t txg, uint64_t min_distance, dva_t *dva, int d)
2834 metaslab_t *msp = NULL;
2835 uint64_t offset = -1ULL;
2836 uint64_t activation_weight;
2837 uint64_t target_distance;
2840 activation_weight = METASLAB_WEIGHT_PRIMARY;
2841 for (i = 0; i < d; i++) {
2842 if (DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
2843 activation_weight = METASLAB_WEIGHT_SECONDARY;
2848 metaslab_t *search = kmem_alloc(sizeof (*search), KM_SLEEP);
2849 search->ms_weight = UINT64_MAX;
2850 search->ms_start = 0;
2852 boolean_t was_active;
2853 avl_tree_t *t = &mg->mg_metaslab_tree;
2856 mutex_enter(&mg->mg_lock);
2859 * Find the metaslab with the highest weight that is less
2860 * than what we've already tried. In the common case, this
2861 * means that we will examine each metaslab at most once.
2862 * Note that concurrent callers could reorder metaslabs
2863 * by activation/passivation once we have dropped the mg_lock.
2864 * If a metaslab is activated by another thread, and we fail
2865 * to allocate from the metaslab we have selected, we may
2866 * not try the newly-activated metaslab, and instead activate
2867 * another metaslab. This is not optimal, but generally
2868 * does not cause any problems (a possible exception being
2869 * if every metaslab is completely full except for the
2870 * the newly-activated metaslab which we fail to examine).
2872 msp = avl_find(t, search, &idx);
2874 msp = avl_nearest(t, idx, AVL_AFTER);
2875 for (; msp != NULL; msp = AVL_NEXT(t, msp)) {
2877 if (!metaslab_should_allocate(msp, asize)) {
2878 metaslab_trace_add(zal, mg, msp, asize, d,
2884 * If the selected metaslab is condensing, skip it.
2886 if (msp->ms_condensing)
2889 was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
2890 if (activation_weight == METASLAB_WEIGHT_PRIMARY)
2893 target_distance = min_distance +
2894 (space_map_allocated(msp->ms_sm) != 0 ? 0 :
2897 for (i = 0; i < d; i++) {
2898 if (metaslab_distance(msp, &dva[i]) <
2905 mutex_exit(&mg->mg_lock);
2907 kmem_free(search, sizeof (*search));
2910 search->ms_weight = msp->ms_weight;
2911 search->ms_start = msp->ms_start + 1;
2913 mutex_enter(&msp->ms_lock);
2916 * Ensure that the metaslab we have selected is still
2917 * capable of handling our request. It's possible that
2918 * another thread may have changed the weight while we
2919 * were blocked on the metaslab lock. We check the
2920 * active status first to see if we need to reselect
2923 if (was_active && !(msp->ms_weight & METASLAB_ACTIVE_MASK)) {
2924 mutex_exit(&msp->ms_lock);
2928 if ((msp->ms_weight & METASLAB_WEIGHT_SECONDARY) &&
2929 activation_weight == METASLAB_WEIGHT_PRIMARY) {
2930 metaslab_passivate(msp,
2931 msp->ms_weight & ~METASLAB_ACTIVE_MASK);
2932 mutex_exit(&msp->ms_lock);
2936 if (metaslab_activate(msp, activation_weight) != 0) {
2937 mutex_exit(&msp->ms_lock);
2940 msp->ms_selected_txg = txg;
2943 * Now that we have the lock, recheck to see if we should
2944 * continue to use this metaslab for this allocation. The
2945 * the metaslab is now loaded so metaslab_should_allocate() can
2946 * accurately determine if the allocation attempt should
2949 if (!metaslab_should_allocate(msp, asize)) {
2950 /* Passivate this metaslab and select a new one. */
2951 metaslab_trace_add(zal, mg, msp, asize, d,
2957 * If this metaslab is currently condensing then pick again as
2958 * we can't manipulate this metaslab until it's committed
2961 if (msp->ms_condensing) {
2962 metaslab_trace_add(zal, mg, msp, asize, d,
2964 mutex_exit(&msp->ms_lock);
2968 offset = metaslab_block_alloc(msp, asize, txg);
2969 metaslab_trace_add(zal, mg, msp, asize, d, offset);
2971 if (offset != -1ULL) {
2972 /* Proactively passivate the metaslab, if needed */
2973 metaslab_segment_may_passivate(msp);
2977 ASSERT(msp->ms_loaded);
2980 * We were unable to allocate from this metaslab so determine
2981 * a new weight for this metaslab. Now that we have loaded
2982 * the metaslab we can provide a better hint to the metaslab
2985 * For space-based metaslabs, we use the maximum block size.
2986 * This information is only available when the metaslab
2987 * is loaded and is more accurate than the generic free
2988 * space weight that was calculated by metaslab_weight().
2989 * This information allows us to quickly compare the maximum
2990 * available allocation in the metaslab to the allocation
2991 * size being requested.
2993 * For segment-based metaslabs, determine the new weight
2994 * based on the highest bucket in the range tree. We
2995 * explicitly use the loaded segment weight (i.e. the range
2996 * tree histogram) since it contains the space that is
2997 * currently available for allocation and is accurate
2998 * even within a sync pass.
3000 if (WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
3001 uint64_t weight = metaslab_block_maxsize(msp);
3002 WEIGHT_SET_SPACEBASED(weight);
3003 metaslab_passivate(msp, weight);
3005 metaslab_passivate(msp,
3006 metaslab_weight_from_range_tree(msp));
3010 * We have just failed an allocation attempt, check
3011 * that metaslab_should_allocate() agrees. Otherwise,
3012 * we may end up in an infinite loop retrying the same
3015 ASSERT(!metaslab_should_allocate(msp, asize));
3016 mutex_exit(&msp->ms_lock);
3018 mutex_exit(&msp->ms_lock);
3019 kmem_free(search, sizeof (*search));
3024 metaslab_group_alloc(metaslab_group_t *mg, zio_alloc_list_t *zal,
3025 uint64_t asize, uint64_t txg, uint64_t min_distance, dva_t *dva, int d)
3028 ASSERT(mg->mg_initialized);
3030 offset = metaslab_group_alloc_normal(mg, zal, asize, txg,
3031 min_distance, dva, d);
3033 mutex_enter(&mg->mg_lock);
3034 if (offset == -1ULL) {
3035 mg->mg_failed_allocations++;
3036 metaslab_trace_add(zal, mg, NULL, asize, d,
3037 TRACE_GROUP_FAILURE);
3038 if (asize == SPA_GANGBLOCKSIZE) {
3040 * This metaslab group was unable to allocate
3041 * the minimum gang block size so it must be out of
3042 * space. We must notify the allocation throttle
3043 * to start skipping allocation attempts to this
3044 * metaslab group until more space becomes available.
3045 * Note: this failure cannot be caused by the
3046 * allocation throttle since the allocation throttle
3047 * is only responsible for skipping devices and
3048 * not failing block allocations.
3050 mg->mg_no_free_space = B_TRUE;
3053 mg->mg_allocations++;
3054 mutex_exit(&mg->mg_lock);
3059 * If we have to write a ditto block (i.e. more than one DVA for a given BP)
3060 * on the same vdev as an existing DVA of this BP, then try to allocate it
3061 * at least (vdev_asize / (2 ^ ditto_same_vdev_distance_shift)) away from the
3064 int ditto_same_vdev_distance_shift = 3;
3067 * Allocate a block for the specified i/o.
3070 metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
3071 dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags,
3072 zio_alloc_list_t *zal)
3074 metaslab_group_t *mg, *rotor;
3076 boolean_t try_hard = B_FALSE;
3078 ASSERT(!DVA_IS_VALID(&dva[d]));
3081 * For testing, make some blocks above a certain size be gang blocks.
3083 if (psize >= metaslab_gang_bang && (ddi_get_lbolt() & 3) == 0) {
3084 metaslab_trace_add(zal, NULL, NULL, psize, d, TRACE_FORCE_GANG);
3085 return (SET_ERROR(ENOSPC));
3089 * Start at the rotor and loop through all mgs until we find something.
3090 * Note that there's no locking on mc_rotor or mc_aliquot because
3091 * nothing actually breaks if we miss a few updates -- we just won't
3092 * allocate quite as evenly. It all balances out over time.
3094 * If we are doing ditto or log blocks, try to spread them across
3095 * consecutive vdevs. If we're forced to reuse a vdev before we've
3096 * allocated all of our ditto blocks, then try and spread them out on
3097 * that vdev as much as possible. If it turns out to not be possible,
3098 * gradually lower our standards until anything becomes acceptable.
3099 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
3100 * gives us hope of containing our fault domains to something we're
3101 * able to reason about. Otherwise, any two top-level vdev failures
3102 * will guarantee the loss of data. With consecutive allocation,
3103 * only two adjacent top-level vdev failures will result in data loss.
3105 * If we are doing gang blocks (hintdva is non-NULL), try to keep
3106 * ourselves on the same vdev as our gang block header. That
3107 * way, we can hope for locality in vdev_cache, plus it makes our
3108 * fault domains something tractable.
3111 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
3114 * It's possible the vdev we're using as the hint no
3115 * longer exists or its mg has been closed (e.g. by
3116 * device removal). Consult the rotor when
3119 if (vd != NULL && vd->vdev_mg != NULL) {
3122 if (flags & METASLAB_HINTBP_AVOID &&
3123 mg->mg_next != NULL)
3128 } else if (d != 0) {
3129 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
3130 mg = vd->vdev_mg->mg_next;
3136 * If the hint put us into the wrong metaslab class, or into a
3137 * metaslab group that has been passivated, just follow the rotor.
3139 if (mg->mg_class != mc || mg->mg_activation_count <= 0)
3145 boolean_t allocatable;
3147 ASSERT(mg->mg_activation_count == 1);
3151 * Don't allocate from faulted devices.
3154 spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
3155 allocatable = vdev_allocatable(vd);
3156 spa_config_exit(spa, SCL_ZIO, FTAG);
3158 allocatable = vdev_allocatable(vd);
3162 * Determine if the selected metaslab group is eligible
3163 * for allocations. If we're ganging then don't allow
3164 * this metaslab group to skip allocations since that would
3165 * inadvertently return ENOSPC and suspend the pool
3166 * even though space is still available.
3168 if (allocatable && !GANG_ALLOCATION(flags) && !try_hard) {
3169 allocatable = metaslab_group_allocatable(mg, rotor,
3174 metaslab_trace_add(zal, mg, NULL, psize, d,
3175 TRACE_NOT_ALLOCATABLE);
3179 ASSERT(mg->mg_initialized);
3182 * Avoid writing single-copy data to a failing,
3183 * non-redundant vdev, unless we've already tried all
3186 if ((vd->vdev_stat.vs_write_errors > 0 ||
3187 vd->vdev_state < VDEV_STATE_HEALTHY) &&
3188 d == 0 && !try_hard && vd->vdev_children == 0) {
3189 metaslab_trace_add(zal, mg, NULL, psize, d,
3194 ASSERT(mg->mg_class == mc);
3197 * If we don't need to try hard, then require that the
3198 * block be 1/8th of the device away from any other DVAs
3199 * in this BP. If we are trying hard, allow any offset
3200 * to be used (distance=0).
3202 uint64_t distance = 0;
3204 distance = vd->vdev_asize >>
3205 ditto_same_vdev_distance_shift;
3206 if (distance <= (1ULL << vd->vdev_ms_shift))
3210 uint64_t asize = vdev_psize_to_asize(vd, psize);
3211 ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
3213 uint64_t offset = metaslab_group_alloc(mg, zal, asize, txg,
3216 if (offset != -1ULL) {
3218 * If we've just selected this metaslab group,
3219 * figure out whether the corresponding vdev is
3220 * over- or under-used relative to the pool,
3221 * and set an allocation bias to even it out.
3223 if (mc->mc_aliquot == 0 && metaslab_bias_enabled) {
3224 vdev_stat_t *vs = &vd->vdev_stat;
3227 vu = (vs->vs_alloc * 100) / (vs->vs_space + 1);
3228 cu = (mc->mc_alloc * 100) / (mc->mc_space + 1);
3231 * Calculate how much more or less we should
3232 * try to allocate from this device during
3233 * this iteration around the rotor.
3234 * For example, if a device is 80% full
3235 * and the pool is 20% full then we should
3236 * reduce allocations by 60% on this device.
3238 * mg_bias = (20 - 80) * 512K / 100 = -307K
3240 * This reduces allocations by 307K for this
3243 mg->mg_bias = ((cu - vu) *
3244 (int64_t)mg->mg_aliquot) / 100;
3245 } else if (!metaslab_bias_enabled) {
3249 if (atomic_add_64_nv(&mc->mc_aliquot, asize) >=
3250 mg->mg_aliquot + mg->mg_bias) {
3251 mc->mc_rotor = mg->mg_next;
3255 DVA_SET_VDEV(&dva[d], vd->vdev_id);
3256 DVA_SET_OFFSET(&dva[d], offset);
3257 DVA_SET_GANG(&dva[d], !!(flags & METASLAB_GANG_HEADER));
3258 DVA_SET_ASIZE(&dva[d], asize);
3263 mc->mc_rotor = mg->mg_next;
3265 } while ((mg = mg->mg_next) != rotor);
3268 * If we haven't tried hard, do so now.
3275 bzero(&dva[d], sizeof (dva_t));
3277 metaslab_trace_add(zal, rotor, NULL, psize, d, TRACE_ENOSPC);
3278 return (SET_ERROR(ENOSPC));
3282 metaslab_free_concrete(vdev_t *vd, uint64_t offset, uint64_t asize,
3286 spa_t *spa = vd->vdev_spa;
3288 ASSERT3U(txg, ==, spa->spa_syncing_txg);
3289 ASSERT(vdev_is_concrete(vd));
3290 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
3291 ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
3293 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3295 VERIFY(!msp->ms_condensing);
3296 VERIFY3U(offset, >=, msp->ms_start);
3297 VERIFY3U(offset + asize, <=, msp->ms_start + msp->ms_size);
3298 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
3299 VERIFY0(P2PHASE(asize, 1ULL << vd->vdev_ashift));
3301 metaslab_check_free_impl(vd, offset, asize);
3302 mutex_enter(&msp->ms_lock);
3303 if (range_tree_space(msp->ms_freeingtree) == 0) {
3304 vdev_dirty(vd, VDD_METASLAB, msp, txg);
3306 range_tree_add(msp->ms_freeingtree, offset, asize);
3307 mutex_exit(&msp->ms_lock);
3312 metaslab_free_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
3313 uint64_t size, void *arg)
3315 uint64_t *txgp = arg;
3317 if (vd->vdev_ops->vdev_op_remap != NULL)
3318 vdev_indirect_mark_obsolete(vd, offset, size, *txgp);
3320 metaslab_free_impl(vd, offset, size, *txgp);
3324 metaslab_free_impl(vdev_t *vd, uint64_t offset, uint64_t size,
3327 spa_t *spa = vd->vdev_spa;
3329 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
3331 if (txg > spa_freeze_txg(spa))
3334 if (spa->spa_vdev_removal != NULL &&
3335 spa->spa_vdev_removal->svr_vdev == vd &&
3336 vdev_is_concrete(vd)) {
3338 * Note: we check if the vdev is concrete because when
3339 * we complete the removal, we first change the vdev to be
3340 * an indirect vdev (in open context), and then (in syncing
3341 * context) clear spa_vdev_removal.
3343 free_from_removing_vdev(vd, offset, size, txg);
3344 } else if (vd->vdev_ops->vdev_op_remap != NULL) {
3345 vdev_indirect_mark_obsolete(vd, offset, size, txg);
3346 vd->vdev_ops->vdev_op_remap(vd, offset, size,
3347 metaslab_free_impl_cb, &txg);
3349 metaslab_free_concrete(vd, offset, size, txg);
3353 typedef struct remap_blkptr_cb_arg {
3355 spa_remap_cb_t rbca_cb;
3356 vdev_t *rbca_remap_vd;
3357 uint64_t rbca_remap_offset;
3359 } remap_blkptr_cb_arg_t;
3362 remap_blkptr_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
3363 uint64_t size, void *arg)
3365 remap_blkptr_cb_arg_t *rbca = arg;
3366 blkptr_t *bp = rbca->rbca_bp;
3368 /* We can not remap split blocks. */
3369 if (size != DVA_GET_ASIZE(&bp->blk_dva[0]))
3371 ASSERT0(inner_offset);
3373 if (rbca->rbca_cb != NULL) {
3375 * At this point we know that we are not handling split
3376 * blocks and we invoke the callback on the previous
3377 * vdev which must be indirect.
3379 ASSERT3P(rbca->rbca_remap_vd->vdev_ops, ==, &vdev_indirect_ops);
3381 rbca->rbca_cb(rbca->rbca_remap_vd->vdev_id,
3382 rbca->rbca_remap_offset, size, rbca->rbca_cb_arg);
3384 /* set up remap_blkptr_cb_arg for the next call */
3385 rbca->rbca_remap_vd = vd;
3386 rbca->rbca_remap_offset = offset;
3390 * The phys birth time is that of dva[0]. This ensures that we know
3391 * when each dva was written, so that resilver can determine which
3392 * blocks need to be scrubbed (i.e. those written during the time
3393 * the vdev was offline). It also ensures that the key used in
3394 * the ARC hash table is unique (i.e. dva[0] + phys_birth). If
3395 * we didn't change the phys_birth, a lookup in the ARC for a
3396 * remapped BP could find the data that was previously stored at
3397 * this vdev + offset.
3399 vdev_t *oldvd = vdev_lookup_top(vd->vdev_spa,
3400 DVA_GET_VDEV(&bp->blk_dva[0]));
3401 vdev_indirect_births_t *vib = oldvd->vdev_indirect_births;
3402 bp->blk_phys_birth = vdev_indirect_births_physbirth(vib,
3403 DVA_GET_OFFSET(&bp->blk_dva[0]), DVA_GET_ASIZE(&bp->blk_dva[0]));
3405 DVA_SET_VDEV(&bp->blk_dva[0], vd->vdev_id);
3406 DVA_SET_OFFSET(&bp->blk_dva[0], offset);
3410 * If the block pointer contains any indirect DVAs, modify them to refer to
3411 * concrete DVAs. Note that this will sometimes not be possible, leaving
3412 * the indirect DVA in place. This happens if the indirect DVA spans multiple
3413 * segments in the mapping (i.e. it is a "split block").
3415 * If the BP was remapped, calls the callback on the original dva (note the
3416 * callback can be called multiple times if the original indirect DVA refers
3417 * to another indirect DVA, etc).
3419 * Returns TRUE if the BP was remapped.
3422 spa_remap_blkptr(spa_t *spa, blkptr_t *bp, spa_remap_cb_t callback, void *arg)
3424 remap_blkptr_cb_arg_t rbca;
3426 if (!zfs_remap_blkptr_enable)
3429 if (!spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS))
3433 * Dedup BP's can not be remapped, because ddt_phys_select() depends
3434 * on DVA[0] being the same in the BP as in the DDT (dedup table).
3436 if (BP_GET_DEDUP(bp))
3440 * Gang blocks can not be remapped, because
3441 * zio_checksum_gang_verifier() depends on the DVA[0] that's in
3442 * the BP used to read the gang block header (GBH) being the same
3443 * as the DVA[0] that we allocated for the GBH.
3449 * Embedded BP's have no DVA to remap.
3451 if (BP_GET_NDVAS(bp) < 1)
3455 * Note: we only remap dva[0]. If we remapped other dvas, we
3456 * would no longer know what their phys birth txg is.
3458 dva_t *dva = &bp->blk_dva[0];
3460 uint64_t offset = DVA_GET_OFFSET(dva);
3461 uint64_t size = DVA_GET_ASIZE(dva);
3462 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
3464 if (vd->vdev_ops->vdev_op_remap == NULL)
3468 rbca.rbca_cb = callback;
3469 rbca.rbca_remap_vd = vd;
3470 rbca.rbca_remap_offset = offset;
3471 rbca.rbca_cb_arg = arg;
3474 * remap_blkptr_cb() will be called in order for each level of
3475 * indirection, until a concrete vdev is reached or a split block is
3476 * encountered. old_vd and old_offset are updated within the callback
3477 * as we go from the one indirect vdev to the next one (either concrete
3478 * or indirect again) in that order.
3480 vd->vdev_ops->vdev_op_remap(vd, offset, size, remap_blkptr_cb, &rbca);
3482 /* Check if the DVA wasn't remapped because it is a split block */
3483 if (DVA_GET_VDEV(&rbca.rbca_bp->blk_dva[0]) == vd->vdev_id)
3490 * Undo the allocation of a DVA which happened in the given transaction group.
3493 metaslab_unalloc_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
3497 uint64_t vdev = DVA_GET_VDEV(dva);
3498 uint64_t offset = DVA_GET_OFFSET(dva);
3499 uint64_t size = DVA_GET_ASIZE(dva);
3501 ASSERT(DVA_IS_VALID(dva));
3502 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
3504 if (txg > spa_freeze_txg(spa))
3507 if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
3508 (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
3509 cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
3510 (u_longlong_t)vdev, (u_longlong_t)offset);
3515 ASSERT(!vd->vdev_removing);
3516 ASSERT(vdev_is_concrete(vd));
3517 ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
3518 ASSERT3P(vd->vdev_indirect_mapping, ==, NULL);
3520 if (DVA_GET_GANG(dva))
3521 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
3523 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3525 mutex_enter(&msp->ms_lock);
3526 range_tree_remove(msp->ms_alloctree[txg & TXG_MASK],
3529 VERIFY(!msp->ms_condensing);
3530 VERIFY3U(offset, >=, msp->ms_start);
3531 VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
3532 VERIFY3U(range_tree_space(msp->ms_tree) + size, <=,
3534 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
3535 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
3536 range_tree_add(msp->ms_tree, offset, size);
3537 mutex_exit(&msp->ms_lock);
3541 * Free the block represented by DVA in the context of the specified
3542 * transaction group.
3545 metaslab_free_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
3547 uint64_t vdev = DVA_GET_VDEV(dva);
3548 uint64_t offset = DVA_GET_OFFSET(dva);
3549 uint64_t size = DVA_GET_ASIZE(dva);
3550 vdev_t *vd = vdev_lookup_top(spa, vdev);
3552 ASSERT(DVA_IS_VALID(dva));
3553 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
3555 if (DVA_GET_GANG(dva)) {
3556 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
3559 metaslab_free_impl(vd, offset, size, txg);
3563 * Reserve some allocation slots. The reservation system must be called
3564 * before we call into the allocator. If there aren't any available slots
3565 * then the I/O will be throttled until an I/O completes and its slots are
3566 * freed up. The function returns true if it was successful in placing
3570 metaslab_class_throttle_reserve(metaslab_class_t *mc, int slots, zio_t *zio,
3573 uint64_t available_slots = 0;
3574 boolean_t slot_reserved = B_FALSE;
3576 ASSERT(mc->mc_alloc_throttle_enabled);
3577 mutex_enter(&mc->mc_lock);
3579 uint64_t reserved_slots = refcount_count(&mc->mc_alloc_slots);
3580 if (reserved_slots < mc->mc_alloc_max_slots)
3581 available_slots = mc->mc_alloc_max_slots - reserved_slots;
3583 if (slots <= available_slots || GANG_ALLOCATION(flags)) {
3585 * We reserve the slots individually so that we can unreserve
3586 * them individually when an I/O completes.
3588 for (int d = 0; d < slots; d++) {
3589 reserved_slots = refcount_add(&mc->mc_alloc_slots, zio);
3591 zio->io_flags |= ZIO_FLAG_IO_ALLOCATING;
3592 slot_reserved = B_TRUE;
3595 mutex_exit(&mc->mc_lock);
3596 return (slot_reserved);
3600 metaslab_class_throttle_unreserve(metaslab_class_t *mc, int slots, zio_t *zio)
3602 ASSERT(mc->mc_alloc_throttle_enabled);
3603 mutex_enter(&mc->mc_lock);
3604 for (int d = 0; d < slots; d++) {
3605 (void) refcount_remove(&mc->mc_alloc_slots, zio);
3607 mutex_exit(&mc->mc_lock);
3611 metaslab_claim_concrete(vdev_t *vd, uint64_t offset, uint64_t size,
3615 spa_t *spa = vd->vdev_spa;
3618 if (offset >> vd->vdev_ms_shift >= vd->vdev_ms_count)
3621 ASSERT3P(vd->vdev_ms, !=, NULL);
3622 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3624 mutex_enter(&msp->ms_lock);
3626 if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded)
3627 error = metaslab_activate(msp, METASLAB_WEIGHT_SECONDARY);
3629 if (error == 0 && !range_tree_contains(msp->ms_tree, offset, size))
3630 error = SET_ERROR(ENOENT);
3632 if (error || txg == 0) { /* txg == 0 indicates dry run */
3633 mutex_exit(&msp->ms_lock);
3637 VERIFY(!msp->ms_condensing);
3638 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
3639 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
3640 VERIFY3U(range_tree_space(msp->ms_tree) - size, <=, msp->ms_size);
3641 range_tree_remove(msp->ms_tree, offset, size);
3643 if (spa_writeable(spa)) { /* don't dirty if we're zdb(1M) */
3644 if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
3645 vdev_dirty(vd, VDD_METASLAB, msp, txg);
3646 range_tree_add(msp->ms_alloctree[txg & TXG_MASK], offset, size);
3649 mutex_exit(&msp->ms_lock);
3654 typedef struct metaslab_claim_cb_arg_t {
3657 } metaslab_claim_cb_arg_t;
3661 metaslab_claim_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
3662 uint64_t size, void *arg)
3664 metaslab_claim_cb_arg_t *mcca_arg = arg;
3666 if (mcca_arg->mcca_error == 0) {
3667 mcca_arg->mcca_error = metaslab_claim_concrete(vd, offset,
3668 size, mcca_arg->mcca_txg);
3673 metaslab_claim_impl(vdev_t *vd, uint64_t offset, uint64_t size, uint64_t txg)
3675 if (vd->vdev_ops->vdev_op_remap != NULL) {
3676 metaslab_claim_cb_arg_t arg;
3679 * Only zdb(1M) can claim on indirect vdevs. This is used
3680 * to detect leaks of mapped space (that are not accounted
3681 * for in the obsolete counts, spacemap, or bpobj).
3683 ASSERT(!spa_writeable(vd->vdev_spa));
3687 vd->vdev_ops->vdev_op_remap(vd, offset, size,
3688 metaslab_claim_impl_cb, &arg);
3690 if (arg.mcca_error == 0) {
3691 arg.mcca_error = metaslab_claim_concrete(vd,
3694 return (arg.mcca_error);
3696 return (metaslab_claim_concrete(vd, offset, size, txg));
3701 * Intent log support: upon opening the pool after a crash, notify the SPA
3702 * of blocks that the intent log has allocated for immediate write, but
3703 * which are still considered free by the SPA because the last transaction
3704 * group didn't commit yet.
3707 metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
3709 uint64_t vdev = DVA_GET_VDEV(dva);
3710 uint64_t offset = DVA_GET_OFFSET(dva);
3711 uint64_t size = DVA_GET_ASIZE(dva);
3714 if ((vd = vdev_lookup_top(spa, vdev)) == NULL) {
3715 return (SET_ERROR(ENXIO));
3718 ASSERT(DVA_IS_VALID(dva));
3720 if (DVA_GET_GANG(dva))
3721 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
3723 return (metaslab_claim_impl(vd, offset, size, txg));
3727 metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
3728 int ndvas, uint64_t txg, blkptr_t *hintbp, int flags,
3729 zio_alloc_list_t *zal, zio_t *zio)
3731 dva_t *dva = bp->blk_dva;
3732 dva_t *hintdva = hintbp->blk_dva;
3735 ASSERT(bp->blk_birth == 0);
3736 ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
3738 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
3740 if (mc->mc_rotor == NULL) { /* no vdevs in this class */
3741 spa_config_exit(spa, SCL_ALLOC, FTAG);
3742 return (SET_ERROR(ENOSPC));
3745 ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
3746 ASSERT(BP_GET_NDVAS(bp) == 0);
3747 ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
3748 ASSERT3P(zal, !=, NULL);
3750 for (int d = 0; d < ndvas; d++) {
3751 error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
3754 for (d--; d >= 0; d--) {
3755 metaslab_unalloc_dva(spa, &dva[d], txg);
3756 metaslab_group_alloc_decrement(spa,
3757 DVA_GET_VDEV(&dva[d]), zio, flags);
3758 bzero(&dva[d], sizeof (dva_t));
3760 spa_config_exit(spa, SCL_ALLOC, FTAG);
3764 * Update the metaslab group's queue depth
3765 * based on the newly allocated dva.
3767 metaslab_group_alloc_increment(spa,
3768 DVA_GET_VDEV(&dva[d]), zio, flags);
3773 ASSERT(BP_GET_NDVAS(bp) == ndvas);
3775 spa_config_exit(spa, SCL_ALLOC, FTAG);
3777 BP_SET_BIRTH(bp, txg, txg);
3783 metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
3785 const dva_t *dva = bp->blk_dva;
3786 int ndvas = BP_GET_NDVAS(bp);
3788 ASSERT(!BP_IS_HOLE(bp));
3789 ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
3791 spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
3793 for (int d = 0; d < ndvas; d++) {
3795 metaslab_unalloc_dva(spa, &dva[d], txg);
3797 metaslab_free_dva(spa, &dva[d], txg);
3801 spa_config_exit(spa, SCL_FREE, FTAG);
3805 metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
3807 const dva_t *dva = bp->blk_dva;
3808 int ndvas = BP_GET_NDVAS(bp);
3811 ASSERT(!BP_IS_HOLE(bp));
3815 * First do a dry run to make sure all DVAs are claimable,
3816 * so we don't have to unwind from partial failures below.
3818 if ((error = metaslab_claim(spa, bp, 0)) != 0)
3822 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
3824 for (int d = 0; d < ndvas; d++)
3825 if ((error = metaslab_claim_dva(spa, &dva[d], txg)) != 0)
3828 spa_config_exit(spa, SCL_ALLOC, FTAG);
3830 ASSERT(error == 0 || txg == 0);
3837 metaslab_check_free_impl_cb(uint64_t inner, vdev_t *vd, uint64_t offset,
3838 uint64_t size, void *arg)
3840 if (vd->vdev_ops == &vdev_indirect_ops)
3843 metaslab_check_free_impl(vd, offset, size);
3847 metaslab_check_free_impl(vdev_t *vd, uint64_t offset, uint64_t size)
3850 spa_t *spa = vd->vdev_spa;
3852 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
3855 if (vd->vdev_ops->vdev_op_remap != NULL) {
3856 vd->vdev_ops->vdev_op_remap(vd, offset, size,
3857 metaslab_check_free_impl_cb, NULL);
3861 ASSERT(vdev_is_concrete(vd));
3862 ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
3863 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
3865 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3867 mutex_enter(&msp->ms_lock);
3869 range_tree_verify(msp->ms_tree, offset, size);
3871 range_tree_verify(msp->ms_freeingtree, offset, size);
3872 range_tree_verify(msp->ms_freedtree, offset, size);
3873 for (int j = 0; j < TXG_DEFER_SIZE; j++)
3874 range_tree_verify(msp->ms_defertree[j], offset, size);
3875 mutex_exit(&msp->ms_lock);
3879 metaslab_check_free(spa_t *spa, const blkptr_t *bp)
3881 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
3884 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3885 for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
3886 uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
3887 vdev_t *vd = vdev_lookup_top(spa, vdev);
3888 uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
3889 uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
3891 if (DVA_GET_GANG(&bp->blk_dva[i]))
3892 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
3894 ASSERT3P(vd, !=, NULL);
3896 metaslab_check_free_impl(vd, offset, size);
3898 spa_config_exit(spa, SCL_VDEV, FTAG);