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, 2019 by Delphix. All rights reserved.
24 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
25 * Copyright (c) 2017, Intel Corporation.
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 #include <sys/btree.h>
41 #define WITH_DF_BLOCK_ALLOCATOR
43 #define GANG_ALLOCATION(flags) \
44 ((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER))
47 * Metaslab granularity, in bytes. This is roughly similar to what would be
48 * referred to as the "stripe size" in traditional RAID arrays. In normal
49 * operation, we will try to write this amount of data to a top-level vdev
50 * before moving on to the next one.
52 unsigned long metaslab_aliquot = 512 << 10;
55 * For testing, make some blocks above a certain size be gang blocks.
57 unsigned long metaslab_force_ganging = SPA_MAXBLOCKSIZE + 1;
60 * In pools where the log space map feature is not enabled we touch
61 * multiple metaslabs (and their respective space maps) with each
62 * transaction group. Thus, we benefit from having a small space map
63 * block size since it allows us to issue more I/O operations scattered
64 * around the disk. So a sane default for the space map block size
67 int zfs_metaslab_sm_blksz_no_log = (1 << 14);
70 * When the log space map feature is enabled, we accumulate a lot of
71 * changes per metaslab that are flushed once in a while so we benefit
72 * from a bigger block size like 128K for the metaslab space maps.
74 int zfs_metaslab_sm_blksz_with_log = (1 << 17);
77 * The in-core space map representation is more compact than its on-disk form.
78 * The zfs_condense_pct determines how much more compact the in-core
79 * space map representation must be before we compact it on-disk.
80 * Values should be greater than or equal to 100.
82 int zfs_condense_pct = 200;
85 * Condensing a metaslab is not guaranteed to actually reduce the amount of
86 * space used on disk. In particular, a space map uses data in increments of
87 * MAX(1 << ashift, space_map_blksz), so a metaslab might use the
88 * same number of blocks after condensing. Since the goal of condensing is to
89 * reduce the number of IOPs required to read the space map, we only want to
90 * condense when we can be sure we will reduce the number of blocks used by the
91 * space map. Unfortunately, we cannot precisely compute whether or not this is
92 * the case in metaslab_should_condense since we are holding ms_lock. Instead,
93 * we apply the following heuristic: do not condense a spacemap unless the
94 * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
97 int zfs_metaslab_condense_block_threshold = 4;
100 * The zfs_mg_noalloc_threshold defines which metaslab groups should
101 * be eligible for allocation. The value is defined as a percentage of
102 * free space. Metaslab groups that have more free space than
103 * zfs_mg_noalloc_threshold are always eligible for allocations. Once
104 * a metaslab group's free space is less than or equal to the
105 * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
106 * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
107 * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
108 * groups are allowed to accept allocations. Gang blocks are always
109 * eligible to allocate on any metaslab group. The default value of 0 means
110 * no metaslab group will be excluded based on this criterion.
112 int zfs_mg_noalloc_threshold = 0;
115 * Metaslab groups are considered eligible for allocations if their
116 * fragmentation metric (measured as a percentage) is less than or
117 * equal to zfs_mg_fragmentation_threshold. If a metaslab group
118 * exceeds this threshold then it will be skipped unless all metaslab
119 * groups within the metaslab class have also crossed this threshold.
121 * This tunable was introduced to avoid edge cases where we continue
122 * allocating from very fragmented disks in our pool while other, less
123 * fragmented disks, exists. On the other hand, if all disks in the
124 * pool are uniformly approaching the threshold, the threshold can
125 * be a speed bump in performance, where we keep switching the disks
126 * that we allocate from (e.g. we allocate some segments from disk A
127 * making it bypassing the threshold while freeing segments from disk
128 * B getting its fragmentation below the threshold).
130 * Empirically, we've seen that our vdev selection for allocations is
131 * good enough that fragmentation increases uniformly across all vdevs
132 * the majority of the time. Thus we set the threshold percentage high
133 * enough to avoid hitting the speed bump on pools that are being pushed
136 int zfs_mg_fragmentation_threshold = 95;
139 * Allow metaslabs to keep their active state as long as their fragmentation
140 * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
141 * active metaslab that exceeds this threshold will no longer keep its active
142 * status allowing better metaslabs to be selected.
144 int zfs_metaslab_fragmentation_threshold = 70;
147 * When set will load all metaslabs when pool is first opened.
149 int metaslab_debug_load = 0;
152 * When set will prevent metaslabs from being unloaded.
154 int metaslab_debug_unload = 0;
157 * Minimum size which forces the dynamic allocator to change
158 * it's allocation strategy. Once the space map cannot satisfy
159 * an allocation of this size then it switches to using more
160 * aggressive strategy (i.e search by size rather than offset).
162 uint64_t metaslab_df_alloc_threshold = SPA_OLD_MAXBLOCKSIZE;
165 * The minimum free space, in percent, which must be available
166 * in a space map to continue allocations in a first-fit fashion.
167 * Once the space map's free space drops below this level we dynamically
168 * switch to using best-fit allocations.
170 int metaslab_df_free_pct = 4;
173 * Maximum distance to search forward from the last offset. Without this
174 * limit, fragmented pools can see >100,000 iterations and
175 * metaslab_block_picker() becomes the performance limiting factor on
176 * high-performance storage.
178 * With the default setting of 16MB, we typically see less than 500
179 * iterations, even with very fragmented, ashift=9 pools. The maximum number
180 * of iterations possible is:
181 * metaslab_df_max_search / (2 * (1<<ashift))
182 * With the default setting of 16MB this is 16*1024 (with ashift=9) or
183 * 2048 (with ashift=12).
185 int metaslab_df_max_search = 16 * 1024 * 1024;
188 * Forces the metaslab_block_picker function to search for at least this many
189 * segments forwards until giving up on finding a segment that the allocation
192 uint32_t metaslab_min_search_count = 100;
195 * If we are not searching forward (due to metaslab_df_max_search,
196 * metaslab_df_free_pct, or metaslab_df_alloc_threshold), this tunable
197 * controls what segment is used. If it is set, we will use the largest free
198 * segment. If it is not set, we will use a segment of exactly the requested
201 int metaslab_df_use_largest_segment = B_FALSE;
204 * Percentage of all cpus that can be used by the metaslab taskq.
206 int metaslab_load_pct = 50;
209 * These tunables control how long a metaslab will remain loaded after the
210 * last allocation from it. A metaslab can't be unloaded until at least
211 * metaslab_unload_delay TXG's and metaslab_unload_delay_ms milliseconds
212 * have elapsed. However, zfs_metaslab_mem_limit may cause it to be
213 * unloaded sooner. These settings are intended to be generous -- to keep
214 * metaslabs loaded for a long time, reducing the rate of metaslab loading.
216 int metaslab_unload_delay = 32;
217 int metaslab_unload_delay_ms = 10 * 60 * 1000; /* ten minutes */
220 * Max number of metaslabs per group to preload.
222 int metaslab_preload_limit = 10;
225 * Enable/disable preloading of metaslab.
227 int metaslab_preload_enabled = B_TRUE;
230 * Enable/disable fragmentation weighting on metaslabs.
232 int metaslab_fragmentation_factor_enabled = B_TRUE;
235 * Enable/disable lba weighting (i.e. outer tracks are given preference).
237 int metaslab_lba_weighting_enabled = B_TRUE;
240 * Enable/disable metaslab group biasing.
242 int metaslab_bias_enabled = B_TRUE;
245 * Enable/disable remapping of indirect DVAs to their concrete vdevs.
247 boolean_t zfs_remap_blkptr_enable = B_TRUE;
250 * Enable/disable segment-based metaslab selection.
252 int zfs_metaslab_segment_weight_enabled = B_TRUE;
255 * When using segment-based metaslab selection, we will continue
256 * allocating from the active metaslab until we have exhausted
257 * zfs_metaslab_switch_threshold of its buckets.
259 int zfs_metaslab_switch_threshold = 2;
262 * Internal switch to enable/disable the metaslab allocation tracing
265 #ifdef _METASLAB_TRACING
266 boolean_t metaslab_trace_enabled = B_TRUE;
270 * Maximum entries that the metaslab allocation tracing facility will keep
271 * in a given list when running in non-debug mode. We limit the number
272 * of entries in non-debug mode to prevent us from using up too much memory.
273 * The limit should be sufficiently large that we don't expect any allocation
274 * to every exceed this value. In debug mode, the system will panic if this
275 * limit is ever reached allowing for further investigation.
277 #ifdef _METASLAB_TRACING
278 uint64_t metaslab_trace_max_entries = 5000;
282 * Maximum number of metaslabs per group that can be disabled
285 int max_disabled_ms = 3;
288 * Time (in seconds) to respect ms_max_size when the metaslab is not loaded.
289 * To avoid 64-bit overflow, don't set above UINT32_MAX.
291 unsigned long zfs_metaslab_max_size_cache_sec = 3600; /* 1 hour */
294 * Maximum percentage of memory to use on storing loaded metaslabs. If loading
295 * a metaslab would take it over this percentage, the oldest selected metaslab
296 * is automatically unloaded.
298 int zfs_metaslab_mem_limit = 75;
301 * Force the per-metaslab range trees to use 64-bit integers to store
302 * segments. Used for debugging purposes.
304 boolean_t zfs_metaslab_force_large_segs = B_FALSE;
307 * By default we only store segments over a certain size in the size-sorted
308 * metaslab trees (ms_allocatable_by_size and
309 * ms_unflushed_frees_by_size). This dramatically reduces memory usage and
310 * improves load and unload times at the cost of causing us to use slightly
311 * larger segments than we would otherwise in some cases.
313 uint32_t metaslab_by_size_min_shift = 14;
315 static uint64_t metaslab_weight(metaslab_t *, boolean_t);
316 static void metaslab_set_fragmentation(metaslab_t *, boolean_t);
317 static void metaslab_free_impl(vdev_t *, uint64_t, uint64_t, boolean_t);
318 static void metaslab_check_free_impl(vdev_t *, uint64_t, uint64_t);
320 static void metaslab_passivate(metaslab_t *msp, uint64_t weight);
321 static uint64_t metaslab_weight_from_range_tree(metaslab_t *msp);
322 static void metaslab_flush_update(metaslab_t *, dmu_tx_t *);
323 static unsigned int metaslab_idx_func(multilist_t *, void *);
324 static void metaslab_evict(metaslab_t *, uint64_t);
325 static void metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg);
326 #ifdef _METASLAB_TRACING
327 kmem_cache_t *metaslab_alloc_trace_cache;
329 typedef struct metaslab_stats {
330 kstat_named_t metaslabstat_trace_over_limit;
331 kstat_named_t metaslabstat_df_find_under_floor;
332 kstat_named_t metaslabstat_reload_tree;
335 static metaslab_stats_t metaslab_stats = {
336 { "trace_over_limit", KSTAT_DATA_UINT64 },
337 { "df_find_under_floor", KSTAT_DATA_UINT64 },
338 { "reload_tree", KSTAT_DATA_UINT64 },
341 #define METASLABSTAT_BUMP(stat) \
342 atomic_inc_64(&metaslab_stats.stat.value.ui64);
345 kstat_t *metaslab_ksp;
348 metaslab_stat_init(void)
350 ASSERT(metaslab_alloc_trace_cache == NULL);
351 metaslab_alloc_trace_cache = kmem_cache_create(
352 "metaslab_alloc_trace_cache", sizeof (metaslab_alloc_trace_t),
353 0, NULL, NULL, NULL, NULL, NULL, 0);
354 metaslab_ksp = kstat_create("zfs", 0, "metaslab_stats",
355 "misc", KSTAT_TYPE_NAMED, sizeof (metaslab_stats) /
356 sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
357 if (metaslab_ksp != NULL) {
358 metaslab_ksp->ks_data = &metaslab_stats;
359 kstat_install(metaslab_ksp);
364 metaslab_stat_fini(void)
366 if (metaslab_ksp != NULL) {
367 kstat_delete(metaslab_ksp);
371 kmem_cache_destroy(metaslab_alloc_trace_cache);
372 metaslab_alloc_trace_cache = NULL;
377 metaslab_stat_init(void)
382 metaslab_stat_fini(void)
388 * ==========================================================================
390 * ==========================================================================
393 metaslab_class_create(spa_t *spa, metaslab_ops_t *ops)
395 metaslab_class_t *mc;
397 mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
402 mutex_init(&mc->mc_lock, NULL, MUTEX_DEFAULT, NULL);
403 mc->mc_metaslab_txg_list = multilist_create(sizeof (metaslab_t),
404 offsetof(metaslab_t, ms_class_txg_node), metaslab_idx_func);
405 mc->mc_alloc_slots = kmem_zalloc(spa->spa_alloc_count *
406 sizeof (zfs_refcount_t), KM_SLEEP);
407 mc->mc_alloc_max_slots = kmem_zalloc(spa->spa_alloc_count *
408 sizeof (uint64_t), KM_SLEEP);
409 for (int i = 0; i < spa->spa_alloc_count; i++)
410 zfs_refcount_create_tracked(&mc->mc_alloc_slots[i]);
416 metaslab_class_destroy(metaslab_class_t *mc)
418 ASSERT(mc->mc_rotor == NULL);
419 ASSERT(mc->mc_alloc == 0);
420 ASSERT(mc->mc_deferred == 0);
421 ASSERT(mc->mc_space == 0);
422 ASSERT(mc->mc_dspace == 0);
424 for (int i = 0; i < mc->mc_spa->spa_alloc_count; i++)
425 zfs_refcount_destroy(&mc->mc_alloc_slots[i]);
426 kmem_free(mc->mc_alloc_slots, mc->mc_spa->spa_alloc_count *
427 sizeof (zfs_refcount_t));
428 kmem_free(mc->mc_alloc_max_slots, mc->mc_spa->spa_alloc_count *
430 mutex_destroy(&mc->mc_lock);
431 multilist_destroy(mc->mc_metaslab_txg_list);
432 kmem_free(mc, sizeof (metaslab_class_t));
436 metaslab_class_validate(metaslab_class_t *mc)
438 metaslab_group_t *mg;
442 * Must hold one of the spa_config locks.
444 ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
445 spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
447 if ((mg = mc->mc_rotor) == NULL)
452 ASSERT(vd->vdev_mg != NULL);
453 ASSERT3P(vd->vdev_top, ==, vd);
454 ASSERT3P(mg->mg_class, ==, mc);
455 ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
456 } while ((mg = mg->mg_next) != mc->mc_rotor);
462 metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
463 int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
465 atomic_add_64(&mc->mc_alloc, alloc_delta);
466 atomic_add_64(&mc->mc_deferred, defer_delta);
467 atomic_add_64(&mc->mc_space, space_delta);
468 atomic_add_64(&mc->mc_dspace, dspace_delta);
472 metaslab_class_get_alloc(metaslab_class_t *mc)
474 return (mc->mc_alloc);
478 metaslab_class_get_deferred(metaslab_class_t *mc)
480 return (mc->mc_deferred);
484 metaslab_class_get_space(metaslab_class_t *mc)
486 return (mc->mc_space);
490 metaslab_class_get_dspace(metaslab_class_t *mc)
492 return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
496 metaslab_class_histogram_verify(metaslab_class_t *mc)
498 spa_t *spa = mc->mc_spa;
499 vdev_t *rvd = spa->spa_root_vdev;
503 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
506 mc_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
509 for (int c = 0; c < rvd->vdev_children; c++) {
510 vdev_t *tvd = rvd->vdev_child[c];
511 metaslab_group_t *mg = tvd->vdev_mg;
514 * Skip any holes, uninitialized top-levels, or
515 * vdevs that are not in this metalab class.
517 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
518 mg->mg_class != mc) {
522 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
523 mc_hist[i] += mg->mg_histogram[i];
526 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
527 VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
529 kmem_free(mc_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
533 * Calculate the metaslab class's fragmentation metric. The metric
534 * is weighted based on the space contribution of each metaslab group.
535 * The return value will be a number between 0 and 100 (inclusive), or
536 * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
537 * zfs_frag_table for more information about the metric.
540 metaslab_class_fragmentation(metaslab_class_t *mc)
542 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
543 uint64_t fragmentation = 0;
545 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
547 for (int c = 0; c < rvd->vdev_children; c++) {
548 vdev_t *tvd = rvd->vdev_child[c];
549 metaslab_group_t *mg = tvd->vdev_mg;
552 * Skip any holes, uninitialized top-levels,
553 * or vdevs that are not in this metalab class.
555 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
556 mg->mg_class != mc) {
561 * If a metaslab group does not contain a fragmentation
562 * metric then just bail out.
564 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
565 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
566 return (ZFS_FRAG_INVALID);
570 * Determine how much this metaslab_group is contributing
571 * to the overall pool fragmentation metric.
573 fragmentation += mg->mg_fragmentation *
574 metaslab_group_get_space(mg);
576 fragmentation /= metaslab_class_get_space(mc);
578 ASSERT3U(fragmentation, <=, 100);
579 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
580 return (fragmentation);
584 * Calculate the amount of expandable space that is available in
585 * this metaslab class. If a device is expanded then its expandable
586 * space will be the amount of allocatable space that is currently not
587 * part of this metaslab class.
590 metaslab_class_expandable_space(metaslab_class_t *mc)
592 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
595 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
596 for (int c = 0; c < rvd->vdev_children; c++) {
597 vdev_t *tvd = rvd->vdev_child[c];
598 metaslab_group_t *mg = tvd->vdev_mg;
600 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
601 mg->mg_class != mc) {
606 * Calculate if we have enough space to add additional
607 * metaslabs. We report the expandable space in terms
608 * of the metaslab size since that's the unit of expansion.
610 space += P2ALIGN(tvd->vdev_max_asize - tvd->vdev_asize,
611 1ULL << tvd->vdev_ms_shift);
613 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
618 metaslab_class_evict_old(metaslab_class_t *mc, uint64_t txg)
620 multilist_t *ml = mc->mc_metaslab_txg_list;
621 for (int i = 0; i < multilist_get_num_sublists(ml); i++) {
622 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
623 metaslab_t *msp = multilist_sublist_head(mls);
624 multilist_sublist_unlock(mls);
625 while (msp != NULL) {
626 mutex_enter(&msp->ms_lock);
629 * If the metaslab has been removed from the list
630 * (which could happen if we were at the memory limit
631 * and it was evicted during this loop), then we can't
632 * proceed and we should restart the sublist.
634 if (!multilist_link_active(&msp->ms_class_txg_node)) {
635 mutex_exit(&msp->ms_lock);
639 mls = multilist_sublist_lock(ml, i);
640 metaslab_t *next_msp = multilist_sublist_next(mls, msp);
641 multilist_sublist_unlock(mls);
643 msp->ms_selected_txg + metaslab_unload_delay &&
644 gethrtime() > msp->ms_selected_time +
645 (uint64_t)MSEC2NSEC(metaslab_unload_delay_ms)) {
646 metaslab_evict(msp, txg);
649 * Once we've hit a metaslab selected too
650 * recently to evict, we're done evicting for
653 mutex_exit(&msp->ms_lock);
656 mutex_exit(&msp->ms_lock);
663 metaslab_compare(const void *x1, const void *x2)
665 const metaslab_t *m1 = (const metaslab_t *)x1;
666 const metaslab_t *m2 = (const metaslab_t *)x2;
670 if (m1->ms_allocator != -1 && m1->ms_primary)
672 else if (m1->ms_allocator != -1 && !m1->ms_primary)
674 if (m2->ms_allocator != -1 && m2->ms_primary)
676 else if (m2->ms_allocator != -1 && !m2->ms_primary)
680 * Sort inactive metaslabs first, then primaries, then secondaries. When
681 * selecting a metaslab to allocate from, an allocator first tries its
682 * primary, then secondary active metaslab. If it doesn't have active
683 * metaslabs, or can't allocate from them, it searches for an inactive
684 * metaslab to activate. If it can't find a suitable one, it will steal
685 * a primary or secondary metaslab from another allocator.
692 int cmp = TREE_CMP(m2->ms_weight, m1->ms_weight);
696 IMPLY(TREE_CMP(m1->ms_start, m2->ms_start) == 0, m1 == m2);
698 return (TREE_CMP(m1->ms_start, m2->ms_start));
702 * ==========================================================================
704 * ==========================================================================
707 * Update the allocatable flag and the metaslab group's capacity.
708 * The allocatable flag is set to true if the capacity is below
709 * the zfs_mg_noalloc_threshold or has a fragmentation value that is
710 * greater than zfs_mg_fragmentation_threshold. If a metaslab group
711 * transitions from allocatable to non-allocatable or vice versa then the
712 * metaslab group's class is updated to reflect the transition.
715 metaslab_group_alloc_update(metaslab_group_t *mg)
717 vdev_t *vd = mg->mg_vd;
718 metaslab_class_t *mc = mg->mg_class;
719 vdev_stat_t *vs = &vd->vdev_stat;
720 boolean_t was_allocatable;
721 boolean_t was_initialized;
723 ASSERT(vd == vd->vdev_top);
724 ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_READER), ==,
727 mutex_enter(&mg->mg_lock);
728 was_allocatable = mg->mg_allocatable;
729 was_initialized = mg->mg_initialized;
731 mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
734 mutex_enter(&mc->mc_lock);
737 * If the metaslab group was just added then it won't
738 * have any space until we finish syncing out this txg.
739 * At that point we will consider it initialized and available
740 * for allocations. We also don't consider non-activated
741 * metaslab groups (e.g. vdevs that are in the middle of being removed)
742 * to be initialized, because they can't be used for allocation.
744 mg->mg_initialized = metaslab_group_initialized(mg);
745 if (!was_initialized && mg->mg_initialized) {
747 } else if (was_initialized && !mg->mg_initialized) {
748 ASSERT3U(mc->mc_groups, >, 0);
751 if (mg->mg_initialized)
752 mg->mg_no_free_space = B_FALSE;
755 * A metaslab group is considered allocatable if it has plenty
756 * of free space or is not heavily fragmented. We only take
757 * fragmentation into account if the metaslab group has a valid
758 * fragmentation metric (i.e. a value between 0 and 100).
760 mg->mg_allocatable = (mg->mg_activation_count > 0 &&
761 mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
762 (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
763 mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
766 * The mc_alloc_groups maintains a count of the number of
767 * groups in this metaslab class that are still above the
768 * zfs_mg_noalloc_threshold. This is used by the allocating
769 * threads to determine if they should avoid allocations to
770 * a given group. The allocator will avoid allocations to a group
771 * if that group has reached or is below the zfs_mg_noalloc_threshold
772 * and there are still other groups that are above the threshold.
773 * When a group transitions from allocatable to non-allocatable or
774 * vice versa we update the metaslab class to reflect that change.
775 * When the mc_alloc_groups value drops to 0 that means that all
776 * groups have reached the zfs_mg_noalloc_threshold making all groups
777 * eligible for allocations. This effectively means that all devices
778 * are balanced again.
780 if (was_allocatable && !mg->mg_allocatable)
781 mc->mc_alloc_groups--;
782 else if (!was_allocatable && mg->mg_allocatable)
783 mc->mc_alloc_groups++;
784 mutex_exit(&mc->mc_lock);
786 mutex_exit(&mg->mg_lock);
790 metaslab_sort_by_flushed(const void *va, const void *vb)
792 const metaslab_t *a = va;
793 const metaslab_t *b = vb;
795 int cmp = TREE_CMP(a->ms_unflushed_txg, b->ms_unflushed_txg);
799 uint64_t a_vdev_id = a->ms_group->mg_vd->vdev_id;
800 uint64_t b_vdev_id = b->ms_group->mg_vd->vdev_id;
801 cmp = TREE_CMP(a_vdev_id, b_vdev_id);
805 return (TREE_CMP(a->ms_id, b->ms_id));
809 metaslab_group_create(metaslab_class_t *mc, vdev_t *vd, int allocators)
811 metaslab_group_t *mg;
813 mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
814 mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
815 mutex_init(&mg->mg_ms_disabled_lock, NULL, MUTEX_DEFAULT, NULL);
816 cv_init(&mg->mg_ms_disabled_cv, NULL, CV_DEFAULT, NULL);
817 avl_create(&mg->mg_metaslab_tree, metaslab_compare,
818 sizeof (metaslab_t), offsetof(metaslab_t, ms_group_node));
821 mg->mg_activation_count = 0;
822 mg->mg_initialized = B_FALSE;
823 mg->mg_no_free_space = B_TRUE;
824 mg->mg_allocators = allocators;
826 mg->mg_allocator = kmem_zalloc(allocators *
827 sizeof (metaslab_group_allocator_t), KM_SLEEP);
828 for (int i = 0; i < allocators; i++) {
829 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
830 zfs_refcount_create_tracked(&mga->mga_alloc_queue_depth);
833 mg->mg_taskq = taskq_create("metaslab_group_taskq", metaslab_load_pct,
834 maxclsyspri, 10, INT_MAX, TASKQ_THREADS_CPU_PCT | TASKQ_DYNAMIC);
840 metaslab_group_destroy(metaslab_group_t *mg)
842 ASSERT(mg->mg_prev == NULL);
843 ASSERT(mg->mg_next == NULL);
845 * We may have gone below zero with the activation count
846 * either because we never activated in the first place or
847 * because we're done, and possibly removing the vdev.
849 ASSERT(mg->mg_activation_count <= 0);
851 taskq_destroy(mg->mg_taskq);
852 avl_destroy(&mg->mg_metaslab_tree);
853 mutex_destroy(&mg->mg_lock);
854 mutex_destroy(&mg->mg_ms_disabled_lock);
855 cv_destroy(&mg->mg_ms_disabled_cv);
857 for (int i = 0; i < mg->mg_allocators; i++) {
858 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
859 zfs_refcount_destroy(&mga->mga_alloc_queue_depth);
861 kmem_free(mg->mg_allocator, mg->mg_allocators *
862 sizeof (metaslab_group_allocator_t));
864 kmem_free(mg, sizeof (metaslab_group_t));
868 metaslab_group_activate(metaslab_group_t *mg)
870 metaslab_class_t *mc = mg->mg_class;
871 metaslab_group_t *mgprev, *mgnext;
873 ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER), !=, 0);
875 ASSERT(mc->mc_rotor != mg);
876 ASSERT(mg->mg_prev == NULL);
877 ASSERT(mg->mg_next == NULL);
878 ASSERT(mg->mg_activation_count <= 0);
880 if (++mg->mg_activation_count <= 0)
883 mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
884 metaslab_group_alloc_update(mg);
886 if ((mgprev = mc->mc_rotor) == NULL) {
890 mgnext = mgprev->mg_next;
891 mg->mg_prev = mgprev;
892 mg->mg_next = mgnext;
893 mgprev->mg_next = mg;
894 mgnext->mg_prev = mg;
900 * Passivate a metaslab group and remove it from the allocation rotor.
901 * Callers must hold both the SCL_ALLOC and SCL_ZIO lock prior to passivating
902 * a metaslab group. This function will momentarily drop spa_config_locks
903 * that are lower than the SCL_ALLOC lock (see comment below).
906 metaslab_group_passivate(metaslab_group_t *mg)
908 metaslab_class_t *mc = mg->mg_class;
909 spa_t *spa = mc->mc_spa;
910 metaslab_group_t *mgprev, *mgnext;
911 int locks = spa_config_held(spa, SCL_ALL, RW_WRITER);
913 ASSERT3U(spa_config_held(spa, SCL_ALLOC | SCL_ZIO, RW_WRITER), ==,
914 (SCL_ALLOC | SCL_ZIO));
916 if (--mg->mg_activation_count != 0) {
917 ASSERT(mc->mc_rotor != mg);
918 ASSERT(mg->mg_prev == NULL);
919 ASSERT(mg->mg_next == NULL);
920 ASSERT(mg->mg_activation_count < 0);
925 * The spa_config_lock is an array of rwlocks, ordered as
926 * follows (from highest to lowest):
927 * SCL_CONFIG > SCL_STATE > SCL_L2ARC > SCL_ALLOC >
928 * SCL_ZIO > SCL_FREE > SCL_VDEV
929 * (For more information about the spa_config_lock see spa_misc.c)
930 * The higher the lock, the broader its coverage. When we passivate
931 * a metaslab group, we must hold both the SCL_ALLOC and the SCL_ZIO
932 * config locks. However, the metaslab group's taskq might be trying
933 * to preload metaslabs so we must drop the SCL_ZIO lock and any
934 * lower locks to allow the I/O to complete. At a minimum,
935 * we continue to hold the SCL_ALLOC lock, which prevents any future
936 * allocations from taking place and any changes to the vdev tree.
938 spa_config_exit(spa, locks & ~(SCL_ZIO - 1), spa);
939 taskq_wait_outstanding(mg->mg_taskq, 0);
940 spa_config_enter(spa, locks & ~(SCL_ZIO - 1), spa, RW_WRITER);
941 metaslab_group_alloc_update(mg);
942 for (int i = 0; i < mg->mg_allocators; i++) {
943 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
944 metaslab_t *msp = mga->mga_primary;
946 mutex_enter(&msp->ms_lock);
947 metaslab_passivate(msp,
948 metaslab_weight_from_range_tree(msp));
949 mutex_exit(&msp->ms_lock);
951 msp = mga->mga_secondary;
953 mutex_enter(&msp->ms_lock);
954 metaslab_passivate(msp,
955 metaslab_weight_from_range_tree(msp));
956 mutex_exit(&msp->ms_lock);
960 mgprev = mg->mg_prev;
961 mgnext = mg->mg_next;
966 mc->mc_rotor = mgnext;
967 mgprev->mg_next = mgnext;
968 mgnext->mg_prev = mgprev;
976 metaslab_group_initialized(metaslab_group_t *mg)
978 vdev_t *vd = mg->mg_vd;
979 vdev_stat_t *vs = &vd->vdev_stat;
981 return (vs->vs_space != 0 && mg->mg_activation_count > 0);
985 metaslab_group_get_space(metaslab_group_t *mg)
987 return ((1ULL << mg->mg_vd->vdev_ms_shift) * mg->mg_vd->vdev_ms_count);
991 metaslab_group_histogram_verify(metaslab_group_t *mg)
994 vdev_t *vd = mg->mg_vd;
995 uint64_t ashift = vd->vdev_ashift;
998 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
1001 mg_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
1004 ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE, >=,
1005 SPACE_MAP_HISTOGRAM_SIZE + ashift);
1007 for (int m = 0; m < vd->vdev_ms_count; m++) {
1008 metaslab_t *msp = vd->vdev_ms[m];
1010 /* skip if not active or not a member */
1011 if (msp->ms_sm == NULL || msp->ms_group != mg)
1014 for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
1015 mg_hist[i + ashift] +=
1016 msp->ms_sm->sm_phys->smp_histogram[i];
1019 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i ++)
1020 VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
1022 kmem_free(mg_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
1026 metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
1028 metaslab_class_t *mc = mg->mg_class;
1029 uint64_t ashift = mg->mg_vd->vdev_ashift;
1031 ASSERT(MUTEX_HELD(&msp->ms_lock));
1032 if (msp->ms_sm == NULL)
1035 mutex_enter(&mg->mg_lock);
1036 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1037 mg->mg_histogram[i + ashift] +=
1038 msp->ms_sm->sm_phys->smp_histogram[i];
1039 mc->mc_histogram[i + ashift] +=
1040 msp->ms_sm->sm_phys->smp_histogram[i];
1042 mutex_exit(&mg->mg_lock);
1046 metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
1048 metaslab_class_t *mc = mg->mg_class;
1049 uint64_t ashift = mg->mg_vd->vdev_ashift;
1051 ASSERT(MUTEX_HELD(&msp->ms_lock));
1052 if (msp->ms_sm == NULL)
1055 mutex_enter(&mg->mg_lock);
1056 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1057 ASSERT3U(mg->mg_histogram[i + ashift], >=,
1058 msp->ms_sm->sm_phys->smp_histogram[i]);
1059 ASSERT3U(mc->mc_histogram[i + ashift], >=,
1060 msp->ms_sm->sm_phys->smp_histogram[i]);
1062 mg->mg_histogram[i + ashift] -=
1063 msp->ms_sm->sm_phys->smp_histogram[i];
1064 mc->mc_histogram[i + ashift] -=
1065 msp->ms_sm->sm_phys->smp_histogram[i];
1067 mutex_exit(&mg->mg_lock);
1071 metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
1073 ASSERT(msp->ms_group == NULL);
1074 mutex_enter(&mg->mg_lock);
1077 avl_add(&mg->mg_metaslab_tree, msp);
1078 mutex_exit(&mg->mg_lock);
1080 mutex_enter(&msp->ms_lock);
1081 metaslab_group_histogram_add(mg, msp);
1082 mutex_exit(&msp->ms_lock);
1086 metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
1088 mutex_enter(&msp->ms_lock);
1089 metaslab_group_histogram_remove(mg, msp);
1090 mutex_exit(&msp->ms_lock);
1092 mutex_enter(&mg->mg_lock);
1093 ASSERT(msp->ms_group == mg);
1094 avl_remove(&mg->mg_metaslab_tree, msp);
1096 metaslab_class_t *mc = msp->ms_group->mg_class;
1097 multilist_sublist_t *mls =
1098 multilist_sublist_lock_obj(mc->mc_metaslab_txg_list, msp);
1099 if (multilist_link_active(&msp->ms_class_txg_node))
1100 multilist_sublist_remove(mls, msp);
1101 multilist_sublist_unlock(mls);
1103 msp->ms_group = NULL;
1104 mutex_exit(&mg->mg_lock);
1108 metaslab_group_sort_impl(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1110 ASSERT(MUTEX_HELD(&msp->ms_lock));
1111 ASSERT(MUTEX_HELD(&mg->mg_lock));
1112 ASSERT(msp->ms_group == mg);
1114 avl_remove(&mg->mg_metaslab_tree, msp);
1115 msp->ms_weight = weight;
1116 avl_add(&mg->mg_metaslab_tree, msp);
1121 metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1124 * Although in principle the weight can be any value, in
1125 * practice we do not use values in the range [1, 511].
1127 ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
1128 ASSERT(MUTEX_HELD(&msp->ms_lock));
1130 mutex_enter(&mg->mg_lock);
1131 metaslab_group_sort_impl(mg, msp, weight);
1132 mutex_exit(&mg->mg_lock);
1136 * Calculate the fragmentation for a given metaslab group. We can use
1137 * a simple average here since all metaslabs within the group must have
1138 * the same size. The return value will be a value between 0 and 100
1139 * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
1140 * group have a fragmentation metric.
1143 metaslab_group_fragmentation(metaslab_group_t *mg)
1145 vdev_t *vd = mg->mg_vd;
1146 uint64_t fragmentation = 0;
1147 uint64_t valid_ms = 0;
1149 for (int m = 0; m < vd->vdev_ms_count; m++) {
1150 metaslab_t *msp = vd->vdev_ms[m];
1152 if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
1154 if (msp->ms_group != mg)
1158 fragmentation += msp->ms_fragmentation;
1161 if (valid_ms <= mg->mg_vd->vdev_ms_count / 2)
1162 return (ZFS_FRAG_INVALID);
1164 fragmentation /= valid_ms;
1165 ASSERT3U(fragmentation, <=, 100);
1166 return (fragmentation);
1170 * Determine if a given metaslab group should skip allocations. A metaslab
1171 * group should avoid allocations if its free capacity is less than the
1172 * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
1173 * zfs_mg_fragmentation_threshold and there is at least one metaslab group
1174 * that can still handle allocations. If the allocation throttle is enabled
1175 * then we skip allocations to devices that have reached their maximum
1176 * allocation queue depth unless the selected metaslab group is the only
1177 * eligible group remaining.
1180 metaslab_group_allocatable(metaslab_group_t *mg, metaslab_group_t *rotor,
1181 uint64_t psize, int allocator, int d)
1183 spa_t *spa = mg->mg_vd->vdev_spa;
1184 metaslab_class_t *mc = mg->mg_class;
1187 * We can only consider skipping this metaslab group if it's
1188 * in the normal metaslab class and there are other metaslab
1189 * groups to select from. Otherwise, we always consider it eligible
1192 if ((mc != spa_normal_class(spa) &&
1193 mc != spa_special_class(spa) &&
1194 mc != spa_dedup_class(spa)) ||
1199 * If the metaslab group's mg_allocatable flag is set (see comments
1200 * in metaslab_group_alloc_update() for more information) and
1201 * the allocation throttle is disabled then allow allocations to this
1202 * device. However, if the allocation throttle is enabled then
1203 * check if we have reached our allocation limit (mg_alloc_queue_depth)
1204 * to determine if we should allow allocations to this metaslab group.
1205 * If all metaslab groups are no longer considered allocatable
1206 * (mc_alloc_groups == 0) or we're trying to allocate the smallest
1207 * gang block size then we allow allocations on this metaslab group
1208 * regardless of the mg_allocatable or throttle settings.
1210 if (mg->mg_allocatable) {
1211 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
1213 uint64_t qmax = mga->mga_cur_max_alloc_queue_depth;
1215 if (!mc->mc_alloc_throttle_enabled)
1219 * If this metaslab group does not have any free space, then
1220 * there is no point in looking further.
1222 if (mg->mg_no_free_space)
1226 * Relax allocation throttling for ditto blocks. Due to
1227 * random imbalances in allocation it tends to push copies
1228 * to one vdev, that looks a bit better at the moment.
1230 qmax = qmax * (4 + d) / 4;
1232 qdepth = zfs_refcount_count(&mga->mga_alloc_queue_depth);
1235 * If this metaslab group is below its qmax or it's
1236 * the only allocatable metasable group, then attempt
1237 * to allocate from it.
1239 if (qdepth < qmax || mc->mc_alloc_groups == 1)
1241 ASSERT3U(mc->mc_alloc_groups, >, 1);
1244 * Since this metaslab group is at or over its qmax, we
1245 * need to determine if there are metaslab groups after this
1246 * one that might be able to handle this allocation. This is
1247 * racy since we can't hold the locks for all metaslab
1248 * groups at the same time when we make this check.
1250 for (metaslab_group_t *mgp = mg->mg_next;
1251 mgp != rotor; mgp = mgp->mg_next) {
1252 metaslab_group_allocator_t *mgap =
1253 &mgp->mg_allocator[allocator];
1254 qmax = mgap->mga_cur_max_alloc_queue_depth;
1255 qmax = qmax * (4 + d) / 4;
1257 zfs_refcount_count(&mgap->mga_alloc_queue_depth);
1260 * If there is another metaslab group that
1261 * might be able to handle the allocation, then
1262 * we return false so that we skip this group.
1264 if (qdepth < qmax && !mgp->mg_no_free_space)
1269 * We didn't find another group to handle the allocation
1270 * so we can't skip this metaslab group even though
1271 * we are at or over our qmax.
1275 } else if (mc->mc_alloc_groups == 0 || psize == SPA_MINBLOCKSIZE) {
1282 * ==========================================================================
1283 * Range tree callbacks
1284 * ==========================================================================
1288 * Comparison function for the private size-ordered tree using 32-bit
1289 * ranges. Tree is sorted by size, larger sizes at the end of the tree.
1292 metaslab_rangesize32_compare(const void *x1, const void *x2)
1294 const range_seg32_t *r1 = x1;
1295 const range_seg32_t *r2 = x2;
1297 uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1298 uint64_t rs_size2 = r2->rs_end - r2->rs_start;
1300 int cmp = TREE_CMP(rs_size1, rs_size2);
1304 return (TREE_CMP(r1->rs_start, r2->rs_start));
1308 * Comparison function for the private size-ordered tree using 64-bit
1309 * ranges. Tree is sorted by size, larger sizes at the end of the tree.
1312 metaslab_rangesize64_compare(const void *x1, const void *x2)
1314 const range_seg64_t *r1 = x1;
1315 const range_seg64_t *r2 = x2;
1317 uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1318 uint64_t rs_size2 = r2->rs_end - r2->rs_start;
1320 int cmp = TREE_CMP(rs_size1, rs_size2);
1324 return (TREE_CMP(r1->rs_start, r2->rs_start));
1326 typedef struct metaslab_rt_arg {
1327 zfs_btree_t *mra_bt;
1328 uint32_t mra_floor_shift;
1329 } metaslab_rt_arg_t;
1333 metaslab_rt_arg_t *mra;
1337 metaslab_size_sorted_add(void *arg, uint64_t start, uint64_t size)
1339 struct mssa_arg *mssap = arg;
1340 range_tree_t *rt = mssap->rt;
1341 metaslab_rt_arg_t *mrap = mssap->mra;
1342 range_seg_max_t seg = {0};
1343 rs_set_start(&seg, rt, start);
1344 rs_set_end(&seg, rt, start + size);
1345 metaslab_rt_add(rt, &seg, mrap);
1349 metaslab_size_tree_full_load(range_tree_t *rt)
1351 metaslab_rt_arg_t *mrap = rt->rt_arg;
1352 #ifdef _METASLAB_TRACING
1353 METASLABSTAT_BUMP(metaslabstat_reload_tree);
1355 ASSERT0(zfs_btree_numnodes(mrap->mra_bt));
1356 mrap->mra_floor_shift = 0;
1357 struct mssa_arg arg = {0};
1360 range_tree_walk(rt, metaslab_size_sorted_add, &arg);
1364 * Create any block allocator specific components. The current allocators
1365 * rely on using both a size-ordered range_tree_t and an array of uint64_t's.
1369 metaslab_rt_create(range_tree_t *rt, void *arg)
1371 metaslab_rt_arg_t *mrap = arg;
1372 zfs_btree_t *size_tree = mrap->mra_bt;
1375 int (*compare) (const void *, const void *);
1376 switch (rt->rt_type) {
1378 size = sizeof (range_seg32_t);
1379 compare = metaslab_rangesize32_compare;
1382 size = sizeof (range_seg64_t);
1383 compare = metaslab_rangesize64_compare;
1386 panic("Invalid range seg type %d", rt->rt_type);
1388 zfs_btree_create(size_tree, compare, size);
1389 mrap->mra_floor_shift = metaslab_by_size_min_shift;
1394 metaslab_rt_destroy(range_tree_t *rt, void *arg)
1396 metaslab_rt_arg_t *mrap = arg;
1397 zfs_btree_t *size_tree = mrap->mra_bt;
1399 zfs_btree_destroy(size_tree);
1400 kmem_free(mrap, sizeof (*mrap));
1405 metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg)
1407 metaslab_rt_arg_t *mrap = arg;
1408 zfs_btree_t *size_tree = mrap->mra_bt;
1410 if (rs_get_end(rs, rt) - rs_get_start(rs, rt) <
1411 (1 << mrap->mra_floor_shift))
1414 zfs_btree_add(size_tree, rs);
1419 metaslab_rt_remove(range_tree_t *rt, range_seg_t *rs, void *arg)
1421 metaslab_rt_arg_t *mrap = arg;
1422 zfs_btree_t *size_tree = mrap->mra_bt;
1424 if (rs_get_end(rs, rt) - rs_get_start(rs, rt) < (1 <<
1425 mrap->mra_floor_shift))
1428 zfs_btree_remove(size_tree, rs);
1433 metaslab_rt_vacate(range_tree_t *rt, void *arg)
1435 metaslab_rt_arg_t *mrap = arg;
1436 zfs_btree_t *size_tree = mrap->mra_bt;
1437 zfs_btree_clear(size_tree);
1438 zfs_btree_destroy(size_tree);
1440 metaslab_rt_create(rt, arg);
1443 static range_tree_ops_t metaslab_rt_ops = {
1444 .rtop_create = metaslab_rt_create,
1445 .rtop_destroy = metaslab_rt_destroy,
1446 .rtop_add = metaslab_rt_add,
1447 .rtop_remove = metaslab_rt_remove,
1448 .rtop_vacate = metaslab_rt_vacate
1452 * ==========================================================================
1453 * Common allocator routines
1454 * ==========================================================================
1458 * Return the maximum contiguous segment within the metaslab.
1461 metaslab_largest_allocatable(metaslab_t *msp)
1463 zfs_btree_t *t = &msp->ms_allocatable_by_size;
1468 if (zfs_btree_numnodes(t) == 0)
1469 metaslab_size_tree_full_load(msp->ms_allocatable);
1471 rs = zfs_btree_last(t, NULL);
1475 return (rs_get_end(rs, msp->ms_allocatable) - rs_get_start(rs,
1476 msp->ms_allocatable));
1480 * Return the maximum contiguous segment within the unflushed frees of this
1484 metaslab_largest_unflushed_free(metaslab_t *msp)
1486 ASSERT(MUTEX_HELD(&msp->ms_lock));
1488 if (msp->ms_unflushed_frees == NULL)
1491 if (zfs_btree_numnodes(&msp->ms_unflushed_frees_by_size) == 0)
1492 metaslab_size_tree_full_load(msp->ms_unflushed_frees);
1493 range_seg_t *rs = zfs_btree_last(&msp->ms_unflushed_frees_by_size,
1499 * When a range is freed from the metaslab, that range is added to
1500 * both the unflushed frees and the deferred frees. While the block
1501 * will eventually be usable, if the metaslab were loaded the range
1502 * would not be added to the ms_allocatable tree until TXG_DEFER_SIZE
1503 * txgs had passed. As a result, when attempting to estimate an upper
1504 * bound for the largest currently-usable free segment in the
1505 * metaslab, we need to not consider any ranges currently in the defer
1506 * trees. This algorithm approximates the largest available chunk in
1507 * the largest range in the unflushed_frees tree by taking the first
1508 * chunk. While this may be a poor estimate, it should only remain so
1509 * briefly and should eventually self-correct as frees are no longer
1510 * deferred. Similar logic applies to the ms_freed tree. See
1511 * metaslab_load() for more details.
1513 * There are two primary sources of inaccuracy in this estimate. Both
1514 * are tolerated for performance reasons. The first source is that we
1515 * only check the largest segment for overlaps. Smaller segments may
1516 * have more favorable overlaps with the other trees, resulting in
1517 * larger usable chunks. Second, we only look at the first chunk in
1518 * the largest segment; there may be other usable chunks in the
1519 * largest segment, but we ignore them.
1521 uint64_t rstart = rs_get_start(rs, msp->ms_unflushed_frees);
1522 uint64_t rsize = rs_get_end(rs, msp->ms_unflushed_frees) - rstart;
1523 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1526 boolean_t found = range_tree_find_in(msp->ms_defer[t], rstart,
1527 rsize, &start, &size);
1529 if (rstart == start)
1531 rsize = start - rstart;
1537 boolean_t found = range_tree_find_in(msp->ms_freed, rstart,
1538 rsize, &start, &size);
1540 rsize = start - rstart;
1545 static range_seg_t *
1546 metaslab_block_find(zfs_btree_t *t, range_tree_t *rt, uint64_t start,
1547 uint64_t size, zfs_btree_index_t *where)
1550 range_seg_max_t rsearch;
1552 rs_set_start(&rsearch, rt, start);
1553 rs_set_end(&rsearch, rt, start + size);
1555 rs = zfs_btree_find(t, &rsearch, where);
1557 rs = zfs_btree_next(t, where, where);
1563 #if defined(WITH_DF_BLOCK_ALLOCATOR) || \
1564 defined(WITH_CF_BLOCK_ALLOCATOR)
1566 * This is a helper function that can be used by the allocator to find a
1567 * suitable block to allocate. This will search the specified B-tree looking
1568 * for a block that matches the specified criteria.
1571 metaslab_block_picker(range_tree_t *rt, uint64_t *cursor, uint64_t size,
1572 uint64_t max_search)
1575 *cursor = rt->rt_start;
1576 zfs_btree_t *bt = &rt->rt_root;
1577 zfs_btree_index_t where;
1578 range_seg_t *rs = metaslab_block_find(bt, rt, *cursor, size, &where);
1579 uint64_t first_found;
1580 int count_searched = 0;
1583 first_found = rs_get_start(rs, rt);
1585 while (rs != NULL && (rs_get_start(rs, rt) - first_found <=
1586 max_search || count_searched < metaslab_min_search_count)) {
1587 uint64_t offset = rs_get_start(rs, rt);
1588 if (offset + size <= rs_get_end(rs, rt)) {
1589 *cursor = offset + size;
1592 rs = zfs_btree_next(bt, &where, &where);
1599 #endif /* WITH_DF/CF_BLOCK_ALLOCATOR */
1601 #if defined(WITH_DF_BLOCK_ALLOCATOR)
1603 * ==========================================================================
1604 * Dynamic Fit (df) block allocator
1606 * Search for a free chunk of at least this size, starting from the last
1607 * offset (for this alignment of block) looking for up to
1608 * metaslab_df_max_search bytes (16MB). If a large enough free chunk is not
1609 * found within 16MB, then return a free chunk of exactly the requested size (or
1612 * If it seems like searching from the last offset will be unproductive, skip
1613 * that and just return a free chunk of exactly the requested size (or larger).
1614 * This is based on metaslab_df_alloc_threshold and metaslab_df_free_pct. This
1615 * mechanism is probably not very useful and may be removed in the future.
1617 * The behavior when not searching can be changed to return the largest free
1618 * chunk, instead of a free chunk of exactly the requested size, by setting
1619 * metaslab_df_use_largest_segment.
1620 * ==========================================================================
1623 metaslab_df_alloc(metaslab_t *msp, uint64_t size)
1626 * Find the largest power of 2 block size that evenly divides the
1627 * requested size. This is used to try to allocate blocks with similar
1628 * alignment from the same area of the metaslab (i.e. same cursor
1629 * bucket) but it does not guarantee that other allocations sizes
1630 * may exist in the same region.
1632 uint64_t align = size & -size;
1633 uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
1634 range_tree_t *rt = msp->ms_allocatable;
1635 int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1638 ASSERT(MUTEX_HELD(&msp->ms_lock));
1641 * If we're running low on space, find a segment based on size,
1642 * rather than iterating based on offset.
1644 if (metaslab_largest_allocatable(msp) < metaslab_df_alloc_threshold ||
1645 free_pct < metaslab_df_free_pct) {
1648 offset = metaslab_block_picker(rt,
1649 cursor, size, metaslab_df_max_search);
1654 if (zfs_btree_numnodes(&msp->ms_allocatable_by_size) == 0)
1655 metaslab_size_tree_full_load(msp->ms_allocatable);
1656 if (metaslab_df_use_largest_segment) {
1657 /* use largest free segment */
1658 rs = zfs_btree_last(&msp->ms_allocatable_by_size, NULL);
1660 zfs_btree_index_t where;
1661 /* use segment of this size, or next largest */
1662 #ifdef _METASLAB_TRACING
1663 metaslab_rt_arg_t *mrap = msp->ms_allocatable->rt_arg;
1664 if (size < (1 << mrap->mra_floor_shift)) {
1666 metaslabstat_df_find_under_floor);
1669 rs = metaslab_block_find(&msp->ms_allocatable_by_size,
1670 rt, msp->ms_start, size, &where);
1672 if (rs != NULL && rs_get_start(rs, rt) + size <= rs_get_end(rs,
1674 offset = rs_get_start(rs, rt);
1675 *cursor = offset + size;
1682 static metaslab_ops_t metaslab_df_ops = {
1686 metaslab_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
1687 #endif /* WITH_DF_BLOCK_ALLOCATOR */
1689 #if defined(WITH_CF_BLOCK_ALLOCATOR)
1691 * ==========================================================================
1692 * Cursor fit block allocator -
1693 * Select the largest region in the metaslab, set the cursor to the beginning
1694 * of the range and the cursor_end to the end of the range. As allocations
1695 * are made advance the cursor. Continue allocating from the cursor until
1696 * the range is exhausted and then find a new range.
1697 * ==========================================================================
1700 metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
1702 range_tree_t *rt = msp->ms_allocatable;
1703 zfs_btree_t *t = &msp->ms_allocatable_by_size;
1704 uint64_t *cursor = &msp->ms_lbas[0];
1705 uint64_t *cursor_end = &msp->ms_lbas[1];
1706 uint64_t offset = 0;
1708 ASSERT(MUTEX_HELD(&msp->ms_lock));
1710 ASSERT3U(*cursor_end, >=, *cursor);
1712 if ((*cursor + size) > *cursor_end) {
1715 if (zfs_btree_numnodes(t) == 0)
1716 metaslab_size_tree_full_load(msp->ms_allocatable);
1717 rs = zfs_btree_last(t, NULL);
1718 if (rs == NULL || (rs_get_end(rs, rt) - rs_get_start(rs, rt)) <
1722 *cursor = rs_get_start(rs, rt);
1723 *cursor_end = rs_get_end(rs, rt);
1732 static metaslab_ops_t metaslab_cf_ops = {
1736 metaslab_ops_t *zfs_metaslab_ops = &metaslab_cf_ops;
1737 #endif /* WITH_CF_BLOCK_ALLOCATOR */
1739 #if defined(WITH_NDF_BLOCK_ALLOCATOR)
1741 * ==========================================================================
1742 * New dynamic fit allocator -
1743 * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1744 * contiguous blocks. If no region is found then just use the largest segment
1746 * ==========================================================================
1750 * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1751 * to request from the allocator.
1753 uint64_t metaslab_ndf_clump_shift = 4;
1756 metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
1758 zfs_btree_t *t = &msp->ms_allocatable->rt_root;
1759 range_tree_t *rt = msp->ms_allocatable;
1760 zfs_btree_index_t where;
1762 range_seg_max_t rsearch;
1763 uint64_t hbit = highbit64(size);
1764 uint64_t *cursor = &msp->ms_lbas[hbit - 1];
1765 uint64_t max_size = metaslab_largest_allocatable(msp);
1767 ASSERT(MUTEX_HELD(&msp->ms_lock));
1769 if (max_size < size)
1772 rs_set_start(&rsearch, rt, *cursor);
1773 rs_set_end(&rsearch, rt, *cursor + size);
1775 rs = zfs_btree_find(t, &rsearch, &where);
1776 if (rs == NULL || (rs_get_end(rs, rt) - rs_get_start(rs, rt)) < size) {
1777 t = &msp->ms_allocatable_by_size;
1779 rs_set_start(&rsearch, rt, 0);
1780 rs_set_end(&rsearch, rt, MIN(max_size, 1ULL << (hbit +
1781 metaslab_ndf_clump_shift)));
1783 rs = zfs_btree_find(t, &rsearch, &where);
1785 rs = zfs_btree_next(t, &where, &where);
1789 if ((rs_get_end(rs, rt) - rs_get_start(rs, rt)) >= size) {
1790 *cursor = rs_get_start(rs, rt) + size;
1791 return (rs_get_start(rs, rt));
1796 static metaslab_ops_t metaslab_ndf_ops = {
1800 metaslab_ops_t *zfs_metaslab_ops = &metaslab_ndf_ops;
1801 #endif /* WITH_NDF_BLOCK_ALLOCATOR */
1805 * ==========================================================================
1807 * ==========================================================================
1811 * Wait for any in-progress metaslab loads to complete.
1814 metaslab_load_wait(metaslab_t *msp)
1816 ASSERT(MUTEX_HELD(&msp->ms_lock));
1818 while (msp->ms_loading) {
1819 ASSERT(!msp->ms_loaded);
1820 cv_wait(&msp->ms_load_cv, &msp->ms_lock);
1825 * Wait for any in-progress flushing to complete.
1828 metaslab_flush_wait(metaslab_t *msp)
1830 ASSERT(MUTEX_HELD(&msp->ms_lock));
1832 while (msp->ms_flushing)
1833 cv_wait(&msp->ms_flush_cv, &msp->ms_lock);
1837 metaslab_idx_func(multilist_t *ml, void *arg)
1839 metaslab_t *msp = arg;
1840 return (msp->ms_id % multilist_get_num_sublists(ml));
1844 metaslab_allocated_space(metaslab_t *msp)
1846 return (msp->ms_allocated_space);
1850 * Verify that the space accounting on disk matches the in-core range_trees.
1853 metaslab_verify_space(metaslab_t *msp, uint64_t txg)
1855 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1856 uint64_t allocating = 0;
1857 uint64_t sm_free_space, msp_free_space;
1859 ASSERT(MUTEX_HELD(&msp->ms_lock));
1860 ASSERT(!msp->ms_condensing);
1862 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
1866 * We can only verify the metaslab space when we're called
1867 * from syncing context with a loaded metaslab that has an
1868 * allocated space map. Calling this in non-syncing context
1869 * does not provide a consistent view of the metaslab since
1870 * we're performing allocations in the future.
1872 if (txg != spa_syncing_txg(spa) || msp->ms_sm == NULL ||
1877 * Even though the smp_alloc field can get negative,
1878 * when it comes to a metaslab's space map, that should
1879 * never be the case.
1881 ASSERT3S(space_map_allocated(msp->ms_sm), >=, 0);
1883 ASSERT3U(space_map_allocated(msp->ms_sm), >=,
1884 range_tree_space(msp->ms_unflushed_frees));
1886 ASSERT3U(metaslab_allocated_space(msp), ==,
1887 space_map_allocated(msp->ms_sm) +
1888 range_tree_space(msp->ms_unflushed_allocs) -
1889 range_tree_space(msp->ms_unflushed_frees));
1891 sm_free_space = msp->ms_size - metaslab_allocated_space(msp);
1894 * Account for future allocations since we would have
1895 * already deducted that space from the ms_allocatable.
1897 for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
1899 range_tree_space(msp->ms_allocating[(txg + t) & TXG_MASK]);
1901 ASSERT3U(allocating + msp->ms_allocated_this_txg, ==,
1902 msp->ms_allocating_total);
1904 ASSERT3U(msp->ms_deferspace, ==,
1905 range_tree_space(msp->ms_defer[0]) +
1906 range_tree_space(msp->ms_defer[1]));
1908 msp_free_space = range_tree_space(msp->ms_allocatable) + allocating +
1909 msp->ms_deferspace + range_tree_space(msp->ms_freed);
1911 VERIFY3U(sm_free_space, ==, msp_free_space);
1915 metaslab_aux_histograms_clear(metaslab_t *msp)
1918 * Auxiliary histograms are only cleared when resetting them,
1919 * which can only happen while the metaslab is loaded.
1921 ASSERT(msp->ms_loaded);
1923 bzero(msp->ms_synchist, sizeof (msp->ms_synchist));
1924 for (int t = 0; t < TXG_DEFER_SIZE; t++)
1925 bzero(msp->ms_deferhist[t], sizeof (msp->ms_deferhist[t]));
1929 metaslab_aux_histogram_add(uint64_t *histogram, uint64_t shift,
1933 * This is modeled after space_map_histogram_add(), so refer to that
1934 * function for implementation details. We want this to work like
1935 * the space map histogram, and not the range tree histogram, as we
1936 * are essentially constructing a delta that will be later subtracted
1937 * from the space map histogram.
1940 for (int i = shift; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
1941 ASSERT3U(i, >=, idx + shift);
1942 histogram[idx] += rt->rt_histogram[i] << (i - idx - shift);
1944 if (idx < SPACE_MAP_HISTOGRAM_SIZE - 1) {
1945 ASSERT3U(idx + shift, ==, i);
1947 ASSERT3U(idx, <, SPACE_MAP_HISTOGRAM_SIZE);
1953 * Called at every sync pass that the metaslab gets synced.
1955 * The reason is that we want our auxiliary histograms to be updated
1956 * wherever the metaslab's space map histogram is updated. This way
1957 * we stay consistent on which parts of the metaslab space map's
1958 * histogram are currently not available for allocations (e.g because
1959 * they are in the defer, freed, and freeing trees).
1962 metaslab_aux_histograms_update(metaslab_t *msp)
1964 space_map_t *sm = msp->ms_sm;
1968 * This is similar to the metaslab's space map histogram updates
1969 * that take place in metaslab_sync(). The only difference is that
1970 * we only care about segments that haven't made it into the
1971 * ms_allocatable tree yet.
1973 if (msp->ms_loaded) {
1974 metaslab_aux_histograms_clear(msp);
1976 metaslab_aux_histogram_add(msp->ms_synchist,
1977 sm->sm_shift, msp->ms_freed);
1979 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1980 metaslab_aux_histogram_add(msp->ms_deferhist[t],
1981 sm->sm_shift, msp->ms_defer[t]);
1985 metaslab_aux_histogram_add(msp->ms_synchist,
1986 sm->sm_shift, msp->ms_freeing);
1990 * Called every time we are done syncing (writing to) the metaslab,
1991 * i.e. at the end of each sync pass.
1992 * [see the comment in metaslab_impl.h for ms_synchist, ms_deferhist]
1995 metaslab_aux_histograms_update_done(metaslab_t *msp, boolean_t defer_allowed)
1997 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1998 space_map_t *sm = msp->ms_sm;
2002 * We came here from metaslab_init() when creating/opening a
2003 * pool, looking at a metaslab that hasn't had any allocations
2010 * This is similar to the actions that we take for the ms_freed
2011 * and ms_defer trees in metaslab_sync_done().
2013 uint64_t hist_index = spa_syncing_txg(spa) % TXG_DEFER_SIZE;
2014 if (defer_allowed) {
2015 bcopy(msp->ms_synchist, msp->ms_deferhist[hist_index],
2016 sizeof (msp->ms_synchist));
2018 bzero(msp->ms_deferhist[hist_index],
2019 sizeof (msp->ms_deferhist[hist_index]));
2021 bzero(msp->ms_synchist, sizeof (msp->ms_synchist));
2025 * Ensure that the metaslab's weight and fragmentation are consistent
2026 * with the contents of the histogram (either the range tree's histogram
2027 * or the space map's depending whether the metaslab is loaded).
2030 metaslab_verify_weight_and_frag(metaslab_t *msp)
2032 ASSERT(MUTEX_HELD(&msp->ms_lock));
2034 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
2038 * We can end up here from vdev_remove_complete(), in which case we
2039 * cannot do these assertions because we hold spa config locks and
2040 * thus we are not allowed to read from the DMU.
2042 * We check if the metaslab group has been removed and if that's
2043 * the case we return immediately as that would mean that we are
2044 * here from the aforementioned code path.
2046 if (msp->ms_group == NULL)
2050 * Devices being removed always return a weight of 0 and leave
2051 * fragmentation and ms_max_size as is - there is nothing for
2052 * us to verify here.
2054 vdev_t *vd = msp->ms_group->mg_vd;
2055 if (vd->vdev_removing)
2059 * If the metaslab is dirty it probably means that we've done
2060 * some allocations or frees that have changed our histograms
2061 * and thus the weight.
2063 for (int t = 0; t < TXG_SIZE; t++) {
2064 if (txg_list_member(&vd->vdev_ms_list, msp, t))
2069 * This verification checks that our in-memory state is consistent
2070 * with what's on disk. If the pool is read-only then there aren't
2071 * any changes and we just have the initially-loaded state.
2073 if (!spa_writeable(msp->ms_group->mg_vd->vdev_spa))
2076 /* some extra verification for in-core tree if you can */
2077 if (msp->ms_loaded) {
2078 range_tree_stat_verify(msp->ms_allocatable);
2079 VERIFY(space_map_histogram_verify(msp->ms_sm,
2080 msp->ms_allocatable));
2083 uint64_t weight = msp->ms_weight;
2084 uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
2085 boolean_t space_based = WEIGHT_IS_SPACEBASED(msp->ms_weight);
2086 uint64_t frag = msp->ms_fragmentation;
2087 uint64_t max_segsize = msp->ms_max_size;
2090 msp->ms_fragmentation = 0;
2093 * This function is used for verification purposes and thus should
2094 * not introduce any side-effects/mutations on the system's state.
2096 * Regardless of whether metaslab_weight() thinks this metaslab
2097 * should be active or not, we want to ensure that the actual weight
2098 * (and therefore the value of ms_weight) would be the same if it
2099 * was to be recalculated at this point.
2101 * In addition we set the nodirty flag so metaslab_weight() does
2102 * not dirty the metaslab for future TXGs (e.g. when trying to
2103 * force condensing to upgrade the metaslab spacemaps).
2105 msp->ms_weight = metaslab_weight(msp, B_TRUE) | was_active;
2107 VERIFY3U(max_segsize, ==, msp->ms_max_size);
2110 * If the weight type changed then there is no point in doing
2111 * verification. Revert fields to their original values.
2113 if ((space_based && !WEIGHT_IS_SPACEBASED(msp->ms_weight)) ||
2114 (!space_based && WEIGHT_IS_SPACEBASED(msp->ms_weight))) {
2115 msp->ms_fragmentation = frag;
2116 msp->ms_weight = weight;
2120 VERIFY3U(msp->ms_fragmentation, ==, frag);
2121 VERIFY3U(msp->ms_weight, ==, weight);
2125 * If we're over the zfs_metaslab_mem_limit, select the loaded metaslab from
2126 * this class that was used longest ago, and attempt to unload it. We don't
2127 * want to spend too much time in this loop to prevent performance
2128 * degradation, and we expect that most of the time this operation will
2129 * succeed. Between that and the normal unloading processing during txg sync,
2130 * we expect this to keep the metaslab memory usage under control.
2133 metaslab_potentially_evict(metaslab_class_t *mc)
2136 uint64_t allmem = arc_all_memory();
2137 uint64_t inuse = spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2138 uint64_t size = spl_kmem_cache_entry_size(zfs_btree_leaf_cache);
2140 for (; allmem * zfs_metaslab_mem_limit / 100 < inuse * size &&
2141 tries < multilist_get_num_sublists(mc->mc_metaslab_txg_list) * 2;
2143 unsigned int idx = multilist_get_random_index(
2144 mc->mc_metaslab_txg_list);
2145 multilist_sublist_t *mls =
2146 multilist_sublist_lock(mc->mc_metaslab_txg_list, idx);
2147 metaslab_t *msp = multilist_sublist_head(mls);
2148 multilist_sublist_unlock(mls);
2149 while (msp != NULL && allmem * zfs_metaslab_mem_limit / 100 <
2151 VERIFY3P(mls, ==, multilist_sublist_lock(
2152 mc->mc_metaslab_txg_list, idx));
2154 metaslab_idx_func(mc->mc_metaslab_txg_list, msp));
2156 if (!multilist_link_active(&msp->ms_class_txg_node)) {
2157 multilist_sublist_unlock(mls);
2160 metaslab_t *next_msp = multilist_sublist_next(mls, msp);
2161 multilist_sublist_unlock(mls);
2163 * If the metaslab is currently loading there are two
2164 * cases. If it's the metaslab we're evicting, we
2165 * can't continue on or we'll panic when we attempt to
2166 * recursively lock the mutex. If it's another
2167 * metaslab that's loading, it can be safely skipped,
2168 * since we know it's very new and therefore not a
2169 * good eviction candidate. We check later once the
2170 * lock is held that the metaslab is fully loaded
2171 * before actually unloading it.
2173 if (msp->ms_loading) {
2176 spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2180 * We can't unload metaslabs with no spacemap because
2181 * they're not ready to be unloaded yet. We can't
2182 * unload metaslabs with outstanding allocations
2183 * because doing so could cause the metaslab's weight
2184 * to decrease while it's unloaded, which violates an
2185 * invariant that we use to prevent unnecessary
2186 * loading. We also don't unload metaslabs that are
2187 * currently active because they are high-weight
2188 * metaslabs that are likely to be used in the near
2191 mutex_enter(&msp->ms_lock);
2192 if (msp->ms_allocator == -1 && msp->ms_sm != NULL &&
2193 msp->ms_allocating_total == 0) {
2194 metaslab_unload(msp);
2196 mutex_exit(&msp->ms_lock);
2198 inuse = spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2205 metaslab_load_impl(metaslab_t *msp)
2209 ASSERT(MUTEX_HELD(&msp->ms_lock));
2210 ASSERT(msp->ms_loading);
2211 ASSERT(!msp->ms_condensing);
2214 * We temporarily drop the lock to unblock other operations while we
2215 * are reading the space map. Therefore, metaslab_sync() and
2216 * metaslab_sync_done() can run at the same time as we do.
2218 * If we are using the log space maps, metaslab_sync() can't write to
2219 * the metaslab's space map while we are loading as we only write to
2220 * it when we are flushing the metaslab, and that can't happen while
2221 * we are loading it.
2223 * If we are not using log space maps though, metaslab_sync() can
2224 * append to the space map while we are loading. Therefore we load
2225 * only entries that existed when we started the load. Additionally,
2226 * metaslab_sync_done() has to wait for the load to complete because
2227 * there are potential races like metaslab_load() loading parts of the
2228 * space map that are currently being appended by metaslab_sync(). If
2229 * we didn't, the ms_allocatable would have entries that
2230 * metaslab_sync_done() would try to re-add later.
2232 * That's why before dropping the lock we remember the synced length
2233 * of the metaslab and read up to that point of the space map,
2234 * ignoring entries appended by metaslab_sync() that happen after we
2237 uint64_t length = msp->ms_synced_length;
2238 mutex_exit(&msp->ms_lock);
2240 hrtime_t load_start = gethrtime();
2241 metaslab_rt_arg_t *mrap;
2242 if (msp->ms_allocatable->rt_arg == NULL) {
2243 mrap = kmem_zalloc(sizeof (*mrap), KM_SLEEP);
2245 mrap = msp->ms_allocatable->rt_arg;
2246 msp->ms_allocatable->rt_ops = NULL;
2247 msp->ms_allocatable->rt_arg = NULL;
2249 mrap->mra_bt = &msp->ms_allocatable_by_size;
2250 mrap->mra_floor_shift = metaslab_by_size_min_shift;
2252 if (msp->ms_sm != NULL) {
2253 error = space_map_load_length(msp->ms_sm, msp->ms_allocatable,
2256 /* Now, populate the size-sorted tree. */
2257 metaslab_rt_create(msp->ms_allocatable, mrap);
2258 msp->ms_allocatable->rt_ops = &metaslab_rt_ops;
2259 msp->ms_allocatable->rt_arg = mrap;
2261 struct mssa_arg arg = {0};
2262 arg.rt = msp->ms_allocatable;
2264 range_tree_walk(msp->ms_allocatable, metaslab_size_sorted_add,
2268 * Add the size-sorted tree first, since we don't need to load
2269 * the metaslab from the spacemap.
2271 metaslab_rt_create(msp->ms_allocatable, mrap);
2272 msp->ms_allocatable->rt_ops = &metaslab_rt_ops;
2273 msp->ms_allocatable->rt_arg = mrap;
2275 * The space map has not been allocated yet, so treat
2276 * all the space in the metaslab as free and add it to the
2277 * ms_allocatable tree.
2279 range_tree_add(msp->ms_allocatable,
2280 msp->ms_start, msp->ms_size);
2282 if (msp->ms_freed != NULL) {
2284 * If the ms_sm doesn't exist, this means that this
2285 * metaslab hasn't gone through metaslab_sync() and
2286 * thus has never been dirtied. So we shouldn't
2287 * expect any unflushed allocs or frees from previous
2290 * Note: ms_freed and all the other trees except for
2291 * the ms_allocatable, can be NULL at this point only
2292 * if this is a new metaslab of a vdev that just got
2295 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
2296 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
2301 * We need to grab the ms_sync_lock to prevent metaslab_sync() from
2302 * changing the ms_sm (or log_sm) and the metaslab's range trees
2303 * while we are about to use them and populate the ms_allocatable.
2304 * The ms_lock is insufficient for this because metaslab_sync() doesn't
2305 * hold the ms_lock while writing the ms_checkpointing tree to disk.
2307 mutex_enter(&msp->ms_sync_lock);
2308 mutex_enter(&msp->ms_lock);
2310 ASSERT(!msp->ms_condensing);
2311 ASSERT(!msp->ms_flushing);
2314 mutex_exit(&msp->ms_sync_lock);
2318 ASSERT3P(msp->ms_group, !=, NULL);
2319 msp->ms_loaded = B_TRUE;
2322 * Apply all the unflushed changes to ms_allocatable right
2323 * away so any manipulations we do below have a clear view
2324 * of what is allocated and what is free.
2326 range_tree_walk(msp->ms_unflushed_allocs,
2327 range_tree_remove, msp->ms_allocatable);
2328 range_tree_walk(msp->ms_unflushed_frees,
2329 range_tree_add, msp->ms_allocatable);
2331 msp->ms_loaded = B_TRUE;
2333 ASSERT3P(msp->ms_group, !=, NULL);
2334 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2335 if (spa_syncing_log_sm(spa) != NULL) {
2336 ASSERT(spa_feature_is_enabled(spa,
2337 SPA_FEATURE_LOG_SPACEMAP));
2340 * If we use a log space map we add all the segments
2341 * that are in ms_unflushed_frees so they are available
2344 * ms_allocatable needs to contain all free segments
2345 * that are ready for allocations (thus not segments
2346 * from ms_freeing, ms_freed, and the ms_defer trees).
2347 * But if we grab the lock in this code path at a sync
2348 * pass later that 1, then it also contains the
2349 * segments of ms_freed (they were added to it earlier
2350 * in this path through ms_unflushed_frees). So we
2351 * need to remove all the segments that exist in
2352 * ms_freed from ms_allocatable as they will be added
2353 * later in metaslab_sync_done().
2355 * When there's no log space map, the ms_allocatable
2356 * correctly doesn't contain any segments that exist
2357 * in ms_freed [see ms_synced_length].
2359 range_tree_walk(msp->ms_freed,
2360 range_tree_remove, msp->ms_allocatable);
2364 * If we are not using the log space map, ms_allocatable
2365 * contains the segments that exist in the ms_defer trees
2366 * [see ms_synced_length]. Thus we need to remove them
2367 * from ms_allocatable as they will be added again in
2368 * metaslab_sync_done().
2370 * If we are using the log space map, ms_allocatable still
2371 * contains the segments that exist in the ms_defer trees.
2372 * Not because it read them through the ms_sm though. But
2373 * because these segments are part of ms_unflushed_frees
2374 * whose segments we add to ms_allocatable earlier in this
2377 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2378 range_tree_walk(msp->ms_defer[t],
2379 range_tree_remove, msp->ms_allocatable);
2383 * Call metaslab_recalculate_weight_and_sort() now that the
2384 * metaslab is loaded so we get the metaslab's real weight.
2386 * Unless this metaslab was created with older software and
2387 * has not yet been converted to use segment-based weight, we
2388 * expect the new weight to be better or equal to the weight
2389 * that the metaslab had while it was not loaded. This is
2390 * because the old weight does not take into account the
2391 * consolidation of adjacent segments between TXGs. [see
2392 * comment for ms_synchist and ms_deferhist[] for more info]
2394 uint64_t weight = msp->ms_weight;
2395 uint64_t max_size = msp->ms_max_size;
2396 metaslab_recalculate_weight_and_sort(msp);
2397 if (!WEIGHT_IS_SPACEBASED(weight))
2398 ASSERT3U(weight, <=, msp->ms_weight);
2399 msp->ms_max_size = metaslab_largest_allocatable(msp);
2400 ASSERT3U(max_size, <=, msp->ms_max_size);
2401 hrtime_t load_end = gethrtime();
2402 msp->ms_load_time = load_end;
2403 zfs_dbgmsg("metaslab_load: txg %llu, spa %s, vdev_id %llu, "
2404 "ms_id %llu, smp_length %llu, "
2405 "unflushed_allocs %llu, unflushed_frees %llu, "
2406 "freed %llu, defer %llu + %llu, unloaded time %llu ms, "
2407 "loading_time %lld ms, ms_max_size %llu, "
2408 "max size error %lld, "
2409 "old_weight %llx, new_weight %llx",
2410 spa_syncing_txg(spa), spa_name(spa),
2411 msp->ms_group->mg_vd->vdev_id, msp->ms_id,
2412 space_map_length(msp->ms_sm),
2413 range_tree_space(msp->ms_unflushed_allocs),
2414 range_tree_space(msp->ms_unflushed_frees),
2415 range_tree_space(msp->ms_freed),
2416 range_tree_space(msp->ms_defer[0]),
2417 range_tree_space(msp->ms_defer[1]),
2418 (longlong_t)((load_start - msp->ms_unload_time) / 1000000),
2419 (longlong_t)((load_end - load_start) / 1000000),
2420 msp->ms_max_size, msp->ms_max_size - max_size,
2421 weight, msp->ms_weight);
2423 metaslab_verify_space(msp, spa_syncing_txg(spa));
2424 mutex_exit(&msp->ms_sync_lock);
2429 metaslab_load(metaslab_t *msp)
2431 ASSERT(MUTEX_HELD(&msp->ms_lock));
2434 * There may be another thread loading the same metaslab, if that's
2435 * the case just wait until the other thread is done and return.
2437 metaslab_load_wait(msp);
2440 VERIFY(!msp->ms_loading);
2441 ASSERT(!msp->ms_condensing);
2444 * We set the loading flag BEFORE potentially dropping the lock to
2445 * wait for an ongoing flush (see ms_flushing below). This way other
2446 * threads know that there is already a thread that is loading this
2449 msp->ms_loading = B_TRUE;
2452 * Wait for any in-progress flushing to finish as we drop the ms_lock
2453 * both here (during space_map_load()) and in metaslab_flush() (when
2454 * we flush our changes to the ms_sm).
2456 if (msp->ms_flushing)
2457 metaslab_flush_wait(msp);
2460 * In the possibility that we were waiting for the metaslab to be
2461 * flushed (where we temporarily dropped the ms_lock), ensure that
2462 * no one else loaded the metaslab somehow.
2464 ASSERT(!msp->ms_loaded);
2467 * If we're loading a metaslab in the normal class, consider evicting
2468 * another one to keep our memory usage under the limit defined by the
2469 * zfs_metaslab_mem_limit tunable.
2471 if (spa_normal_class(msp->ms_group->mg_class->mc_spa) ==
2472 msp->ms_group->mg_class) {
2473 metaslab_potentially_evict(msp->ms_group->mg_class);
2476 int error = metaslab_load_impl(msp);
2478 ASSERT(MUTEX_HELD(&msp->ms_lock));
2479 msp->ms_loading = B_FALSE;
2480 cv_broadcast(&msp->ms_load_cv);
2486 metaslab_unload(metaslab_t *msp)
2488 ASSERT(MUTEX_HELD(&msp->ms_lock));
2491 * This can happen if a metaslab is selected for eviction (in
2492 * metaslab_potentially_evict) and then unloaded during spa_sync (via
2493 * metaslab_class_evict_old).
2495 if (!msp->ms_loaded)
2498 range_tree_vacate(msp->ms_allocatable, NULL, NULL);
2499 msp->ms_loaded = B_FALSE;
2500 msp->ms_unload_time = gethrtime();
2502 msp->ms_activation_weight = 0;
2503 msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
2505 if (msp->ms_group != NULL) {
2506 metaslab_class_t *mc = msp->ms_group->mg_class;
2507 multilist_sublist_t *mls =
2508 multilist_sublist_lock_obj(mc->mc_metaslab_txg_list, msp);
2509 if (multilist_link_active(&msp->ms_class_txg_node))
2510 multilist_sublist_remove(mls, msp);
2511 multilist_sublist_unlock(mls);
2513 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2514 zfs_dbgmsg("metaslab_unload: txg %llu, spa %s, vdev_id %llu, "
2515 "ms_id %llu, weight %llx, "
2516 "selected txg %llu (%llu ms ago), alloc_txg %llu, "
2517 "loaded %llu ms ago, max_size %llu",
2518 spa_syncing_txg(spa), spa_name(spa),
2519 msp->ms_group->mg_vd->vdev_id, msp->ms_id,
2521 msp->ms_selected_txg,
2522 (msp->ms_unload_time - msp->ms_selected_time) / 1000 / 1000,
2524 (msp->ms_unload_time - msp->ms_load_time) / 1000 / 1000,
2529 * We explicitly recalculate the metaslab's weight based on its space
2530 * map (as it is now not loaded). We want unload metaslabs to always
2531 * have their weights calculated from the space map histograms, while
2532 * loaded ones have it calculated from their in-core range tree
2533 * [see metaslab_load()]. This way, the weight reflects the information
2534 * available in-core, whether it is loaded or not.
2536 * If ms_group == NULL means that we came here from metaslab_fini(),
2537 * at which point it doesn't make sense for us to do the recalculation
2540 if (msp->ms_group != NULL)
2541 metaslab_recalculate_weight_and_sort(msp);
2545 * We want to optimize the memory use of the per-metaslab range
2546 * trees. To do this, we store the segments in the range trees in
2547 * units of sectors, zero-indexing from the start of the metaslab. If
2548 * the vdev_ms_shift - the vdev_ashift is less than 32, we can store
2549 * the ranges using two uint32_ts, rather than two uint64_ts.
2552 metaslab_calculate_range_tree_type(vdev_t *vdev, metaslab_t *msp,
2553 uint64_t *start, uint64_t *shift)
2555 if (vdev->vdev_ms_shift - vdev->vdev_ashift < 32 &&
2556 !zfs_metaslab_force_large_segs) {
2557 *shift = vdev->vdev_ashift;
2558 *start = msp->ms_start;
2559 return (RANGE_SEG32);
2563 return (RANGE_SEG64);
2568 metaslab_set_selected_txg(metaslab_t *msp, uint64_t txg)
2570 ASSERT(MUTEX_HELD(&msp->ms_lock));
2571 metaslab_class_t *mc = msp->ms_group->mg_class;
2572 multilist_sublist_t *mls =
2573 multilist_sublist_lock_obj(mc->mc_metaslab_txg_list, msp);
2574 if (multilist_link_active(&msp->ms_class_txg_node))
2575 multilist_sublist_remove(mls, msp);
2576 msp->ms_selected_txg = txg;
2577 msp->ms_selected_time = gethrtime();
2578 multilist_sublist_insert_tail(mls, msp);
2579 multilist_sublist_unlock(mls);
2583 metaslab_space_update(vdev_t *vd, metaslab_class_t *mc, int64_t alloc_delta,
2584 int64_t defer_delta, int64_t space_delta)
2586 vdev_space_update(vd, alloc_delta, defer_delta, space_delta);
2588 ASSERT3P(vd->vdev_spa->spa_root_vdev, ==, vd->vdev_parent);
2589 ASSERT(vd->vdev_ms_count != 0);
2591 metaslab_class_space_update(mc, alloc_delta, defer_delta, space_delta,
2592 vdev_deflated_space(vd, space_delta));
2596 metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object,
2597 uint64_t txg, metaslab_t **msp)
2599 vdev_t *vd = mg->mg_vd;
2600 spa_t *spa = vd->vdev_spa;
2601 objset_t *mos = spa->spa_meta_objset;
2605 ms = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
2606 mutex_init(&ms->ms_lock, NULL, MUTEX_DEFAULT, NULL);
2607 mutex_init(&ms->ms_sync_lock, NULL, MUTEX_DEFAULT, NULL);
2608 cv_init(&ms->ms_load_cv, NULL, CV_DEFAULT, NULL);
2609 cv_init(&ms->ms_flush_cv, NULL, CV_DEFAULT, NULL);
2610 multilist_link_init(&ms->ms_class_txg_node);
2613 ms->ms_start = id << vd->vdev_ms_shift;
2614 ms->ms_size = 1ULL << vd->vdev_ms_shift;
2615 ms->ms_allocator = -1;
2616 ms->ms_new = B_TRUE;
2619 * We only open space map objects that already exist. All others
2620 * will be opened when we finally allocate an object for it.
2623 * When called from vdev_expand(), we can't call into the DMU as
2624 * we are holding the spa_config_lock as a writer and we would
2625 * deadlock [see relevant comment in vdev_metaslab_init()]. in
2626 * that case, the object parameter is zero though, so we won't
2627 * call into the DMU.
2630 error = space_map_open(&ms->ms_sm, mos, object, ms->ms_start,
2631 ms->ms_size, vd->vdev_ashift);
2634 kmem_free(ms, sizeof (metaslab_t));
2638 ASSERT(ms->ms_sm != NULL);
2639 ms->ms_allocated_space = space_map_allocated(ms->ms_sm);
2642 range_seg_type_t type;
2643 uint64_t shift, start;
2644 type = metaslab_calculate_range_tree_type(vd, ms, &start, &shift);
2647 * We create the ms_allocatable here, but we don't create the
2648 * other range trees until metaslab_sync_done(). This serves
2649 * two purposes: it allows metaslab_sync_done() to detect the
2650 * addition of new space; and for debugging, it ensures that
2651 * we'd data fault on any attempt to use this metaslab before
2654 ms->ms_allocatable = range_tree_create(NULL, type, NULL, start, shift);
2656 ms->ms_trim = range_tree_create(NULL, type, NULL, start, shift);
2658 metaslab_group_add(mg, ms);
2659 metaslab_set_fragmentation(ms, B_FALSE);
2662 * If we're opening an existing pool (txg == 0) or creating
2663 * a new one (txg == TXG_INITIAL), all space is available now.
2664 * If we're adding space to an existing pool, the new space
2665 * does not become available until after this txg has synced.
2666 * The metaslab's weight will also be initialized when we sync
2667 * out this txg. This ensures that we don't attempt to allocate
2668 * from it before we have initialized it completely.
2670 if (txg <= TXG_INITIAL) {
2671 metaslab_sync_done(ms, 0);
2672 metaslab_space_update(vd, mg->mg_class,
2673 metaslab_allocated_space(ms), 0, 0);
2677 vdev_dirty(vd, 0, NULL, txg);
2678 vdev_dirty(vd, VDD_METASLAB, ms, txg);
2687 metaslab_fini_flush_data(metaslab_t *msp)
2689 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2691 if (metaslab_unflushed_txg(msp) == 0) {
2692 ASSERT3P(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL),
2696 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
2698 mutex_enter(&spa->spa_flushed_ms_lock);
2699 avl_remove(&spa->spa_metaslabs_by_flushed, msp);
2700 mutex_exit(&spa->spa_flushed_ms_lock);
2702 spa_log_sm_decrement_mscount(spa, metaslab_unflushed_txg(msp));
2703 spa_log_summary_decrement_mscount(spa, metaslab_unflushed_txg(msp));
2707 metaslab_unflushed_changes_memused(metaslab_t *ms)
2709 return ((range_tree_numsegs(ms->ms_unflushed_allocs) +
2710 range_tree_numsegs(ms->ms_unflushed_frees)) *
2711 ms->ms_unflushed_allocs->rt_root.bt_elem_size);
2715 metaslab_fini(metaslab_t *msp)
2717 metaslab_group_t *mg = msp->ms_group;
2718 vdev_t *vd = mg->mg_vd;
2719 spa_t *spa = vd->vdev_spa;
2721 metaslab_fini_flush_data(msp);
2723 metaslab_group_remove(mg, msp);
2725 mutex_enter(&msp->ms_lock);
2726 VERIFY(msp->ms_group == NULL);
2727 metaslab_space_update(vd, mg->mg_class,
2728 -metaslab_allocated_space(msp), 0, -msp->ms_size);
2730 space_map_close(msp->ms_sm);
2733 metaslab_unload(msp);
2734 range_tree_destroy(msp->ms_allocatable);
2735 range_tree_destroy(msp->ms_freeing);
2736 range_tree_destroy(msp->ms_freed);
2738 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
2739 metaslab_unflushed_changes_memused(msp));
2740 spa->spa_unflushed_stats.sus_memused -=
2741 metaslab_unflushed_changes_memused(msp);
2742 range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
2743 range_tree_destroy(msp->ms_unflushed_allocs);
2744 range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
2745 range_tree_destroy(msp->ms_unflushed_frees);
2747 for (int t = 0; t < TXG_SIZE; t++) {
2748 range_tree_destroy(msp->ms_allocating[t]);
2751 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2752 range_tree_destroy(msp->ms_defer[t]);
2754 ASSERT0(msp->ms_deferspace);
2756 range_tree_destroy(msp->ms_checkpointing);
2758 for (int t = 0; t < TXG_SIZE; t++)
2759 ASSERT(!txg_list_member(&vd->vdev_ms_list, msp, t));
2761 range_tree_vacate(msp->ms_trim, NULL, NULL);
2762 range_tree_destroy(msp->ms_trim);
2764 mutex_exit(&msp->ms_lock);
2765 cv_destroy(&msp->ms_load_cv);
2766 cv_destroy(&msp->ms_flush_cv);
2767 mutex_destroy(&msp->ms_lock);
2768 mutex_destroy(&msp->ms_sync_lock);
2769 ASSERT3U(msp->ms_allocator, ==, -1);
2771 kmem_free(msp, sizeof (metaslab_t));
2774 #define FRAGMENTATION_TABLE_SIZE 17
2777 * This table defines a segment size based fragmentation metric that will
2778 * allow each metaslab to derive its own fragmentation value. This is done
2779 * by calculating the space in each bucket of the spacemap histogram and
2780 * multiplying that by the fragmentation metric in this table. Doing
2781 * this for all buckets and dividing it by the total amount of free
2782 * space in this metaslab (i.e. the total free space in all buckets) gives
2783 * us the fragmentation metric. This means that a high fragmentation metric
2784 * equates to most of the free space being comprised of small segments.
2785 * Conversely, if the metric is low, then most of the free space is in
2786 * large segments. A 10% change in fragmentation equates to approximately
2787 * double the number of segments.
2789 * This table defines 0% fragmented space using 16MB segments. Testing has
2790 * shown that segments that are greater than or equal to 16MB do not suffer
2791 * from drastic performance problems. Using this value, we derive the rest
2792 * of the table. Since the fragmentation value is never stored on disk, it
2793 * is possible to change these calculations in the future.
2795 int zfs_frag_table[FRAGMENTATION_TABLE_SIZE] = {
2815 * Calculate the metaslab's fragmentation metric and set ms_fragmentation.
2816 * Setting this value to ZFS_FRAG_INVALID means that the metaslab has not
2817 * been upgraded and does not support this metric. Otherwise, the return
2818 * value should be in the range [0, 100].
2821 metaslab_set_fragmentation(metaslab_t *msp, boolean_t nodirty)
2823 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2824 uint64_t fragmentation = 0;
2826 boolean_t feature_enabled = spa_feature_is_enabled(spa,
2827 SPA_FEATURE_SPACEMAP_HISTOGRAM);
2829 if (!feature_enabled) {
2830 msp->ms_fragmentation = ZFS_FRAG_INVALID;
2835 * A null space map means that the entire metaslab is free
2836 * and thus is not fragmented.
2838 if (msp->ms_sm == NULL) {
2839 msp->ms_fragmentation = 0;
2844 * If this metaslab's space map has not been upgraded, flag it
2845 * so that we upgrade next time we encounter it.
2847 if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
2848 uint64_t txg = spa_syncing_txg(spa);
2849 vdev_t *vd = msp->ms_group->mg_vd;
2852 * If we've reached the final dirty txg, then we must
2853 * be shutting down the pool. We don't want to dirty
2854 * any data past this point so skip setting the condense
2855 * flag. We can retry this action the next time the pool
2856 * is imported. We also skip marking this metaslab for
2857 * condensing if the caller has explicitly set nodirty.
2860 spa_writeable(spa) && txg < spa_final_dirty_txg(spa)) {
2861 msp->ms_condense_wanted = B_TRUE;
2862 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
2863 zfs_dbgmsg("txg %llu, requesting force condense: "
2864 "ms_id %llu, vdev_id %llu", txg, msp->ms_id,
2867 msp->ms_fragmentation = ZFS_FRAG_INVALID;
2871 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
2873 uint8_t shift = msp->ms_sm->sm_shift;
2875 int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
2876 FRAGMENTATION_TABLE_SIZE - 1);
2878 if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
2881 space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
2884 ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
2885 fragmentation += space * zfs_frag_table[idx];
2889 fragmentation /= total;
2890 ASSERT3U(fragmentation, <=, 100);
2892 msp->ms_fragmentation = fragmentation;
2896 * Compute a weight -- a selection preference value -- for the given metaslab.
2897 * This is based on the amount of free space, the level of fragmentation,
2898 * the LBA range, and whether the metaslab is loaded.
2901 metaslab_space_weight(metaslab_t *msp)
2903 metaslab_group_t *mg = msp->ms_group;
2904 vdev_t *vd = mg->mg_vd;
2905 uint64_t weight, space;
2907 ASSERT(MUTEX_HELD(&msp->ms_lock));
2910 * The baseline weight is the metaslab's free space.
2912 space = msp->ms_size - metaslab_allocated_space(msp);
2914 if (metaslab_fragmentation_factor_enabled &&
2915 msp->ms_fragmentation != ZFS_FRAG_INVALID) {
2917 * Use the fragmentation information to inversely scale
2918 * down the baseline weight. We need to ensure that we
2919 * don't exclude this metaslab completely when it's 100%
2920 * fragmented. To avoid this we reduce the fragmented value
2923 space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
2926 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
2927 * this metaslab again. The fragmentation metric may have
2928 * decreased the space to something smaller than
2929 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
2930 * so that we can consume any remaining space.
2932 if (space > 0 && space < SPA_MINBLOCKSIZE)
2933 space = SPA_MINBLOCKSIZE;
2938 * Modern disks have uniform bit density and constant angular velocity.
2939 * Therefore, the outer recording zones are faster (higher bandwidth)
2940 * than the inner zones by the ratio of outer to inner track diameter,
2941 * which is typically around 2:1. We account for this by assigning
2942 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
2943 * In effect, this means that we'll select the metaslab with the most
2944 * free bandwidth rather than simply the one with the most free space.
2946 if (!vd->vdev_nonrot && metaslab_lba_weighting_enabled) {
2947 weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
2948 ASSERT(weight >= space && weight <= 2 * space);
2952 * If this metaslab is one we're actively using, adjust its
2953 * weight to make it preferable to any inactive metaslab so
2954 * we'll polish it off. If the fragmentation on this metaslab
2955 * has exceed our threshold, then don't mark it active.
2957 if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
2958 msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
2959 weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
2962 WEIGHT_SET_SPACEBASED(weight);
2967 * Return the weight of the specified metaslab, according to the segment-based
2968 * weighting algorithm. The metaslab must be loaded. This function can
2969 * be called within a sync pass since it relies only on the metaslab's
2970 * range tree which is always accurate when the metaslab is loaded.
2973 metaslab_weight_from_range_tree(metaslab_t *msp)
2975 uint64_t weight = 0;
2976 uint32_t segments = 0;
2978 ASSERT(msp->ms_loaded);
2980 for (int i = RANGE_TREE_HISTOGRAM_SIZE - 1; i >= SPA_MINBLOCKSHIFT;
2982 uint8_t shift = msp->ms_group->mg_vd->vdev_ashift;
2983 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
2986 segments += msp->ms_allocatable->rt_histogram[i];
2989 * The range tree provides more precision than the space map
2990 * and must be downgraded so that all values fit within the
2991 * space map's histogram. This allows us to compare loaded
2992 * vs. unloaded metaslabs to determine which metaslab is
2993 * considered "best".
2998 if (segments != 0) {
2999 WEIGHT_SET_COUNT(weight, segments);
3000 WEIGHT_SET_INDEX(weight, i);
3001 WEIGHT_SET_ACTIVE(weight, 0);
3009 * Calculate the weight based on the on-disk histogram. Should be applied
3010 * only to unloaded metaslabs (i.e no incoming allocations) in-order to
3011 * give results consistent with the on-disk state
3014 metaslab_weight_from_spacemap(metaslab_t *msp)
3016 space_map_t *sm = msp->ms_sm;
3017 ASSERT(!msp->ms_loaded);
3019 ASSERT3U(space_map_object(sm), !=, 0);
3020 ASSERT3U(sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
3023 * Create a joint histogram from all the segments that have made
3024 * it to the metaslab's space map histogram, that are not yet
3025 * available for allocation because they are still in the freeing
3026 * pipeline (e.g. freeing, freed, and defer trees). Then subtract
3027 * these segments from the space map's histogram to get a more
3030 uint64_t deferspace_histogram[SPACE_MAP_HISTOGRAM_SIZE] = {0};
3031 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
3032 deferspace_histogram[i] += msp->ms_synchist[i];
3033 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3034 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
3035 deferspace_histogram[i] += msp->ms_deferhist[t][i];
3039 uint64_t weight = 0;
3040 for (int i = SPACE_MAP_HISTOGRAM_SIZE - 1; i >= 0; i--) {
3041 ASSERT3U(sm->sm_phys->smp_histogram[i], >=,
3042 deferspace_histogram[i]);
3044 sm->sm_phys->smp_histogram[i] - deferspace_histogram[i];
3046 WEIGHT_SET_COUNT(weight, count);
3047 WEIGHT_SET_INDEX(weight, i + sm->sm_shift);
3048 WEIGHT_SET_ACTIVE(weight, 0);
3056 * Compute a segment-based weight for the specified metaslab. The weight
3057 * is determined by highest bucket in the histogram. The information
3058 * for the highest bucket is encoded into the weight value.
3061 metaslab_segment_weight(metaslab_t *msp)
3063 metaslab_group_t *mg = msp->ms_group;
3064 uint64_t weight = 0;
3065 uint8_t shift = mg->mg_vd->vdev_ashift;
3067 ASSERT(MUTEX_HELD(&msp->ms_lock));
3070 * The metaslab is completely free.
3072 if (metaslab_allocated_space(msp) == 0) {
3073 int idx = highbit64(msp->ms_size) - 1;
3074 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
3076 if (idx < max_idx) {
3077 WEIGHT_SET_COUNT(weight, 1ULL);
3078 WEIGHT_SET_INDEX(weight, idx);
3080 WEIGHT_SET_COUNT(weight, 1ULL << (idx - max_idx));
3081 WEIGHT_SET_INDEX(weight, max_idx);
3083 WEIGHT_SET_ACTIVE(weight, 0);
3084 ASSERT(!WEIGHT_IS_SPACEBASED(weight));
3088 ASSERT3U(msp->ms_sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
3091 * If the metaslab is fully allocated then just make the weight 0.
3093 if (metaslab_allocated_space(msp) == msp->ms_size)
3096 * If the metaslab is already loaded, then use the range tree to
3097 * determine the weight. Otherwise, we rely on the space map information
3098 * to generate the weight.
3100 if (msp->ms_loaded) {
3101 weight = metaslab_weight_from_range_tree(msp);
3103 weight = metaslab_weight_from_spacemap(msp);
3107 * If the metaslab was active the last time we calculated its weight
3108 * then keep it active. We want to consume the entire region that
3109 * is associated with this weight.
3111 if (msp->ms_activation_weight != 0 && weight != 0)
3112 WEIGHT_SET_ACTIVE(weight, WEIGHT_GET_ACTIVE(msp->ms_weight));
3117 * Determine if we should attempt to allocate from this metaslab. If the
3118 * metaslab is loaded, then we can determine if the desired allocation
3119 * can be satisfied by looking at the size of the maximum free segment
3120 * on that metaslab. Otherwise, we make our decision based on the metaslab's
3121 * weight. For segment-based weighting we can determine the maximum
3122 * allocation based on the index encoded in its value. For space-based
3123 * weights we rely on the entire weight (excluding the weight-type bit).
3126 metaslab_should_allocate(metaslab_t *msp, uint64_t asize, boolean_t try_hard)
3129 * If the metaslab is loaded, ms_max_size is definitive and we can use
3130 * the fast check. If it's not, the ms_max_size is a lower bound (once
3131 * set), and we should use the fast check as long as we're not in
3132 * try_hard and it's been less than zfs_metaslab_max_size_cache_sec
3133 * seconds since the metaslab was unloaded.
3135 if (msp->ms_loaded ||
3136 (msp->ms_max_size != 0 && !try_hard && gethrtime() <
3137 msp->ms_unload_time + SEC2NSEC(zfs_metaslab_max_size_cache_sec)))
3138 return (msp->ms_max_size >= asize);
3140 boolean_t should_allocate;
3141 if (!WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
3143 * The metaslab segment weight indicates segments in the
3144 * range [2^i, 2^(i+1)), where i is the index in the weight.
3145 * Since the asize might be in the middle of the range, we
3146 * should attempt the allocation if asize < 2^(i+1).
3148 should_allocate = (asize <
3149 1ULL << (WEIGHT_GET_INDEX(msp->ms_weight) + 1));
3151 should_allocate = (asize <=
3152 (msp->ms_weight & ~METASLAB_WEIGHT_TYPE));
3155 return (should_allocate);
3159 metaslab_weight(metaslab_t *msp, boolean_t nodirty)
3161 vdev_t *vd = msp->ms_group->mg_vd;
3162 spa_t *spa = vd->vdev_spa;
3165 ASSERT(MUTEX_HELD(&msp->ms_lock));
3167 metaslab_set_fragmentation(msp, nodirty);
3170 * Update the maximum size. If the metaslab is loaded, this will
3171 * ensure that we get an accurate maximum size if newly freed space
3172 * has been added back into the free tree. If the metaslab is
3173 * unloaded, we check if there's a larger free segment in the
3174 * unflushed frees. This is a lower bound on the largest allocatable
3175 * segment size. Coalescing of adjacent entries may reveal larger
3176 * allocatable segments, but we aren't aware of those until loading
3177 * the space map into a range tree.
3179 if (msp->ms_loaded) {
3180 msp->ms_max_size = metaslab_largest_allocatable(msp);
3182 msp->ms_max_size = MAX(msp->ms_max_size,
3183 metaslab_largest_unflushed_free(msp));
3187 * Segment-based weighting requires space map histogram support.
3189 if (zfs_metaslab_segment_weight_enabled &&
3190 spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM) &&
3191 (msp->ms_sm == NULL || msp->ms_sm->sm_dbuf->db_size ==
3192 sizeof (space_map_phys_t))) {
3193 weight = metaslab_segment_weight(msp);
3195 weight = metaslab_space_weight(msp);
3201 metaslab_recalculate_weight_and_sort(metaslab_t *msp)
3203 ASSERT(MUTEX_HELD(&msp->ms_lock));
3205 /* note: we preserve the mask (e.g. indication of primary, etc..) */
3206 uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
3207 metaslab_group_sort(msp->ms_group, msp,
3208 metaslab_weight(msp, B_FALSE) | was_active);
3212 metaslab_activate_allocator(metaslab_group_t *mg, metaslab_t *msp,
3213 int allocator, uint64_t activation_weight)
3215 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
3216 ASSERT(MUTEX_HELD(&msp->ms_lock));
3219 * If we're activating for the claim code, we don't want to actually
3220 * set the metaslab up for a specific allocator.
3222 if (activation_weight == METASLAB_WEIGHT_CLAIM) {
3223 ASSERT0(msp->ms_activation_weight);
3224 msp->ms_activation_weight = msp->ms_weight;
3225 metaslab_group_sort(mg, msp, msp->ms_weight |
3230 metaslab_t **mspp = (activation_weight == METASLAB_WEIGHT_PRIMARY ?
3231 &mga->mga_primary : &mga->mga_secondary);
3233 mutex_enter(&mg->mg_lock);
3234 if (*mspp != NULL) {
3235 mutex_exit(&mg->mg_lock);
3240 ASSERT3S(msp->ms_allocator, ==, -1);
3241 msp->ms_allocator = allocator;
3242 msp->ms_primary = (activation_weight == METASLAB_WEIGHT_PRIMARY);
3244 ASSERT0(msp->ms_activation_weight);
3245 msp->ms_activation_weight = msp->ms_weight;
3246 metaslab_group_sort_impl(mg, msp,
3247 msp->ms_weight | activation_weight);
3248 mutex_exit(&mg->mg_lock);
3254 metaslab_activate(metaslab_t *msp, int allocator, uint64_t activation_weight)
3256 ASSERT(MUTEX_HELD(&msp->ms_lock));
3259 * The current metaslab is already activated for us so there
3260 * is nothing to do. Already activated though, doesn't mean
3261 * that this metaslab is activated for our allocator nor our
3262 * requested activation weight. The metaslab could have started
3263 * as an active one for our allocator but changed allocators
3264 * while we were waiting to grab its ms_lock or we stole it
3265 * [see find_valid_metaslab()]. This means that there is a
3266 * possibility of passivating a metaslab of another allocator
3267 * or from a different activation mask, from this thread.
3269 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
3270 ASSERT(msp->ms_loaded);
3274 int error = metaslab_load(msp);
3276 metaslab_group_sort(msp->ms_group, msp, 0);
3281 * When entering metaslab_load() we may have dropped the
3282 * ms_lock because we were loading this metaslab, or we
3283 * were waiting for another thread to load it for us. In
3284 * that scenario, we recheck the weight of the metaslab
3285 * to see if it was activated by another thread.
3287 * If the metaslab was activated for another allocator or
3288 * it was activated with a different activation weight (e.g.
3289 * we wanted to make it a primary but it was activated as
3290 * secondary) we return error (EBUSY).
3292 * If the metaslab was activated for the same allocator
3293 * and requested activation mask, skip activating it.
3295 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
3296 if (msp->ms_allocator != allocator)
3299 if ((msp->ms_weight & activation_weight) == 0)
3300 return (SET_ERROR(EBUSY));
3302 EQUIV((activation_weight == METASLAB_WEIGHT_PRIMARY),
3308 * If the metaslab has literally 0 space, it will have weight 0. In
3309 * that case, don't bother activating it. This can happen if the
3310 * metaslab had space during find_valid_metaslab, but another thread
3311 * loaded it and used all that space while we were waiting to grab the
3314 if (msp->ms_weight == 0) {
3315 ASSERT0(range_tree_space(msp->ms_allocatable));
3316 return (SET_ERROR(ENOSPC));
3319 if ((error = metaslab_activate_allocator(msp->ms_group, msp,
3320 allocator, activation_weight)) != 0) {
3324 ASSERT(msp->ms_loaded);
3325 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
3331 metaslab_passivate_allocator(metaslab_group_t *mg, metaslab_t *msp,
3334 ASSERT(MUTEX_HELD(&msp->ms_lock));
3335 ASSERT(msp->ms_loaded);
3337 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
3338 metaslab_group_sort(mg, msp, weight);
3342 mutex_enter(&mg->mg_lock);
3343 ASSERT3P(msp->ms_group, ==, mg);
3344 ASSERT3S(0, <=, msp->ms_allocator);
3345 ASSERT3U(msp->ms_allocator, <, mg->mg_allocators);
3347 metaslab_group_allocator_t *mga = &mg->mg_allocator[msp->ms_allocator];
3348 if (msp->ms_primary) {
3349 ASSERT3P(mga->mga_primary, ==, msp);
3350 ASSERT(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
3351 mga->mga_primary = NULL;
3353 ASSERT3P(mga->mga_secondary, ==, msp);
3354 ASSERT(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
3355 mga->mga_secondary = NULL;
3357 msp->ms_allocator = -1;
3358 metaslab_group_sort_impl(mg, msp, weight);
3359 mutex_exit(&mg->mg_lock);
3363 metaslab_passivate(metaslab_t *msp, uint64_t weight)
3365 uint64_t size __maybe_unused = weight & ~METASLAB_WEIGHT_TYPE;
3368 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
3369 * this metaslab again. In that case, it had better be empty,
3370 * or we would be leaving space on the table.
3372 ASSERT(!WEIGHT_IS_SPACEBASED(msp->ms_weight) ||
3373 size >= SPA_MINBLOCKSIZE ||
3374 range_tree_space(msp->ms_allocatable) == 0);
3375 ASSERT0(weight & METASLAB_ACTIVE_MASK);
3377 ASSERT(msp->ms_activation_weight != 0);
3378 msp->ms_activation_weight = 0;
3379 metaslab_passivate_allocator(msp->ms_group, msp, weight);
3380 ASSERT0(msp->ms_weight & METASLAB_ACTIVE_MASK);
3384 * Segment-based metaslabs are activated once and remain active until
3385 * we either fail an allocation attempt (similar to space-based metaslabs)
3386 * or have exhausted the free space in zfs_metaslab_switch_threshold
3387 * buckets since the metaslab was activated. This function checks to see
3388 * if we've exhausted the zfs_metaslab_switch_threshold buckets in the
3389 * metaslab and passivates it proactively. This will allow us to select a
3390 * metaslab with a larger contiguous region, if any, remaining within this
3391 * metaslab group. If we're in sync pass > 1, then we continue using this
3392 * metaslab so that we don't dirty more block and cause more sync passes.
3395 metaslab_segment_may_passivate(metaslab_t *msp)
3397 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3399 if (WEIGHT_IS_SPACEBASED(msp->ms_weight) || spa_sync_pass(spa) > 1)
3403 * Since we are in the middle of a sync pass, the most accurate
3404 * information that is accessible to us is the in-core range tree
3405 * histogram; calculate the new weight based on that information.
3407 uint64_t weight = metaslab_weight_from_range_tree(msp);
3408 int activation_idx = WEIGHT_GET_INDEX(msp->ms_activation_weight);
3409 int current_idx = WEIGHT_GET_INDEX(weight);
3411 if (current_idx <= activation_idx - zfs_metaslab_switch_threshold)
3412 metaslab_passivate(msp, weight);
3416 metaslab_preload(void *arg)
3418 metaslab_t *msp = arg;
3419 metaslab_class_t *mc = msp->ms_group->mg_class;
3420 spa_t *spa = mc->mc_spa;
3421 fstrans_cookie_t cookie = spl_fstrans_mark();
3423 ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
3425 mutex_enter(&msp->ms_lock);
3426 (void) metaslab_load(msp);
3427 metaslab_set_selected_txg(msp, spa_syncing_txg(spa));
3428 mutex_exit(&msp->ms_lock);
3429 spl_fstrans_unmark(cookie);
3433 metaslab_group_preload(metaslab_group_t *mg)
3435 spa_t *spa = mg->mg_vd->vdev_spa;
3437 avl_tree_t *t = &mg->mg_metaslab_tree;
3440 if (spa_shutting_down(spa) || !metaslab_preload_enabled) {
3441 taskq_wait_outstanding(mg->mg_taskq, 0);
3445 mutex_enter(&mg->mg_lock);
3448 * Load the next potential metaslabs
3450 for (msp = avl_first(t); msp != NULL; msp = AVL_NEXT(t, msp)) {
3451 ASSERT3P(msp->ms_group, ==, mg);
3454 * We preload only the maximum number of metaslabs specified
3455 * by metaslab_preload_limit. If a metaslab is being forced
3456 * to condense then we preload it too. This will ensure
3457 * that force condensing happens in the next txg.
3459 if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
3463 VERIFY(taskq_dispatch(mg->mg_taskq, metaslab_preload,
3464 msp, TQ_SLEEP) != TASKQID_INVALID);
3466 mutex_exit(&mg->mg_lock);
3470 * Determine if the space map's on-disk footprint is past our tolerance for
3471 * inefficiency. We would like to use the following criteria to make our
3474 * 1. Do not condense if the size of the space map object would dramatically
3475 * increase as a result of writing out the free space range tree.
3477 * 2. Condense if the on on-disk space map representation is at least
3478 * zfs_condense_pct/100 times the size of the optimal representation
3479 * (i.e. zfs_condense_pct = 110 and in-core = 1MB, optimal = 1.1MB).
3481 * 3. Do not condense if the on-disk size of the space map does not actually
3484 * Unfortunately, we cannot compute the on-disk size of the space map in this
3485 * context because we cannot accurately compute the effects of compression, etc.
3486 * Instead, we apply the heuristic described in the block comment for
3487 * zfs_metaslab_condense_block_threshold - we only condense if the space used
3488 * is greater than a threshold number of blocks.
3491 metaslab_should_condense(metaslab_t *msp)
3493 space_map_t *sm = msp->ms_sm;
3494 vdev_t *vd = msp->ms_group->mg_vd;
3495 uint64_t vdev_blocksize = 1 << vd->vdev_ashift;
3497 ASSERT(MUTEX_HELD(&msp->ms_lock));
3498 ASSERT(msp->ms_loaded);
3500 ASSERT3U(spa_sync_pass(vd->vdev_spa), ==, 1);
3503 * We always condense metaslabs that are empty and metaslabs for
3504 * which a condense request has been made.
3506 if (range_tree_numsegs(msp->ms_allocatable) == 0 ||
3507 msp->ms_condense_wanted)
3510 uint64_t record_size = MAX(sm->sm_blksz, vdev_blocksize);
3511 uint64_t object_size = space_map_length(sm);
3512 uint64_t optimal_size = space_map_estimate_optimal_size(sm,
3513 msp->ms_allocatable, SM_NO_VDEVID);
3515 return (object_size >= (optimal_size * zfs_condense_pct / 100) &&
3516 object_size > zfs_metaslab_condense_block_threshold * record_size);
3520 * Condense the on-disk space map representation to its minimized form.
3521 * The minimized form consists of a small number of allocations followed
3522 * by the entries of the free range tree (ms_allocatable). The condensed
3523 * spacemap contains all the entries of previous TXGs (including those in
3524 * the pool-wide log spacemaps; thus this is effectively a superset of
3525 * metaslab_flush()), but this TXG's entries still need to be written.
3528 metaslab_condense(metaslab_t *msp, dmu_tx_t *tx)
3530 range_tree_t *condense_tree;
3531 space_map_t *sm = msp->ms_sm;
3532 uint64_t txg = dmu_tx_get_txg(tx);
3533 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3535 ASSERT(MUTEX_HELD(&msp->ms_lock));
3536 ASSERT(msp->ms_loaded);
3537 ASSERT(msp->ms_sm != NULL);
3540 * In order to condense the space map, we need to change it so it
3541 * only describes which segments are currently allocated and free.
3543 * All the current free space resides in the ms_allocatable, all
3544 * the ms_defer trees, and all the ms_allocating trees. We ignore
3545 * ms_freed because it is empty because we're in sync pass 1. We
3546 * ignore ms_freeing because these changes are not yet reflected
3547 * in the spacemap (they will be written later this txg).
3549 * So to truncate the space map to represent all the entries of
3550 * previous TXGs we do the following:
3552 * 1] We create a range tree (condense tree) that is 100% empty.
3553 * 2] We add to it all segments found in the ms_defer trees
3554 * as those segments are marked as free in the original space
3555 * map. We do the same with the ms_allocating trees for the same
3556 * reason. Adding these segments should be a relatively
3557 * inexpensive operation since we expect these trees to have a
3558 * small number of nodes.
3559 * 3] We vacate any unflushed allocs, since they are not frees we
3560 * need to add to the condense tree. Then we vacate any
3561 * unflushed frees as they should already be part of ms_allocatable.
3562 * 4] At this point, we would ideally like to add all segments
3563 * in the ms_allocatable tree from the condense tree. This way
3564 * we would write all the entries of the condense tree as the
3565 * condensed space map, which would only contain freed
3566 * segments with everything else assumed to be allocated.
3568 * Doing so can be prohibitively expensive as ms_allocatable can
3569 * be large, and therefore computationally expensive to add to
3570 * the condense_tree. Instead we first sync out an entry marking
3571 * everything as allocated, then the condense_tree and then the
3572 * ms_allocatable, in the condensed space map. While this is not
3573 * optimal, it is typically close to optimal and more importantly
3574 * much cheaper to compute.
3576 * 5] Finally, as both of the unflushed trees were written to our
3577 * new and condensed metaslab space map, we basically flushed
3578 * all the unflushed changes to disk, thus we call
3579 * metaslab_flush_update().
3581 ASSERT3U(spa_sync_pass(spa), ==, 1);
3582 ASSERT(range_tree_is_empty(msp->ms_freed)); /* since it is pass 1 */
3584 zfs_dbgmsg("condensing: txg %llu, msp[%llu] %px, vdev id %llu, "
3585 "spa %s, smp size %llu, segments %lu, forcing condense=%s", txg,
3586 msp->ms_id, msp, msp->ms_group->mg_vd->vdev_id,
3587 spa->spa_name, space_map_length(msp->ms_sm),
3588 range_tree_numsegs(msp->ms_allocatable),
3589 msp->ms_condense_wanted ? "TRUE" : "FALSE");
3591 msp->ms_condense_wanted = B_FALSE;
3593 range_seg_type_t type;
3594 uint64_t shift, start;
3595 type = metaslab_calculate_range_tree_type(msp->ms_group->mg_vd, msp,
3598 condense_tree = range_tree_create(NULL, type, NULL, start, shift);
3600 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3601 range_tree_walk(msp->ms_defer[t],
3602 range_tree_add, condense_tree);
3605 for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
3606 range_tree_walk(msp->ms_allocating[(txg + t) & TXG_MASK],
3607 range_tree_add, condense_tree);
3610 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
3611 metaslab_unflushed_changes_memused(msp));
3612 spa->spa_unflushed_stats.sus_memused -=
3613 metaslab_unflushed_changes_memused(msp);
3614 range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
3615 range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
3618 * We're about to drop the metaslab's lock thus allowing other
3619 * consumers to change it's content. Set the metaslab's ms_condensing
3620 * flag to ensure that allocations on this metaslab do not occur
3621 * while we're in the middle of committing it to disk. This is only
3622 * critical for ms_allocatable as all other range trees use per TXG
3623 * views of their content.
3625 msp->ms_condensing = B_TRUE;
3627 mutex_exit(&msp->ms_lock);
3628 uint64_t object = space_map_object(msp->ms_sm);
3629 space_map_truncate(sm,
3630 spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP) ?
3631 zfs_metaslab_sm_blksz_with_log : zfs_metaslab_sm_blksz_no_log, tx);
3634 * space_map_truncate() may have reallocated the spacemap object.
3635 * If so, update the vdev_ms_array.
3637 if (space_map_object(msp->ms_sm) != object) {
3638 object = space_map_object(msp->ms_sm);
3639 dmu_write(spa->spa_meta_objset,
3640 msp->ms_group->mg_vd->vdev_ms_array, sizeof (uint64_t) *
3641 msp->ms_id, sizeof (uint64_t), &object, tx);
3646 * When the log space map feature is enabled, each space map will
3647 * always have ALLOCS followed by FREES for each sync pass. This is
3648 * typically true even when the log space map feature is disabled,
3649 * except from the case where a metaslab goes through metaslab_sync()
3650 * and gets condensed. In that case the metaslab's space map will have
3651 * ALLOCS followed by FREES (due to condensing) followed by ALLOCS
3652 * followed by FREES (due to space_map_write() in metaslab_sync()) for
3655 range_tree_t *tmp_tree = range_tree_create(NULL, type, NULL, start,
3657 range_tree_add(tmp_tree, msp->ms_start, msp->ms_size);
3658 space_map_write(sm, tmp_tree, SM_ALLOC, SM_NO_VDEVID, tx);
3659 space_map_write(sm, msp->ms_allocatable, SM_FREE, SM_NO_VDEVID, tx);
3660 space_map_write(sm, condense_tree, SM_FREE, SM_NO_VDEVID, tx);
3662 range_tree_vacate(condense_tree, NULL, NULL);
3663 range_tree_destroy(condense_tree);
3664 range_tree_vacate(tmp_tree, NULL, NULL);
3665 range_tree_destroy(tmp_tree);
3666 mutex_enter(&msp->ms_lock);
3668 msp->ms_condensing = B_FALSE;
3669 metaslab_flush_update(msp, tx);
3673 * Called when the metaslab has been flushed (its own spacemap now reflects
3674 * all the contents of the pool-wide spacemap log). Updates the metaslab's
3675 * metadata and any pool-wide related log space map data (e.g. summary,
3676 * obsolete logs, etc..) to reflect that.
3679 metaslab_flush_update(metaslab_t *msp, dmu_tx_t *tx)
3681 metaslab_group_t *mg = msp->ms_group;
3682 spa_t *spa = mg->mg_vd->vdev_spa;
3684 ASSERT(MUTEX_HELD(&msp->ms_lock));
3686 ASSERT3U(spa_sync_pass(spa), ==, 1);
3687 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
3688 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
3691 * Just because a metaslab got flushed, that doesn't mean that
3692 * it will pass through metaslab_sync_done(). Thus, make sure to
3693 * update ms_synced_length here in case it doesn't.
3695 msp->ms_synced_length = space_map_length(msp->ms_sm);
3698 * We may end up here from metaslab_condense() without the
3699 * feature being active. In that case this is a no-op.
3701 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
3704 ASSERT(spa_syncing_log_sm(spa) != NULL);
3705 ASSERT(msp->ms_sm != NULL);
3706 ASSERT(metaslab_unflushed_txg(msp) != 0);
3707 ASSERT3P(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL), ==, msp);
3709 VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(spa));
3711 /* update metaslab's position in our flushing tree */
3712 uint64_t ms_prev_flushed_txg = metaslab_unflushed_txg(msp);
3713 mutex_enter(&spa->spa_flushed_ms_lock);
3714 avl_remove(&spa->spa_metaslabs_by_flushed, msp);
3715 metaslab_set_unflushed_txg(msp, spa_syncing_txg(spa), tx);
3716 avl_add(&spa->spa_metaslabs_by_flushed, msp);
3717 mutex_exit(&spa->spa_flushed_ms_lock);
3719 /* update metaslab counts of spa_log_sm_t nodes */
3720 spa_log_sm_decrement_mscount(spa, ms_prev_flushed_txg);
3721 spa_log_sm_increment_current_mscount(spa);
3723 /* cleanup obsolete logs if any */
3724 uint64_t log_blocks_before = spa_log_sm_nblocks(spa);
3725 spa_cleanup_old_sm_logs(spa, tx);
3726 uint64_t log_blocks_after = spa_log_sm_nblocks(spa);
3727 VERIFY3U(log_blocks_after, <=, log_blocks_before);
3729 /* update log space map summary */
3730 uint64_t blocks_gone = log_blocks_before - log_blocks_after;
3731 spa_log_summary_add_flushed_metaslab(spa);
3732 spa_log_summary_decrement_mscount(spa, ms_prev_flushed_txg);
3733 spa_log_summary_decrement_blkcount(spa, blocks_gone);
3737 metaslab_flush(metaslab_t *msp, dmu_tx_t *tx)
3739 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3741 ASSERT(MUTEX_HELD(&msp->ms_lock));
3742 ASSERT3U(spa_sync_pass(spa), ==, 1);
3743 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
3745 ASSERT(msp->ms_sm != NULL);
3746 ASSERT(metaslab_unflushed_txg(msp) != 0);
3747 ASSERT(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL) != NULL);
3750 * There is nothing wrong with flushing the same metaslab twice, as
3751 * this codepath should work on that case. However, the current
3752 * flushing scheme makes sure to avoid this situation as we would be
3753 * making all these calls without having anything meaningful to write
3754 * to disk. We assert this behavior here.
3756 ASSERT3U(metaslab_unflushed_txg(msp), <, dmu_tx_get_txg(tx));
3759 * We can not flush while loading, because then we would
3760 * not load the ms_unflushed_{allocs,frees}.
3762 if (msp->ms_loading)
3765 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3766 metaslab_verify_weight_and_frag(msp);
3769 * Metaslab condensing is effectively flushing. Therefore if the
3770 * metaslab can be condensed we can just condense it instead of
3773 * Note that metaslab_condense() does call metaslab_flush_update()
3774 * so we can just return immediately after condensing. We also
3775 * don't need to care about setting ms_flushing or broadcasting
3776 * ms_flush_cv, even if we temporarily drop the ms_lock in
3777 * metaslab_condense(), as the metaslab is already loaded.
3779 if (msp->ms_loaded && metaslab_should_condense(msp)) {
3780 metaslab_group_t *mg = msp->ms_group;
3783 * For all histogram operations below refer to the
3784 * comments of metaslab_sync() where we follow a
3785 * similar procedure.
3787 metaslab_group_histogram_verify(mg);
3788 metaslab_class_histogram_verify(mg->mg_class);
3789 metaslab_group_histogram_remove(mg, msp);
3791 metaslab_condense(msp, tx);
3793 space_map_histogram_clear(msp->ms_sm);
3794 space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
3795 ASSERT(range_tree_is_empty(msp->ms_freed));
3796 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3797 space_map_histogram_add(msp->ms_sm,
3798 msp->ms_defer[t], tx);
3800 metaslab_aux_histograms_update(msp);
3802 metaslab_group_histogram_add(mg, msp);
3803 metaslab_group_histogram_verify(mg);
3804 metaslab_class_histogram_verify(mg->mg_class);
3806 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3809 * Since we recreated the histogram (and potentially
3810 * the ms_sm too while condensing) ensure that the
3811 * weight is updated too because we are not guaranteed
3812 * that this metaslab is dirty and will go through
3813 * metaslab_sync_done().
3815 metaslab_recalculate_weight_and_sort(msp);
3819 msp->ms_flushing = B_TRUE;
3820 uint64_t sm_len_before = space_map_length(msp->ms_sm);
3822 mutex_exit(&msp->ms_lock);
3823 space_map_write(msp->ms_sm, msp->ms_unflushed_allocs, SM_ALLOC,
3825 space_map_write(msp->ms_sm, msp->ms_unflushed_frees, SM_FREE,
3827 mutex_enter(&msp->ms_lock);
3829 uint64_t sm_len_after = space_map_length(msp->ms_sm);
3830 if (zfs_flags & ZFS_DEBUG_LOG_SPACEMAP) {
3831 zfs_dbgmsg("flushing: txg %llu, spa %s, vdev_id %llu, "
3832 "ms_id %llu, unflushed_allocs %llu, unflushed_frees %llu, "
3833 "appended %llu bytes", dmu_tx_get_txg(tx), spa_name(spa),
3834 msp->ms_group->mg_vd->vdev_id, msp->ms_id,
3835 range_tree_space(msp->ms_unflushed_allocs),
3836 range_tree_space(msp->ms_unflushed_frees),
3837 (sm_len_after - sm_len_before));
3840 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
3841 metaslab_unflushed_changes_memused(msp));
3842 spa->spa_unflushed_stats.sus_memused -=
3843 metaslab_unflushed_changes_memused(msp);
3844 range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
3845 range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
3847 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3848 metaslab_verify_weight_and_frag(msp);
3850 metaslab_flush_update(msp, tx);
3852 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3853 metaslab_verify_weight_and_frag(msp);
3855 msp->ms_flushing = B_FALSE;
3856 cv_broadcast(&msp->ms_flush_cv);
3861 * Write a metaslab to disk in the context of the specified transaction group.
3864 metaslab_sync(metaslab_t *msp, uint64_t txg)
3866 metaslab_group_t *mg = msp->ms_group;
3867 vdev_t *vd = mg->mg_vd;
3868 spa_t *spa = vd->vdev_spa;
3869 objset_t *mos = spa_meta_objset(spa);
3870 range_tree_t *alloctree = msp->ms_allocating[txg & TXG_MASK];
3873 ASSERT(!vd->vdev_ishole);
3876 * This metaslab has just been added so there's no work to do now.
3878 if (msp->ms_freeing == NULL) {
3879 ASSERT3P(alloctree, ==, NULL);
3883 ASSERT3P(alloctree, !=, NULL);
3884 ASSERT3P(msp->ms_freeing, !=, NULL);
3885 ASSERT3P(msp->ms_freed, !=, NULL);
3886 ASSERT3P(msp->ms_checkpointing, !=, NULL);
3887 ASSERT3P(msp->ms_trim, !=, NULL);
3890 * Normally, we don't want to process a metaslab if there are no
3891 * allocations or frees to perform. However, if the metaslab is being
3892 * forced to condense, it's loaded and we're not beyond the final
3893 * dirty txg, we need to let it through. Not condensing beyond the
3894 * final dirty txg prevents an issue where metaslabs that need to be
3895 * condensed but were loaded for other reasons could cause a panic
3896 * here. By only checking the txg in that branch of the conditional,
3897 * we preserve the utility of the VERIFY statements in all other
3900 if (range_tree_is_empty(alloctree) &&
3901 range_tree_is_empty(msp->ms_freeing) &&
3902 range_tree_is_empty(msp->ms_checkpointing) &&
3903 !(msp->ms_loaded && msp->ms_condense_wanted &&
3904 txg <= spa_final_dirty_txg(spa)))
3908 VERIFY3U(txg, <=, spa_final_dirty_txg(spa));
3911 * The only state that can actually be changing concurrently
3912 * with metaslab_sync() is the metaslab's ms_allocatable. No
3913 * other thread can be modifying this txg's alloc, freeing,
3914 * freed, or space_map_phys_t. We drop ms_lock whenever we
3915 * could call into the DMU, because the DMU can call down to
3916 * us (e.g. via zio_free()) at any time.
3918 * The spa_vdev_remove_thread() can be reading metaslab state
3919 * concurrently, and it is locked out by the ms_sync_lock.
3920 * Note that the ms_lock is insufficient for this, because it
3921 * is dropped by space_map_write().
3923 tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
3926 * Generate a log space map if one doesn't exist already.
3928 spa_generate_syncing_log_sm(spa, tx);
3930 if (msp->ms_sm == NULL) {
3931 uint64_t new_object = space_map_alloc(mos,
3932 spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP) ?
3933 zfs_metaslab_sm_blksz_with_log :
3934 zfs_metaslab_sm_blksz_no_log, tx);
3935 VERIFY3U(new_object, !=, 0);
3937 dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
3938 msp->ms_id, sizeof (uint64_t), &new_object, tx);
3940 VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
3941 msp->ms_start, msp->ms_size, vd->vdev_ashift));
3942 ASSERT(msp->ms_sm != NULL);
3944 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
3945 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
3946 ASSERT0(metaslab_allocated_space(msp));
3949 if (metaslab_unflushed_txg(msp) == 0 &&
3950 spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
3951 ASSERT(spa_syncing_log_sm(spa) != NULL);
3953 metaslab_set_unflushed_txg(msp, spa_syncing_txg(spa), tx);
3954 spa_log_sm_increment_current_mscount(spa);
3955 spa_log_summary_add_flushed_metaslab(spa);
3957 ASSERT(msp->ms_sm != NULL);
3958 mutex_enter(&spa->spa_flushed_ms_lock);
3959 avl_add(&spa->spa_metaslabs_by_flushed, msp);
3960 mutex_exit(&spa->spa_flushed_ms_lock);
3962 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
3963 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
3966 if (!range_tree_is_empty(msp->ms_checkpointing) &&
3967 vd->vdev_checkpoint_sm == NULL) {
3968 ASSERT(spa_has_checkpoint(spa));
3970 uint64_t new_object = space_map_alloc(mos,
3971 zfs_vdev_standard_sm_blksz, tx);
3972 VERIFY3U(new_object, !=, 0);
3974 VERIFY0(space_map_open(&vd->vdev_checkpoint_sm,
3975 mos, new_object, 0, vd->vdev_asize, vd->vdev_ashift));
3976 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
3979 * We save the space map object as an entry in vdev_top_zap
3980 * so it can be retrieved when the pool is reopened after an
3981 * export or through zdb.
3983 VERIFY0(zap_add(vd->vdev_spa->spa_meta_objset,
3984 vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
3985 sizeof (new_object), 1, &new_object, tx));
3988 mutex_enter(&msp->ms_sync_lock);
3989 mutex_enter(&msp->ms_lock);
3992 * Note: metaslab_condense() clears the space map's histogram.
3993 * Therefore we must verify and remove this histogram before
3996 metaslab_group_histogram_verify(mg);
3997 metaslab_class_histogram_verify(mg->mg_class);
3998 metaslab_group_histogram_remove(mg, msp);
4000 if (spa->spa_sync_pass == 1 && msp->ms_loaded &&
4001 metaslab_should_condense(msp))
4002 metaslab_condense(msp, tx);
4005 * We'll be going to disk to sync our space accounting, thus we
4006 * drop the ms_lock during that time so allocations coming from
4007 * open-context (ZIL) for future TXGs do not block.
4009 mutex_exit(&msp->ms_lock);
4010 space_map_t *log_sm = spa_syncing_log_sm(spa);
4011 if (log_sm != NULL) {
4012 ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP));
4014 space_map_write(log_sm, alloctree, SM_ALLOC,
4016 space_map_write(log_sm, msp->ms_freeing, SM_FREE,
4018 mutex_enter(&msp->ms_lock);
4020 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
4021 metaslab_unflushed_changes_memused(msp));
4022 spa->spa_unflushed_stats.sus_memused -=
4023 metaslab_unflushed_changes_memused(msp);
4024 range_tree_remove_xor_add(alloctree,
4025 msp->ms_unflushed_frees, msp->ms_unflushed_allocs);
4026 range_tree_remove_xor_add(msp->ms_freeing,
4027 msp->ms_unflushed_allocs, msp->ms_unflushed_frees);
4028 spa->spa_unflushed_stats.sus_memused +=
4029 metaslab_unflushed_changes_memused(msp);
4031 ASSERT(!spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP));
4033 space_map_write(msp->ms_sm, alloctree, SM_ALLOC,
4035 space_map_write(msp->ms_sm, msp->ms_freeing, SM_FREE,
4037 mutex_enter(&msp->ms_lock);
4040 msp->ms_allocated_space += range_tree_space(alloctree);
4041 ASSERT3U(msp->ms_allocated_space, >=,
4042 range_tree_space(msp->ms_freeing));
4043 msp->ms_allocated_space -= range_tree_space(msp->ms_freeing);
4045 if (!range_tree_is_empty(msp->ms_checkpointing)) {
4046 ASSERT(spa_has_checkpoint(spa));
4047 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
4050 * Since we are doing writes to disk and the ms_checkpointing
4051 * tree won't be changing during that time, we drop the
4052 * ms_lock while writing to the checkpoint space map, for the
4053 * same reason mentioned above.
4055 mutex_exit(&msp->ms_lock);
4056 space_map_write(vd->vdev_checkpoint_sm,
4057 msp->ms_checkpointing, SM_FREE, SM_NO_VDEVID, tx);
4058 mutex_enter(&msp->ms_lock);
4060 spa->spa_checkpoint_info.sci_dspace +=
4061 range_tree_space(msp->ms_checkpointing);
4062 vd->vdev_stat.vs_checkpoint_space +=
4063 range_tree_space(msp->ms_checkpointing);
4064 ASSERT3U(vd->vdev_stat.vs_checkpoint_space, ==,
4065 -space_map_allocated(vd->vdev_checkpoint_sm));
4067 range_tree_vacate(msp->ms_checkpointing, NULL, NULL);
4070 if (msp->ms_loaded) {
4072 * When the space map is loaded, we have an accurate
4073 * histogram in the range tree. This gives us an opportunity
4074 * to bring the space map's histogram up-to-date so we clear
4075 * it first before updating it.
4077 space_map_histogram_clear(msp->ms_sm);
4078 space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
4081 * Since we've cleared the histogram we need to add back
4082 * any free space that has already been processed, plus
4083 * any deferred space. This allows the on-disk histogram
4084 * to accurately reflect all free space even if some space
4085 * is not yet available for allocation (i.e. deferred).
4087 space_map_histogram_add(msp->ms_sm, msp->ms_freed, tx);
4090 * Add back any deferred free space that has not been
4091 * added back into the in-core free tree yet. This will
4092 * ensure that we don't end up with a space map histogram
4093 * that is completely empty unless the metaslab is fully
4096 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
4097 space_map_histogram_add(msp->ms_sm,
4098 msp->ms_defer[t], tx);
4103 * Always add the free space from this sync pass to the space
4104 * map histogram. We want to make sure that the on-disk histogram
4105 * accounts for all free space. If the space map is not loaded,
4106 * then we will lose some accuracy but will correct it the next
4107 * time we load the space map.
4109 space_map_histogram_add(msp->ms_sm, msp->ms_freeing, tx);
4110 metaslab_aux_histograms_update(msp);
4112 metaslab_group_histogram_add(mg, msp);
4113 metaslab_group_histogram_verify(mg);
4114 metaslab_class_histogram_verify(mg->mg_class);
4117 * For sync pass 1, we avoid traversing this txg's free range tree
4118 * and instead will just swap the pointers for freeing and freed.
4119 * We can safely do this since the freed_tree is guaranteed to be
4120 * empty on the initial pass.
4122 * Keep in mind that even if we are currently using a log spacemap
4123 * we want current frees to end up in the ms_allocatable (but not
4124 * get appended to the ms_sm) so their ranges can be reused as usual.
4126 if (spa_sync_pass(spa) == 1) {
4127 range_tree_swap(&msp->ms_freeing, &msp->ms_freed);
4128 ASSERT0(msp->ms_allocated_this_txg);
4130 range_tree_vacate(msp->ms_freeing,
4131 range_tree_add, msp->ms_freed);
4133 msp->ms_allocated_this_txg += range_tree_space(alloctree);
4134 range_tree_vacate(alloctree, NULL, NULL);
4136 ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
4137 ASSERT0(range_tree_space(msp->ms_allocating[TXG_CLEAN(txg)
4139 ASSERT0(range_tree_space(msp->ms_freeing));
4140 ASSERT0(range_tree_space(msp->ms_checkpointing));
4142 mutex_exit(&msp->ms_lock);
4145 * Verify that the space map object ID has been recorded in the
4149 VERIFY0(dmu_read(mos, vd->vdev_ms_array,
4150 msp->ms_id * sizeof (uint64_t), sizeof (uint64_t), &object, 0));
4151 VERIFY3U(object, ==, space_map_object(msp->ms_sm));
4153 mutex_exit(&msp->ms_sync_lock);
4158 metaslab_evict(metaslab_t *msp, uint64_t txg)
4160 if (!msp->ms_loaded || msp->ms_disabled != 0)
4163 for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
4164 VERIFY0(range_tree_space(
4165 msp->ms_allocating[(txg + t) & TXG_MASK]));
4167 if (msp->ms_allocator != -1)
4168 metaslab_passivate(msp, msp->ms_weight & ~METASLAB_ACTIVE_MASK);
4170 if (!metaslab_debug_unload)
4171 metaslab_unload(msp);
4175 * Called after a transaction group has completely synced to mark
4176 * all of the metaslab's free space as usable.
4179 metaslab_sync_done(metaslab_t *msp, uint64_t txg)
4181 metaslab_group_t *mg = msp->ms_group;
4182 vdev_t *vd = mg->mg_vd;
4183 spa_t *spa = vd->vdev_spa;
4184 range_tree_t **defer_tree;
4185 int64_t alloc_delta, defer_delta;
4186 boolean_t defer_allowed = B_TRUE;
4188 ASSERT(!vd->vdev_ishole);
4190 mutex_enter(&msp->ms_lock);
4193 * If this metaslab is just becoming available, initialize its
4194 * range trees and add its capacity to the vdev.
4196 if (msp->ms_freed == NULL) {
4197 range_seg_type_t type;
4198 uint64_t shift, start;
4199 type = metaslab_calculate_range_tree_type(vd, msp, &start,
4202 for (int t = 0; t < TXG_SIZE; t++) {
4203 ASSERT(msp->ms_allocating[t] == NULL);
4205 msp->ms_allocating[t] = range_tree_create(NULL, type,
4206 NULL, start, shift);
4209 ASSERT3P(msp->ms_freeing, ==, NULL);
4210 msp->ms_freeing = range_tree_create(NULL, type, NULL, start,
4213 ASSERT3P(msp->ms_freed, ==, NULL);
4214 msp->ms_freed = range_tree_create(NULL, type, NULL, start,
4217 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
4218 ASSERT3P(msp->ms_defer[t], ==, NULL);
4219 msp->ms_defer[t] = range_tree_create(NULL, type, NULL,
4223 ASSERT3P(msp->ms_checkpointing, ==, NULL);
4224 msp->ms_checkpointing = range_tree_create(NULL, type, NULL,
4227 ASSERT3P(msp->ms_unflushed_allocs, ==, NULL);
4228 msp->ms_unflushed_allocs = range_tree_create(NULL, type, NULL,
4231 metaslab_rt_arg_t *mrap = kmem_zalloc(sizeof (*mrap), KM_SLEEP);
4232 mrap->mra_bt = &msp->ms_unflushed_frees_by_size;
4233 mrap->mra_floor_shift = metaslab_by_size_min_shift;
4234 ASSERT3P(msp->ms_unflushed_frees, ==, NULL);
4235 msp->ms_unflushed_frees = range_tree_create(&metaslab_rt_ops,
4236 type, mrap, start, shift);
4238 metaslab_space_update(vd, mg->mg_class, 0, 0, msp->ms_size);
4240 ASSERT0(range_tree_space(msp->ms_freeing));
4241 ASSERT0(range_tree_space(msp->ms_checkpointing));
4243 defer_tree = &msp->ms_defer[txg % TXG_DEFER_SIZE];
4245 uint64_t free_space = metaslab_class_get_space(spa_normal_class(spa)) -
4246 metaslab_class_get_alloc(spa_normal_class(spa));
4247 if (free_space <= spa_get_slop_space(spa) || vd->vdev_removing) {
4248 defer_allowed = B_FALSE;
4252 alloc_delta = msp->ms_allocated_this_txg -
4253 range_tree_space(msp->ms_freed);
4255 if (defer_allowed) {
4256 defer_delta = range_tree_space(msp->ms_freed) -
4257 range_tree_space(*defer_tree);
4259 defer_delta -= range_tree_space(*defer_tree);
4261 metaslab_space_update(vd, mg->mg_class, alloc_delta + defer_delta,
4264 if (spa_syncing_log_sm(spa) == NULL) {
4266 * If there's a metaslab_load() in progress and we don't have
4267 * a log space map, it means that we probably wrote to the
4268 * metaslab's space map. If this is the case, we need to
4269 * make sure that we wait for the load to complete so that we
4270 * have a consistent view at the in-core side of the metaslab.
4272 metaslab_load_wait(msp);
4274 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
4278 * When auto-trimming is enabled, free ranges which are added to
4279 * ms_allocatable are also be added to ms_trim. The ms_trim tree is
4280 * periodically consumed by the vdev_autotrim_thread() which issues
4281 * trims for all ranges and then vacates the tree. The ms_trim tree
4282 * can be discarded at any time with the sole consequence of recent
4283 * frees not being trimmed.
4285 if (spa_get_autotrim(spa) == SPA_AUTOTRIM_ON) {
4286 range_tree_walk(*defer_tree, range_tree_add, msp->ms_trim);
4287 if (!defer_allowed) {
4288 range_tree_walk(msp->ms_freed, range_tree_add,
4292 range_tree_vacate(msp->ms_trim, NULL, NULL);
4296 * Move the frees from the defer_tree back to the free
4297 * range tree (if it's loaded). Swap the freed_tree and
4298 * the defer_tree -- this is safe to do because we've
4299 * just emptied out the defer_tree.
4301 range_tree_vacate(*defer_tree,
4302 msp->ms_loaded ? range_tree_add : NULL, msp->ms_allocatable);
4303 if (defer_allowed) {
4304 range_tree_swap(&msp->ms_freed, defer_tree);
4306 range_tree_vacate(msp->ms_freed,
4307 msp->ms_loaded ? range_tree_add : NULL,
4308 msp->ms_allocatable);
4311 msp->ms_synced_length = space_map_length(msp->ms_sm);
4313 msp->ms_deferspace += defer_delta;
4314 ASSERT3S(msp->ms_deferspace, >=, 0);
4315 ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
4316 if (msp->ms_deferspace != 0) {
4318 * Keep syncing this metaslab until all deferred frees
4319 * are back in circulation.
4321 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
4323 metaslab_aux_histograms_update_done(msp, defer_allowed);
4326 msp->ms_new = B_FALSE;
4327 mutex_enter(&mg->mg_lock);
4329 mutex_exit(&mg->mg_lock);
4333 * Re-sort metaslab within its group now that we've adjusted
4334 * its allocatable space.
4336 metaslab_recalculate_weight_and_sort(msp);
4338 ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
4339 ASSERT0(range_tree_space(msp->ms_freeing));
4340 ASSERT0(range_tree_space(msp->ms_freed));
4341 ASSERT0(range_tree_space(msp->ms_checkpointing));
4342 msp->ms_allocating_total -= msp->ms_allocated_this_txg;
4343 msp->ms_allocated_this_txg = 0;
4344 mutex_exit(&msp->ms_lock);
4348 metaslab_sync_reassess(metaslab_group_t *mg)
4350 spa_t *spa = mg->mg_class->mc_spa;
4352 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
4353 metaslab_group_alloc_update(mg);
4354 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
4357 * Preload the next potential metaslabs but only on active
4358 * metaslab groups. We can get into a state where the metaslab
4359 * is no longer active since we dirty metaslabs as we remove a
4360 * a device, thus potentially making the metaslab group eligible
4363 if (mg->mg_activation_count > 0) {
4364 metaslab_group_preload(mg);
4366 spa_config_exit(spa, SCL_ALLOC, FTAG);
4370 * When writing a ditto block (i.e. more than one DVA for a given BP) on
4371 * the same vdev as an existing DVA of this BP, then try to allocate it
4372 * on a different metaslab than existing DVAs (i.e. a unique metaslab).
4375 metaslab_is_unique(metaslab_t *msp, dva_t *dva)
4379 if (DVA_GET_ASIZE(dva) == 0)
4382 if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
4385 dva_ms_id = DVA_GET_OFFSET(dva) >> msp->ms_group->mg_vd->vdev_ms_shift;
4387 return (msp->ms_id != dva_ms_id);
4391 * ==========================================================================
4392 * Metaslab allocation tracing facility
4393 * ==========================================================================
4395 #ifdef _METASLAB_TRACING
4398 * Add an allocation trace element to the allocation tracing list.
4401 metaslab_trace_add(zio_alloc_list_t *zal, metaslab_group_t *mg,
4402 metaslab_t *msp, uint64_t psize, uint32_t dva_id, uint64_t offset,
4405 metaslab_alloc_trace_t *mat;
4407 if (!metaslab_trace_enabled)
4411 * When the tracing list reaches its maximum we remove
4412 * the second element in the list before adding a new one.
4413 * By removing the second element we preserve the original
4414 * entry as a clue to what allocations steps have already been
4417 if (zal->zal_size == metaslab_trace_max_entries) {
4418 metaslab_alloc_trace_t *mat_next;
4420 panic("too many entries in allocation list");
4422 METASLABSTAT_BUMP(metaslabstat_trace_over_limit);
4424 mat_next = list_next(&zal->zal_list, list_head(&zal->zal_list));
4425 list_remove(&zal->zal_list, mat_next);
4426 kmem_cache_free(metaslab_alloc_trace_cache, mat_next);
4429 mat = kmem_cache_alloc(metaslab_alloc_trace_cache, KM_SLEEP);
4430 list_link_init(&mat->mat_list_node);
4433 mat->mat_size = psize;
4434 mat->mat_dva_id = dva_id;
4435 mat->mat_offset = offset;
4436 mat->mat_weight = 0;
4437 mat->mat_allocator = allocator;
4440 mat->mat_weight = msp->ms_weight;
4443 * The list is part of the zio so locking is not required. Only
4444 * a single thread will perform allocations for a given zio.
4446 list_insert_tail(&zal->zal_list, mat);
4449 ASSERT3U(zal->zal_size, <=, metaslab_trace_max_entries);
4453 metaslab_trace_init(zio_alloc_list_t *zal)
4455 list_create(&zal->zal_list, sizeof (metaslab_alloc_trace_t),
4456 offsetof(metaslab_alloc_trace_t, mat_list_node));
4461 metaslab_trace_fini(zio_alloc_list_t *zal)
4463 metaslab_alloc_trace_t *mat;
4465 while ((mat = list_remove_head(&zal->zal_list)) != NULL)
4466 kmem_cache_free(metaslab_alloc_trace_cache, mat);
4467 list_destroy(&zal->zal_list);
4472 #define metaslab_trace_add(zal, mg, msp, psize, id, off, alloc)
4475 metaslab_trace_init(zio_alloc_list_t *zal)
4480 metaslab_trace_fini(zio_alloc_list_t *zal)
4484 #endif /* _METASLAB_TRACING */
4487 * ==========================================================================
4488 * Metaslab block operations
4489 * ==========================================================================
4493 metaslab_group_alloc_increment(spa_t *spa, uint64_t vdev, void *tag, int flags,
4496 if (!(flags & METASLAB_ASYNC_ALLOC) ||
4497 (flags & METASLAB_DONT_THROTTLE))
4500 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
4501 if (!mg->mg_class->mc_alloc_throttle_enabled)
4504 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4505 (void) zfs_refcount_add(&mga->mga_alloc_queue_depth, tag);
4509 metaslab_group_increment_qdepth(metaslab_group_t *mg, int allocator)
4511 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4512 uint64_t max = mg->mg_max_alloc_queue_depth;
4513 uint64_t cur = mga->mga_cur_max_alloc_queue_depth;
4515 if (atomic_cas_64(&mga->mga_cur_max_alloc_queue_depth,
4516 cur, cur + 1) == cur) {
4518 &mg->mg_class->mc_alloc_max_slots[allocator]);
4521 cur = mga->mga_cur_max_alloc_queue_depth;
4526 metaslab_group_alloc_decrement(spa_t *spa, uint64_t vdev, void *tag, int flags,
4527 int allocator, boolean_t io_complete)
4529 if (!(flags & METASLAB_ASYNC_ALLOC) ||
4530 (flags & METASLAB_DONT_THROTTLE))
4533 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
4534 if (!mg->mg_class->mc_alloc_throttle_enabled)
4537 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4538 (void) zfs_refcount_remove(&mga->mga_alloc_queue_depth, tag);
4540 metaslab_group_increment_qdepth(mg, allocator);
4544 metaslab_group_alloc_verify(spa_t *spa, const blkptr_t *bp, void *tag,
4548 const dva_t *dva = bp->blk_dva;
4549 int ndvas = BP_GET_NDVAS(bp);
4551 for (int d = 0; d < ndvas; d++) {
4552 uint64_t vdev = DVA_GET_VDEV(&dva[d]);
4553 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
4554 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4555 VERIFY(zfs_refcount_not_held(&mga->mga_alloc_queue_depth, tag));
4561 metaslab_block_alloc(metaslab_t *msp, uint64_t size, uint64_t txg)
4564 range_tree_t *rt = msp->ms_allocatable;
4565 metaslab_class_t *mc = msp->ms_group->mg_class;
4567 ASSERT(MUTEX_HELD(&msp->ms_lock));
4568 VERIFY(!msp->ms_condensing);
4569 VERIFY0(msp->ms_disabled);
4571 start = mc->mc_ops->msop_alloc(msp, size);
4572 if (start != -1ULL) {
4573 metaslab_group_t *mg = msp->ms_group;
4574 vdev_t *vd = mg->mg_vd;
4576 VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
4577 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
4578 VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
4579 range_tree_remove(rt, start, size);
4580 range_tree_clear(msp->ms_trim, start, size);
4582 if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
4583 vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
4585 range_tree_add(msp->ms_allocating[txg & TXG_MASK], start, size);
4586 msp->ms_allocating_total += size;
4588 /* Track the last successful allocation */
4589 msp->ms_alloc_txg = txg;
4590 metaslab_verify_space(msp, txg);
4594 * Now that we've attempted the allocation we need to update the
4595 * metaslab's maximum block size since it may have changed.
4597 msp->ms_max_size = metaslab_largest_allocatable(msp);
4602 * Find the metaslab with the highest weight that is less than what we've
4603 * already tried. In the common case, this means that we will examine each
4604 * metaslab at most once. Note that concurrent callers could reorder metaslabs
4605 * by activation/passivation once we have dropped the mg_lock. If a metaslab is
4606 * activated by another thread, and we fail to allocate from the metaslab we
4607 * have selected, we may not try the newly-activated metaslab, and instead
4608 * activate another metaslab. This is not optimal, but generally does not cause
4609 * any problems (a possible exception being if every metaslab is completely full
4610 * except for the newly-activated metaslab which we fail to examine).
4613 find_valid_metaslab(metaslab_group_t *mg, uint64_t activation_weight,
4614 dva_t *dva, int d, boolean_t want_unique, uint64_t asize, int allocator,
4615 boolean_t try_hard, zio_alloc_list_t *zal, metaslab_t *search,
4616 boolean_t *was_active)
4619 avl_tree_t *t = &mg->mg_metaslab_tree;
4620 metaslab_t *msp = avl_find(t, search, &idx);
4622 msp = avl_nearest(t, idx, AVL_AFTER);
4624 for (; msp != NULL; msp = AVL_NEXT(t, msp)) {
4626 if (!metaslab_should_allocate(msp, asize, try_hard)) {
4627 metaslab_trace_add(zal, mg, msp, asize, d,
4628 TRACE_TOO_SMALL, allocator);
4633 * If the selected metaslab is condensing or disabled,
4636 if (msp->ms_condensing || msp->ms_disabled > 0)
4639 *was_active = msp->ms_allocator != -1;
4641 * If we're activating as primary, this is our first allocation
4642 * from this disk, so we don't need to check how close we are.
4643 * If the metaslab under consideration was already active,
4644 * we're getting desperate enough to steal another allocator's
4645 * metaslab, so we still don't care about distances.
4647 if (activation_weight == METASLAB_WEIGHT_PRIMARY || *was_active)
4650 for (i = 0; i < d; i++) {
4652 !metaslab_is_unique(msp, &dva[i]))
4653 break; /* try another metaslab */
4660 search->ms_weight = msp->ms_weight;
4661 search->ms_start = msp->ms_start + 1;
4662 search->ms_allocator = msp->ms_allocator;
4663 search->ms_primary = msp->ms_primary;
4669 metaslab_active_mask_verify(metaslab_t *msp)
4671 ASSERT(MUTEX_HELD(&msp->ms_lock));
4673 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
4676 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0)
4679 if (msp->ms_weight & METASLAB_WEIGHT_PRIMARY) {
4680 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
4681 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_CLAIM);
4682 VERIFY3S(msp->ms_allocator, !=, -1);
4683 VERIFY(msp->ms_primary);
4687 if (msp->ms_weight & METASLAB_WEIGHT_SECONDARY) {
4688 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
4689 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_CLAIM);
4690 VERIFY3S(msp->ms_allocator, !=, -1);
4691 VERIFY(!msp->ms_primary);
4695 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
4696 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
4697 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
4698 VERIFY3S(msp->ms_allocator, ==, -1);
4705 metaslab_group_alloc_normal(metaslab_group_t *mg, zio_alloc_list_t *zal,
4706 uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva, int d,
4707 int allocator, boolean_t try_hard)
4709 metaslab_t *msp = NULL;
4710 uint64_t offset = -1ULL;
4712 uint64_t activation_weight = METASLAB_WEIGHT_PRIMARY;
4713 for (int i = 0; i < d; i++) {
4714 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
4715 DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
4716 activation_weight = METASLAB_WEIGHT_SECONDARY;
4717 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
4718 DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
4719 activation_weight = METASLAB_WEIGHT_CLAIM;
4725 * If we don't have enough metaslabs active to fill the entire array, we
4726 * just use the 0th slot.
4728 if (mg->mg_ms_ready < mg->mg_allocators * 3)
4730 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4732 ASSERT3U(mg->mg_vd->vdev_ms_count, >=, 2);
4734 metaslab_t *search = kmem_alloc(sizeof (*search), KM_SLEEP);
4735 search->ms_weight = UINT64_MAX;
4736 search->ms_start = 0;
4738 * At the end of the metaslab tree are the already-active metaslabs,
4739 * first the primaries, then the secondaries. When we resume searching
4740 * through the tree, we need to consider ms_allocator and ms_primary so
4741 * we start in the location right after where we left off, and don't
4742 * accidentally loop forever considering the same metaslabs.
4744 search->ms_allocator = -1;
4745 search->ms_primary = B_TRUE;
4747 boolean_t was_active = B_FALSE;
4749 mutex_enter(&mg->mg_lock);
4751 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
4752 mga->mga_primary != NULL) {
4753 msp = mga->mga_primary;
4756 * Even though we don't hold the ms_lock for the
4757 * primary metaslab, those fields should not
4758 * change while we hold the mg_lock. Thus it is
4759 * safe to make assertions on them.
4761 ASSERT(msp->ms_primary);
4762 ASSERT3S(msp->ms_allocator, ==, allocator);
4763 ASSERT(msp->ms_loaded);
4765 was_active = B_TRUE;
4766 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
4767 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
4768 mga->mga_secondary != NULL) {
4769 msp = mga->mga_secondary;
4772 * See comment above about the similar assertions
4773 * for the primary metaslab.
4775 ASSERT(!msp->ms_primary);
4776 ASSERT3S(msp->ms_allocator, ==, allocator);
4777 ASSERT(msp->ms_loaded);
4779 was_active = B_TRUE;
4780 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
4782 msp = find_valid_metaslab(mg, activation_weight, dva, d,
4783 want_unique, asize, allocator, try_hard, zal,
4784 search, &was_active);
4787 mutex_exit(&mg->mg_lock);
4789 kmem_free(search, sizeof (*search));
4792 mutex_enter(&msp->ms_lock);
4794 metaslab_active_mask_verify(msp);
4797 * This code is disabled out because of issues with
4798 * tracepoints in non-gpl kernel modules.
4801 DTRACE_PROBE3(ms__activation__attempt,
4802 metaslab_t *, msp, uint64_t, activation_weight,
4803 boolean_t, was_active);
4807 * Ensure that the metaslab we have selected is still
4808 * capable of handling our request. It's possible that
4809 * another thread may have changed the weight while we
4810 * were blocked on the metaslab lock. We check the
4811 * active status first to see if we need to set_selected_txg
4814 if (was_active && !(msp->ms_weight & METASLAB_ACTIVE_MASK)) {
4815 ASSERT3S(msp->ms_allocator, ==, -1);
4816 mutex_exit(&msp->ms_lock);
4821 * If the metaslab was activated for another allocator
4822 * while we were waiting in the ms_lock above, or it's
4823 * a primary and we're seeking a secondary (or vice versa),
4824 * we go back and select a new metaslab.
4826 if (!was_active && (msp->ms_weight & METASLAB_ACTIVE_MASK) &&
4827 (msp->ms_allocator != -1) &&
4828 (msp->ms_allocator != allocator || ((activation_weight ==
4829 METASLAB_WEIGHT_PRIMARY) != msp->ms_primary))) {
4830 ASSERT(msp->ms_loaded);
4831 ASSERT((msp->ms_weight & METASLAB_WEIGHT_CLAIM) ||
4832 msp->ms_allocator != -1);
4833 mutex_exit(&msp->ms_lock);
4838 * This metaslab was used for claiming regions allocated
4839 * by the ZIL during pool import. Once these regions are
4840 * claimed we don't need to keep the CLAIM bit set
4841 * anymore. Passivate this metaslab to zero its activation
4844 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM &&
4845 activation_weight != METASLAB_WEIGHT_CLAIM) {
4846 ASSERT(msp->ms_loaded);
4847 ASSERT3S(msp->ms_allocator, ==, -1);
4848 metaslab_passivate(msp, msp->ms_weight &
4849 ~METASLAB_WEIGHT_CLAIM);
4850 mutex_exit(&msp->ms_lock);
4854 metaslab_set_selected_txg(msp, txg);
4856 int activation_error =
4857 metaslab_activate(msp, allocator, activation_weight);
4858 metaslab_active_mask_verify(msp);
4861 * If the metaslab was activated by another thread for
4862 * another allocator or activation_weight (EBUSY), or it
4863 * failed because another metaslab was assigned as primary
4864 * for this allocator (EEXIST) we continue using this
4865 * metaslab for our allocation, rather than going on to a
4866 * worse metaslab (we waited for that metaslab to be loaded
4869 * If the activation failed due to an I/O error or ENOSPC we
4870 * skip to the next metaslab.
4872 boolean_t activated;
4873 if (activation_error == 0) {
4875 } else if (activation_error == EBUSY ||
4876 activation_error == EEXIST) {
4877 activated = B_FALSE;
4879 mutex_exit(&msp->ms_lock);
4882 ASSERT(msp->ms_loaded);
4885 * Now that we have the lock, recheck to see if we should
4886 * continue to use this metaslab for this allocation. The
4887 * the metaslab is now loaded so metaslab_should_allocate()
4888 * can accurately determine if the allocation attempt should
4891 if (!metaslab_should_allocate(msp, asize, try_hard)) {
4892 /* Passivate this metaslab and select a new one. */
4893 metaslab_trace_add(zal, mg, msp, asize, d,
4894 TRACE_TOO_SMALL, allocator);
4899 * If this metaslab is currently condensing then pick again
4900 * as we can't manipulate this metaslab until it's committed
4901 * to disk. If this metaslab is being initialized, we shouldn't
4902 * allocate from it since the allocated region might be
4903 * overwritten after allocation.
4905 if (msp->ms_condensing) {
4906 metaslab_trace_add(zal, mg, msp, asize, d,
4907 TRACE_CONDENSING, allocator);
4909 metaslab_passivate(msp, msp->ms_weight &
4910 ~METASLAB_ACTIVE_MASK);
4912 mutex_exit(&msp->ms_lock);
4914 } else if (msp->ms_disabled > 0) {
4915 metaslab_trace_add(zal, mg, msp, asize, d,
4916 TRACE_DISABLED, allocator);
4918 metaslab_passivate(msp, msp->ms_weight &
4919 ~METASLAB_ACTIVE_MASK);
4921 mutex_exit(&msp->ms_lock);
4925 offset = metaslab_block_alloc(msp, asize, txg);
4926 metaslab_trace_add(zal, mg, msp, asize, d, offset, allocator);
4928 if (offset != -1ULL) {
4929 /* Proactively passivate the metaslab, if needed */
4931 metaslab_segment_may_passivate(msp);
4935 ASSERT(msp->ms_loaded);
4938 * This code is disabled out because of issues with
4939 * tracepoints in non-gpl kernel modules.
4942 DTRACE_PROBE2(ms__alloc__failure, metaslab_t *, msp,
4947 * We were unable to allocate from this metaslab so determine
4948 * a new weight for this metaslab. Now that we have loaded
4949 * the metaslab we can provide a better hint to the metaslab
4952 * For space-based metaslabs, we use the maximum block size.
4953 * This information is only available when the metaslab
4954 * is loaded and is more accurate than the generic free
4955 * space weight that was calculated by metaslab_weight().
4956 * This information allows us to quickly compare the maximum
4957 * available allocation in the metaslab to the allocation
4958 * size being requested.
4960 * For segment-based metaslabs, determine the new weight
4961 * based on the highest bucket in the range tree. We
4962 * explicitly use the loaded segment weight (i.e. the range
4963 * tree histogram) since it contains the space that is
4964 * currently available for allocation and is accurate
4965 * even within a sync pass.
4968 if (WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
4969 weight = metaslab_largest_allocatable(msp);
4970 WEIGHT_SET_SPACEBASED(weight);
4972 weight = metaslab_weight_from_range_tree(msp);
4976 metaslab_passivate(msp, weight);
4979 * For the case where we use the metaslab that is
4980 * active for another allocator we want to make
4981 * sure that we retain the activation mask.
4983 * Note that we could attempt to use something like
4984 * metaslab_recalculate_weight_and_sort() that
4985 * retains the activation mask here. That function
4986 * uses metaslab_weight() to set the weight though
4987 * which is not as accurate as the calculations
4990 weight |= msp->ms_weight & METASLAB_ACTIVE_MASK;
4991 metaslab_group_sort(mg, msp, weight);
4993 metaslab_active_mask_verify(msp);
4996 * We have just failed an allocation attempt, check
4997 * that metaslab_should_allocate() agrees. Otherwise,
4998 * we may end up in an infinite loop retrying the same
5001 ASSERT(!metaslab_should_allocate(msp, asize, try_hard));
5003 mutex_exit(&msp->ms_lock);
5005 mutex_exit(&msp->ms_lock);
5006 kmem_free(search, sizeof (*search));
5011 metaslab_group_alloc(metaslab_group_t *mg, zio_alloc_list_t *zal,
5012 uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva, int d,
5013 int allocator, boolean_t try_hard)
5016 ASSERT(mg->mg_initialized);
5018 offset = metaslab_group_alloc_normal(mg, zal, asize, txg, want_unique,
5019 dva, d, allocator, try_hard);
5021 mutex_enter(&mg->mg_lock);
5022 if (offset == -1ULL) {
5023 mg->mg_failed_allocations++;
5024 metaslab_trace_add(zal, mg, NULL, asize, d,
5025 TRACE_GROUP_FAILURE, allocator);
5026 if (asize == SPA_GANGBLOCKSIZE) {
5028 * This metaslab group was unable to allocate
5029 * the minimum gang block size so it must be out of
5030 * space. We must notify the allocation throttle
5031 * to start skipping allocation attempts to this
5032 * metaslab group until more space becomes available.
5033 * Note: this failure cannot be caused by the
5034 * allocation throttle since the allocation throttle
5035 * is only responsible for skipping devices and
5036 * not failing block allocations.
5038 mg->mg_no_free_space = B_TRUE;
5041 mg->mg_allocations++;
5042 mutex_exit(&mg->mg_lock);
5047 * Allocate a block for the specified i/o.
5050 metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
5051 dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags,
5052 zio_alloc_list_t *zal, int allocator)
5054 metaslab_group_t *mg, *fast_mg, *rotor;
5056 boolean_t try_hard = B_FALSE;
5058 ASSERT(!DVA_IS_VALID(&dva[d]));
5061 * For testing, make some blocks above a certain size be gang blocks.
5062 * This will result in more split blocks when using device removal,
5063 * and a large number of split blocks coupled with ztest-induced
5064 * damage can result in extremely long reconstruction times. This
5065 * will also test spilling from special to normal.
5067 if (psize >= metaslab_force_ganging && (spa_get_random(100) < 3)) {
5068 metaslab_trace_add(zal, NULL, NULL, psize, d, TRACE_FORCE_GANG,
5070 return (SET_ERROR(ENOSPC));
5074 * Start at the rotor and loop through all mgs until we find something.
5075 * Note that there's no locking on mc_rotor or mc_aliquot because
5076 * nothing actually breaks if we miss a few updates -- we just won't
5077 * allocate quite as evenly. It all balances out over time.
5079 * If we are doing ditto or log blocks, try to spread them across
5080 * consecutive vdevs. If we're forced to reuse a vdev before we've
5081 * allocated all of our ditto blocks, then try and spread them out on
5082 * that vdev as much as possible. If it turns out to not be possible,
5083 * gradually lower our standards until anything becomes acceptable.
5084 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
5085 * gives us hope of containing our fault domains to something we're
5086 * able to reason about. Otherwise, any two top-level vdev failures
5087 * will guarantee the loss of data. With consecutive allocation,
5088 * only two adjacent top-level vdev failures will result in data loss.
5090 * If we are doing gang blocks (hintdva is non-NULL), try to keep
5091 * ourselves on the same vdev as our gang block header. That
5092 * way, we can hope for locality in vdev_cache, plus it makes our
5093 * fault domains something tractable.
5096 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
5099 * It's possible the vdev we're using as the hint no
5100 * longer exists or its mg has been closed (e.g. by
5101 * device removal). Consult the rotor when
5104 if (vd != NULL && vd->vdev_mg != NULL) {
5107 if (flags & METASLAB_HINTBP_AVOID &&
5108 mg->mg_next != NULL)
5113 } else if (d != 0) {
5114 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
5115 mg = vd->vdev_mg->mg_next;
5116 } else if (flags & METASLAB_FASTWRITE) {
5117 mg = fast_mg = mc->mc_rotor;
5120 if (fast_mg->mg_vd->vdev_pending_fastwrite <
5121 mg->mg_vd->vdev_pending_fastwrite)
5123 } while ((fast_mg = fast_mg->mg_next) != mc->mc_rotor);
5126 ASSERT(mc->mc_rotor != NULL);
5131 * If the hint put us into the wrong metaslab class, or into a
5132 * metaslab group that has been passivated, just follow the rotor.
5134 if (mg->mg_class != mc || mg->mg_activation_count <= 0)
5140 boolean_t allocatable;
5142 ASSERT(mg->mg_activation_count == 1);
5146 * Don't allocate from faulted devices.
5149 spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
5150 allocatable = vdev_allocatable(vd);
5151 spa_config_exit(spa, SCL_ZIO, FTAG);
5153 allocatable = vdev_allocatable(vd);
5157 * Determine if the selected metaslab group is eligible
5158 * for allocations. If we're ganging then don't allow
5159 * this metaslab group to skip allocations since that would
5160 * inadvertently return ENOSPC and suspend the pool
5161 * even though space is still available.
5163 if (allocatable && !GANG_ALLOCATION(flags) && !try_hard) {
5164 allocatable = metaslab_group_allocatable(mg, rotor,
5165 psize, allocator, d);
5169 metaslab_trace_add(zal, mg, NULL, psize, d,
5170 TRACE_NOT_ALLOCATABLE, allocator);
5174 ASSERT(mg->mg_initialized);
5177 * Avoid writing single-copy data to a failing,
5178 * non-redundant vdev, unless we've already tried all
5181 if ((vd->vdev_stat.vs_write_errors > 0 ||
5182 vd->vdev_state < VDEV_STATE_HEALTHY) &&
5183 d == 0 && !try_hard && vd->vdev_children == 0) {
5184 metaslab_trace_add(zal, mg, NULL, psize, d,
5185 TRACE_VDEV_ERROR, allocator);
5189 ASSERT(mg->mg_class == mc);
5191 uint64_t asize = vdev_psize_to_asize(vd, psize);
5192 ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
5195 * If we don't need to try hard, then require that the
5196 * block be on a different metaslab from any other DVAs
5197 * in this BP (unique=true). If we are trying hard, then
5198 * allow any metaslab to be used (unique=false).
5200 uint64_t offset = metaslab_group_alloc(mg, zal, asize, txg,
5201 !try_hard, dva, d, allocator, try_hard);
5203 if (offset != -1ULL) {
5205 * If we've just selected this metaslab group,
5206 * figure out whether the corresponding vdev is
5207 * over- or under-used relative to the pool,
5208 * and set an allocation bias to even it out.
5210 * Bias is also used to compensate for unequally
5211 * sized vdevs so that space is allocated fairly.
5213 if (mc->mc_aliquot == 0 && metaslab_bias_enabled) {
5214 vdev_stat_t *vs = &vd->vdev_stat;
5215 int64_t vs_free = vs->vs_space - vs->vs_alloc;
5216 int64_t mc_free = mc->mc_space - mc->mc_alloc;
5220 * Calculate how much more or less we should
5221 * try to allocate from this device during
5222 * this iteration around the rotor.
5224 * This basically introduces a zero-centered
5225 * bias towards the devices with the most
5226 * free space, while compensating for vdev
5230 * vdev V1 = 16M/128M
5231 * vdev V2 = 16M/128M
5232 * ratio(V1) = 100% ratio(V2) = 100%
5234 * vdev V1 = 16M/128M
5235 * vdev V2 = 64M/128M
5236 * ratio(V1) = 127% ratio(V2) = 72%
5238 * vdev V1 = 16M/128M
5239 * vdev V2 = 64M/512M
5240 * ratio(V1) = 40% ratio(V2) = 160%
5242 ratio = (vs_free * mc->mc_alloc_groups * 100) /
5244 mg->mg_bias = ((ratio - 100) *
5245 (int64_t)mg->mg_aliquot) / 100;
5246 } else if (!metaslab_bias_enabled) {
5250 if ((flags & METASLAB_FASTWRITE) ||
5251 atomic_add_64_nv(&mc->mc_aliquot, asize) >=
5252 mg->mg_aliquot + mg->mg_bias) {
5253 mc->mc_rotor = mg->mg_next;
5257 DVA_SET_VDEV(&dva[d], vd->vdev_id);
5258 DVA_SET_OFFSET(&dva[d], offset);
5259 DVA_SET_GANG(&dva[d],
5260 ((flags & METASLAB_GANG_HEADER) ? 1 : 0));
5261 DVA_SET_ASIZE(&dva[d], asize);
5263 if (flags & METASLAB_FASTWRITE) {
5264 atomic_add_64(&vd->vdev_pending_fastwrite,
5271 mc->mc_rotor = mg->mg_next;
5273 } while ((mg = mg->mg_next) != rotor);
5276 * If we haven't tried hard, do so now.
5283 bzero(&dva[d], sizeof (dva_t));
5285 metaslab_trace_add(zal, rotor, NULL, psize, d, TRACE_ENOSPC, allocator);
5286 return (SET_ERROR(ENOSPC));
5290 metaslab_free_concrete(vdev_t *vd, uint64_t offset, uint64_t asize,
5291 boolean_t checkpoint)
5294 spa_t *spa = vd->vdev_spa;
5296 ASSERT(vdev_is_concrete(vd));
5297 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5298 ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
5300 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5302 VERIFY(!msp->ms_condensing);
5303 VERIFY3U(offset, >=, msp->ms_start);
5304 VERIFY3U(offset + asize, <=, msp->ms_start + msp->ms_size);
5305 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5306 VERIFY0(P2PHASE(asize, 1ULL << vd->vdev_ashift));
5308 metaslab_check_free_impl(vd, offset, asize);
5310 mutex_enter(&msp->ms_lock);
5311 if (range_tree_is_empty(msp->ms_freeing) &&
5312 range_tree_is_empty(msp->ms_checkpointing)) {
5313 vdev_dirty(vd, VDD_METASLAB, msp, spa_syncing_txg(spa));
5317 ASSERT(spa_has_checkpoint(spa));
5318 range_tree_add(msp->ms_checkpointing, offset, asize);
5320 range_tree_add(msp->ms_freeing, offset, asize);
5322 mutex_exit(&msp->ms_lock);
5327 metaslab_free_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5328 uint64_t size, void *arg)
5330 boolean_t *checkpoint = arg;
5332 ASSERT3P(checkpoint, !=, NULL);
5334 if (vd->vdev_ops->vdev_op_remap != NULL)
5335 vdev_indirect_mark_obsolete(vd, offset, size);
5337 metaslab_free_impl(vd, offset, size, *checkpoint);
5341 metaslab_free_impl(vdev_t *vd, uint64_t offset, uint64_t size,
5342 boolean_t checkpoint)
5344 spa_t *spa = vd->vdev_spa;
5346 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5348 if (spa_syncing_txg(spa) > spa_freeze_txg(spa))
5351 if (spa->spa_vdev_removal != NULL &&
5352 spa->spa_vdev_removal->svr_vdev_id == vd->vdev_id &&
5353 vdev_is_concrete(vd)) {
5355 * Note: we check if the vdev is concrete because when
5356 * we complete the removal, we first change the vdev to be
5357 * an indirect vdev (in open context), and then (in syncing
5358 * context) clear spa_vdev_removal.
5360 free_from_removing_vdev(vd, offset, size);
5361 } else if (vd->vdev_ops->vdev_op_remap != NULL) {
5362 vdev_indirect_mark_obsolete(vd, offset, size);
5363 vd->vdev_ops->vdev_op_remap(vd, offset, size,
5364 metaslab_free_impl_cb, &checkpoint);
5366 metaslab_free_concrete(vd, offset, size, checkpoint);
5370 typedef struct remap_blkptr_cb_arg {
5372 spa_remap_cb_t rbca_cb;
5373 vdev_t *rbca_remap_vd;
5374 uint64_t rbca_remap_offset;
5376 } remap_blkptr_cb_arg_t;
5379 remap_blkptr_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5380 uint64_t size, void *arg)
5382 remap_blkptr_cb_arg_t *rbca = arg;
5383 blkptr_t *bp = rbca->rbca_bp;
5385 /* We can not remap split blocks. */
5386 if (size != DVA_GET_ASIZE(&bp->blk_dva[0]))
5388 ASSERT0(inner_offset);
5390 if (rbca->rbca_cb != NULL) {
5392 * At this point we know that we are not handling split
5393 * blocks and we invoke the callback on the previous
5394 * vdev which must be indirect.
5396 ASSERT3P(rbca->rbca_remap_vd->vdev_ops, ==, &vdev_indirect_ops);
5398 rbca->rbca_cb(rbca->rbca_remap_vd->vdev_id,
5399 rbca->rbca_remap_offset, size, rbca->rbca_cb_arg);
5401 /* set up remap_blkptr_cb_arg for the next call */
5402 rbca->rbca_remap_vd = vd;
5403 rbca->rbca_remap_offset = offset;
5407 * The phys birth time is that of dva[0]. This ensures that we know
5408 * when each dva was written, so that resilver can determine which
5409 * blocks need to be scrubbed (i.e. those written during the time
5410 * the vdev was offline). It also ensures that the key used in
5411 * the ARC hash table is unique (i.e. dva[0] + phys_birth). If
5412 * we didn't change the phys_birth, a lookup in the ARC for a
5413 * remapped BP could find the data that was previously stored at
5414 * this vdev + offset.
5416 vdev_t *oldvd = vdev_lookup_top(vd->vdev_spa,
5417 DVA_GET_VDEV(&bp->blk_dva[0]));
5418 vdev_indirect_births_t *vib = oldvd->vdev_indirect_births;
5419 bp->blk_phys_birth = vdev_indirect_births_physbirth(vib,
5420 DVA_GET_OFFSET(&bp->blk_dva[0]), DVA_GET_ASIZE(&bp->blk_dva[0]));
5422 DVA_SET_VDEV(&bp->blk_dva[0], vd->vdev_id);
5423 DVA_SET_OFFSET(&bp->blk_dva[0], offset);
5427 * If the block pointer contains any indirect DVAs, modify them to refer to
5428 * concrete DVAs. Note that this will sometimes not be possible, leaving
5429 * the indirect DVA in place. This happens if the indirect DVA spans multiple
5430 * segments in the mapping (i.e. it is a "split block").
5432 * If the BP was remapped, calls the callback on the original dva (note the
5433 * callback can be called multiple times if the original indirect DVA refers
5434 * to another indirect DVA, etc).
5436 * Returns TRUE if the BP was remapped.
5439 spa_remap_blkptr(spa_t *spa, blkptr_t *bp, spa_remap_cb_t callback, void *arg)
5441 remap_blkptr_cb_arg_t rbca;
5443 if (!zfs_remap_blkptr_enable)
5446 if (!spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS))
5450 * Dedup BP's can not be remapped, because ddt_phys_select() depends
5451 * on DVA[0] being the same in the BP as in the DDT (dedup table).
5453 if (BP_GET_DEDUP(bp))
5457 * Gang blocks can not be remapped, because
5458 * zio_checksum_gang_verifier() depends on the DVA[0] that's in
5459 * the BP used to read the gang block header (GBH) being the same
5460 * as the DVA[0] that we allocated for the GBH.
5466 * Embedded BP's have no DVA to remap.
5468 if (BP_GET_NDVAS(bp) < 1)
5472 * Note: we only remap dva[0]. If we remapped other dvas, we
5473 * would no longer know what their phys birth txg is.
5475 dva_t *dva = &bp->blk_dva[0];
5477 uint64_t offset = DVA_GET_OFFSET(dva);
5478 uint64_t size = DVA_GET_ASIZE(dva);
5479 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
5481 if (vd->vdev_ops->vdev_op_remap == NULL)
5485 rbca.rbca_cb = callback;
5486 rbca.rbca_remap_vd = vd;
5487 rbca.rbca_remap_offset = offset;
5488 rbca.rbca_cb_arg = arg;
5491 * remap_blkptr_cb() will be called in order for each level of
5492 * indirection, until a concrete vdev is reached or a split block is
5493 * encountered. old_vd and old_offset are updated within the callback
5494 * as we go from the one indirect vdev to the next one (either concrete
5495 * or indirect again) in that order.
5497 vd->vdev_ops->vdev_op_remap(vd, offset, size, remap_blkptr_cb, &rbca);
5499 /* Check if the DVA wasn't remapped because it is a split block */
5500 if (DVA_GET_VDEV(&rbca.rbca_bp->blk_dva[0]) == vd->vdev_id)
5507 * Undo the allocation of a DVA which happened in the given transaction group.
5510 metaslab_unalloc_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
5514 uint64_t vdev = DVA_GET_VDEV(dva);
5515 uint64_t offset = DVA_GET_OFFSET(dva);
5516 uint64_t size = DVA_GET_ASIZE(dva);
5518 ASSERT(DVA_IS_VALID(dva));
5519 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5521 if (txg > spa_freeze_txg(spa))
5524 if ((vd = vdev_lookup_top(spa, vdev)) == NULL || !DVA_IS_VALID(dva) ||
5525 (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
5526 zfs_panic_recover("metaslab_free_dva(): bad DVA %llu:%llu:%llu",
5527 (u_longlong_t)vdev, (u_longlong_t)offset,
5528 (u_longlong_t)size);
5532 ASSERT(!vd->vdev_removing);
5533 ASSERT(vdev_is_concrete(vd));
5534 ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
5535 ASSERT3P(vd->vdev_indirect_mapping, ==, NULL);
5537 if (DVA_GET_GANG(dva))
5538 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
5540 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5542 mutex_enter(&msp->ms_lock);
5543 range_tree_remove(msp->ms_allocating[txg & TXG_MASK],
5545 msp->ms_allocating_total -= size;
5547 VERIFY(!msp->ms_condensing);
5548 VERIFY3U(offset, >=, msp->ms_start);
5549 VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
5550 VERIFY3U(range_tree_space(msp->ms_allocatable) + size, <=,
5552 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5553 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
5554 range_tree_add(msp->ms_allocatable, offset, size);
5555 mutex_exit(&msp->ms_lock);
5559 * Free the block represented by the given DVA.
5562 metaslab_free_dva(spa_t *spa, const dva_t *dva, boolean_t checkpoint)
5564 uint64_t vdev = DVA_GET_VDEV(dva);
5565 uint64_t offset = DVA_GET_OFFSET(dva);
5566 uint64_t size = DVA_GET_ASIZE(dva);
5567 vdev_t *vd = vdev_lookup_top(spa, vdev);
5569 ASSERT(DVA_IS_VALID(dva));
5570 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5572 if (DVA_GET_GANG(dva)) {
5573 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
5576 metaslab_free_impl(vd, offset, size, checkpoint);
5580 * Reserve some allocation slots. The reservation system must be called
5581 * before we call into the allocator. If there aren't any available slots
5582 * then the I/O will be throttled until an I/O completes and its slots are
5583 * freed up. The function returns true if it was successful in placing
5587 metaslab_class_throttle_reserve(metaslab_class_t *mc, int slots, int allocator,
5588 zio_t *zio, int flags)
5590 uint64_t available_slots = 0;
5591 boolean_t slot_reserved = B_FALSE;
5592 uint64_t max = mc->mc_alloc_max_slots[allocator];
5594 ASSERT(mc->mc_alloc_throttle_enabled);
5595 mutex_enter(&mc->mc_lock);
5597 uint64_t reserved_slots =
5598 zfs_refcount_count(&mc->mc_alloc_slots[allocator]);
5599 if (reserved_slots < max)
5600 available_slots = max - reserved_slots;
5602 if (slots <= available_slots || GANG_ALLOCATION(flags) ||
5603 flags & METASLAB_MUST_RESERVE) {
5605 * We reserve the slots individually so that we can unreserve
5606 * them individually when an I/O completes.
5608 for (int d = 0; d < slots; d++) {
5610 zfs_refcount_add(&mc->mc_alloc_slots[allocator],
5613 zio->io_flags |= ZIO_FLAG_IO_ALLOCATING;
5614 slot_reserved = B_TRUE;
5617 mutex_exit(&mc->mc_lock);
5618 return (slot_reserved);
5622 metaslab_class_throttle_unreserve(metaslab_class_t *mc, int slots,
5623 int allocator, zio_t *zio)
5625 ASSERT(mc->mc_alloc_throttle_enabled);
5626 mutex_enter(&mc->mc_lock);
5627 for (int d = 0; d < slots; d++) {
5628 (void) zfs_refcount_remove(&mc->mc_alloc_slots[allocator],
5631 mutex_exit(&mc->mc_lock);
5635 metaslab_claim_concrete(vdev_t *vd, uint64_t offset, uint64_t size,
5639 spa_t *spa = vd->vdev_spa;
5642 if (offset >> vd->vdev_ms_shift >= vd->vdev_ms_count)
5643 return (SET_ERROR(ENXIO));
5645 ASSERT3P(vd->vdev_ms, !=, NULL);
5646 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5648 mutex_enter(&msp->ms_lock);
5650 if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded) {
5651 error = metaslab_activate(msp, 0, METASLAB_WEIGHT_CLAIM);
5652 if (error == EBUSY) {
5653 ASSERT(msp->ms_loaded);
5654 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
5660 !range_tree_contains(msp->ms_allocatable, offset, size))
5661 error = SET_ERROR(ENOENT);
5663 if (error || txg == 0) { /* txg == 0 indicates dry run */
5664 mutex_exit(&msp->ms_lock);
5668 VERIFY(!msp->ms_condensing);
5669 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5670 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
5671 VERIFY3U(range_tree_space(msp->ms_allocatable) - size, <=,
5673 range_tree_remove(msp->ms_allocatable, offset, size);
5674 range_tree_clear(msp->ms_trim, offset, size);
5676 if (spa_writeable(spa)) { /* don't dirty if we're zdb(1M) */
5677 metaslab_class_t *mc = msp->ms_group->mg_class;
5678 multilist_sublist_t *mls =
5679 multilist_sublist_lock_obj(mc->mc_metaslab_txg_list, msp);
5680 if (!multilist_link_active(&msp->ms_class_txg_node)) {
5681 msp->ms_selected_txg = txg;
5682 multilist_sublist_insert_head(mls, msp);
5684 multilist_sublist_unlock(mls);
5686 if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
5687 vdev_dirty(vd, VDD_METASLAB, msp, txg);
5688 range_tree_add(msp->ms_allocating[txg & TXG_MASK],
5690 msp->ms_allocating_total += size;
5693 mutex_exit(&msp->ms_lock);
5698 typedef struct metaslab_claim_cb_arg_t {
5701 } metaslab_claim_cb_arg_t;
5705 metaslab_claim_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5706 uint64_t size, void *arg)
5708 metaslab_claim_cb_arg_t *mcca_arg = arg;
5710 if (mcca_arg->mcca_error == 0) {
5711 mcca_arg->mcca_error = metaslab_claim_concrete(vd, offset,
5712 size, mcca_arg->mcca_txg);
5717 metaslab_claim_impl(vdev_t *vd, uint64_t offset, uint64_t size, uint64_t txg)
5719 if (vd->vdev_ops->vdev_op_remap != NULL) {
5720 metaslab_claim_cb_arg_t arg;
5723 * Only zdb(1M) can claim on indirect vdevs. This is used
5724 * to detect leaks of mapped space (that are not accounted
5725 * for in the obsolete counts, spacemap, or bpobj).
5727 ASSERT(!spa_writeable(vd->vdev_spa));
5731 vd->vdev_ops->vdev_op_remap(vd, offset, size,
5732 metaslab_claim_impl_cb, &arg);
5734 if (arg.mcca_error == 0) {
5735 arg.mcca_error = metaslab_claim_concrete(vd,
5738 return (arg.mcca_error);
5740 return (metaslab_claim_concrete(vd, offset, size, txg));
5745 * Intent log support: upon opening the pool after a crash, notify the SPA
5746 * of blocks that the intent log has allocated for immediate write, but
5747 * which are still considered free by the SPA because the last transaction
5748 * group didn't commit yet.
5751 metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
5753 uint64_t vdev = DVA_GET_VDEV(dva);
5754 uint64_t offset = DVA_GET_OFFSET(dva);
5755 uint64_t size = DVA_GET_ASIZE(dva);
5758 if ((vd = vdev_lookup_top(spa, vdev)) == NULL) {
5759 return (SET_ERROR(ENXIO));
5762 ASSERT(DVA_IS_VALID(dva));
5764 if (DVA_GET_GANG(dva))
5765 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
5767 return (metaslab_claim_impl(vd, offset, size, txg));
5771 metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
5772 int ndvas, uint64_t txg, blkptr_t *hintbp, int flags,
5773 zio_alloc_list_t *zal, zio_t *zio, int allocator)
5775 dva_t *dva = bp->blk_dva;
5776 dva_t *hintdva = (hintbp != NULL) ? hintbp->blk_dva : NULL;
5779 ASSERT(bp->blk_birth == 0);
5780 ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
5782 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
5784 if (mc->mc_rotor == NULL) { /* no vdevs in this class */
5785 spa_config_exit(spa, SCL_ALLOC, FTAG);
5786 return (SET_ERROR(ENOSPC));
5789 ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
5790 ASSERT(BP_GET_NDVAS(bp) == 0);
5791 ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
5792 ASSERT3P(zal, !=, NULL);
5794 for (int d = 0; d < ndvas; d++) {
5795 error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
5796 txg, flags, zal, allocator);
5798 for (d--; d >= 0; d--) {
5799 metaslab_unalloc_dva(spa, &dva[d], txg);
5800 metaslab_group_alloc_decrement(spa,
5801 DVA_GET_VDEV(&dva[d]), zio, flags,
5802 allocator, B_FALSE);
5803 bzero(&dva[d], sizeof (dva_t));
5805 spa_config_exit(spa, SCL_ALLOC, FTAG);
5809 * Update the metaslab group's queue depth
5810 * based on the newly allocated dva.
5812 metaslab_group_alloc_increment(spa,
5813 DVA_GET_VDEV(&dva[d]), zio, flags, allocator);
5818 ASSERT(BP_GET_NDVAS(bp) == ndvas);
5820 spa_config_exit(spa, SCL_ALLOC, FTAG);
5822 BP_SET_BIRTH(bp, txg, 0);
5828 metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
5830 const dva_t *dva = bp->blk_dva;
5831 int ndvas = BP_GET_NDVAS(bp);
5833 ASSERT(!BP_IS_HOLE(bp));
5834 ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
5837 * If we have a checkpoint for the pool we need to make sure that
5838 * the blocks that we free that are part of the checkpoint won't be
5839 * reused until the checkpoint is discarded or we revert to it.
5841 * The checkpoint flag is passed down the metaslab_free code path
5842 * and is set whenever we want to add a block to the checkpoint's
5843 * accounting. That is, we "checkpoint" blocks that existed at the
5844 * time the checkpoint was created and are therefore referenced by
5845 * the checkpointed uberblock.
5847 * Note that, we don't checkpoint any blocks if the current
5848 * syncing txg <= spa_checkpoint_txg. We want these frees to sync
5849 * normally as they will be referenced by the checkpointed uberblock.
5851 boolean_t checkpoint = B_FALSE;
5852 if (bp->blk_birth <= spa->spa_checkpoint_txg &&
5853 spa_syncing_txg(spa) > spa->spa_checkpoint_txg) {
5855 * At this point, if the block is part of the checkpoint
5856 * there is no way it was created in the current txg.
5859 ASSERT3U(spa_syncing_txg(spa), ==, txg);
5860 checkpoint = B_TRUE;
5863 spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
5865 for (int d = 0; d < ndvas; d++) {
5867 metaslab_unalloc_dva(spa, &dva[d], txg);
5869 ASSERT3U(txg, ==, spa_syncing_txg(spa));
5870 metaslab_free_dva(spa, &dva[d], checkpoint);
5874 spa_config_exit(spa, SCL_FREE, FTAG);
5878 metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
5880 const dva_t *dva = bp->blk_dva;
5881 int ndvas = BP_GET_NDVAS(bp);
5884 ASSERT(!BP_IS_HOLE(bp));
5888 * First do a dry run to make sure all DVAs are claimable,
5889 * so we don't have to unwind from partial failures below.
5891 if ((error = metaslab_claim(spa, bp, 0)) != 0)
5895 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
5897 for (int d = 0; d < ndvas; d++) {
5898 error = metaslab_claim_dva(spa, &dva[d], txg);
5903 spa_config_exit(spa, SCL_ALLOC, FTAG);
5905 ASSERT(error == 0 || txg == 0);
5911 metaslab_fastwrite_mark(spa_t *spa, const blkptr_t *bp)
5913 const dva_t *dva = bp->blk_dva;
5914 int ndvas = BP_GET_NDVAS(bp);
5915 uint64_t psize = BP_GET_PSIZE(bp);
5919 ASSERT(!BP_IS_HOLE(bp));
5920 ASSERT(!BP_IS_EMBEDDED(bp));
5923 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
5925 for (d = 0; d < ndvas; d++) {
5926 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
5928 atomic_add_64(&vd->vdev_pending_fastwrite, psize);
5931 spa_config_exit(spa, SCL_VDEV, FTAG);
5935 metaslab_fastwrite_unmark(spa_t *spa, const blkptr_t *bp)
5937 const dva_t *dva = bp->blk_dva;
5938 int ndvas = BP_GET_NDVAS(bp);
5939 uint64_t psize = BP_GET_PSIZE(bp);
5943 ASSERT(!BP_IS_HOLE(bp));
5944 ASSERT(!BP_IS_EMBEDDED(bp));
5947 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
5949 for (d = 0; d < ndvas; d++) {
5950 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
5952 ASSERT3U(vd->vdev_pending_fastwrite, >=, psize);
5953 atomic_sub_64(&vd->vdev_pending_fastwrite, psize);
5956 spa_config_exit(spa, SCL_VDEV, FTAG);
5961 metaslab_check_free_impl_cb(uint64_t inner, vdev_t *vd, uint64_t offset,
5962 uint64_t size, void *arg)
5964 if (vd->vdev_ops == &vdev_indirect_ops)
5967 metaslab_check_free_impl(vd, offset, size);
5971 metaslab_check_free_impl(vdev_t *vd, uint64_t offset, uint64_t size)
5974 spa_t *spa __maybe_unused = vd->vdev_spa;
5976 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
5979 if (vd->vdev_ops->vdev_op_remap != NULL) {
5980 vd->vdev_ops->vdev_op_remap(vd, offset, size,
5981 metaslab_check_free_impl_cb, NULL);
5985 ASSERT(vdev_is_concrete(vd));
5986 ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
5987 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5989 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5991 mutex_enter(&msp->ms_lock);
5992 if (msp->ms_loaded) {
5993 range_tree_verify_not_present(msp->ms_allocatable,
5998 * Check all segments that currently exist in the freeing pipeline.
6000 * It would intuitively make sense to also check the current allocating
6001 * tree since metaslab_unalloc_dva() exists for extents that are
6002 * allocated and freed in the same sync pass within the same txg.
6003 * Unfortunately there are places (e.g. the ZIL) where we allocate a
6004 * segment but then we free part of it within the same txg
6005 * [see zil_sync()]. Thus, we don't call range_tree_verify() in the
6006 * current allocating tree.
6008 range_tree_verify_not_present(msp->ms_freeing, offset, size);
6009 range_tree_verify_not_present(msp->ms_checkpointing, offset, size);
6010 range_tree_verify_not_present(msp->ms_freed, offset, size);
6011 for (int j = 0; j < TXG_DEFER_SIZE; j++)
6012 range_tree_verify_not_present(msp->ms_defer[j], offset, size);
6013 range_tree_verify_not_present(msp->ms_trim, offset, size);
6014 mutex_exit(&msp->ms_lock);
6018 metaslab_check_free(spa_t *spa, const blkptr_t *bp)
6020 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
6023 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6024 for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
6025 uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
6026 vdev_t *vd = vdev_lookup_top(spa, vdev);
6027 uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
6028 uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
6030 if (DVA_GET_GANG(&bp->blk_dva[i]))
6031 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
6033 ASSERT3P(vd, !=, NULL);
6035 metaslab_check_free_impl(vd, offset, size);
6037 spa_config_exit(spa, SCL_VDEV, FTAG);
6041 metaslab_group_disable_wait(metaslab_group_t *mg)
6043 ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
6044 while (mg->mg_disabled_updating) {
6045 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
6050 metaslab_group_disabled_increment(metaslab_group_t *mg)
6052 ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
6053 ASSERT(mg->mg_disabled_updating);
6055 while (mg->mg_ms_disabled >= max_disabled_ms) {
6056 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
6058 mg->mg_ms_disabled++;
6059 ASSERT3U(mg->mg_ms_disabled, <=, max_disabled_ms);
6063 * Mark the metaslab as disabled to prevent any allocations on this metaslab.
6064 * We must also track how many metaslabs are currently disabled within a
6065 * metaslab group and limit them to prevent allocation failures from
6066 * occurring because all metaslabs are disabled.
6069 metaslab_disable(metaslab_t *msp)
6071 ASSERT(!MUTEX_HELD(&msp->ms_lock));
6072 metaslab_group_t *mg = msp->ms_group;
6074 mutex_enter(&mg->mg_ms_disabled_lock);
6077 * To keep an accurate count of how many threads have disabled
6078 * a specific metaslab group, we only allow one thread to mark
6079 * the metaslab group at a time. This ensures that the value of
6080 * ms_disabled will be accurate when we decide to mark a metaslab
6081 * group as disabled. To do this we force all other threads
6082 * to wait till the metaslab's mg_disabled_updating flag is no
6085 metaslab_group_disable_wait(mg);
6086 mg->mg_disabled_updating = B_TRUE;
6087 if (msp->ms_disabled == 0) {
6088 metaslab_group_disabled_increment(mg);
6090 mutex_enter(&msp->ms_lock);
6092 mutex_exit(&msp->ms_lock);
6094 mg->mg_disabled_updating = B_FALSE;
6095 cv_broadcast(&mg->mg_ms_disabled_cv);
6096 mutex_exit(&mg->mg_ms_disabled_lock);
6100 metaslab_enable(metaslab_t *msp, boolean_t sync, boolean_t unload)
6102 metaslab_group_t *mg = msp->ms_group;
6103 spa_t *spa = mg->mg_vd->vdev_spa;
6106 * Wait for the outstanding IO to be synced to prevent newly
6107 * allocated blocks from being overwritten. This used by
6108 * initialize and TRIM which are modifying unallocated space.
6111 txg_wait_synced(spa_get_dsl(spa), 0);
6113 mutex_enter(&mg->mg_ms_disabled_lock);
6114 mutex_enter(&msp->ms_lock);
6115 if (--msp->ms_disabled == 0) {
6116 mg->mg_ms_disabled--;
6117 cv_broadcast(&mg->mg_ms_disabled_cv);
6119 metaslab_unload(msp);
6121 mutex_exit(&msp->ms_lock);
6122 mutex_exit(&mg->mg_ms_disabled_lock);
6126 metaslab_update_ondisk_flush_data(metaslab_t *ms, dmu_tx_t *tx)
6128 vdev_t *vd = ms->ms_group->mg_vd;
6129 spa_t *spa = vd->vdev_spa;
6130 objset_t *mos = spa_meta_objset(spa);
6132 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
6134 metaslab_unflushed_phys_t entry = {
6135 .msp_unflushed_txg = metaslab_unflushed_txg(ms),
6137 uint64_t entry_size = sizeof (entry);
6138 uint64_t entry_offset = ms->ms_id * entry_size;
6140 uint64_t object = 0;
6141 int err = zap_lookup(mos, vd->vdev_top_zap,
6142 VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1,
6144 if (err == ENOENT) {
6145 object = dmu_object_alloc(mos, DMU_OTN_UINT64_METADATA,
6146 SPA_OLD_MAXBLOCKSIZE, DMU_OT_NONE, 0, tx);
6147 VERIFY0(zap_add(mos, vd->vdev_top_zap,
6148 VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1,
6154 dmu_write(spa_meta_objset(spa), object, entry_offset, entry_size,
6159 metaslab_set_unflushed_txg(metaslab_t *ms, uint64_t txg, dmu_tx_t *tx)
6161 spa_t *spa = ms->ms_group->mg_vd->vdev_spa;
6163 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
6166 ms->ms_unflushed_txg = txg;
6167 metaslab_update_ondisk_flush_data(ms, tx);
6171 metaslab_unflushed_txg(metaslab_t *ms)
6173 return (ms->ms_unflushed_txg);
6176 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, aliquot, ULONG, ZMOD_RW,
6177 "Allocation granularity (a.k.a. stripe size)");
6179 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, debug_load, INT, ZMOD_RW,
6180 "Load all metaslabs when pool is first opened");
6182 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, debug_unload, INT, ZMOD_RW,
6183 "Prevent metaslabs from being unloaded");
6185 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, preload_enabled, INT, ZMOD_RW,
6186 "Preload potential metaslabs during reassessment");
6188 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, unload_delay, INT, ZMOD_RW,
6189 "Delay in txgs after metaslab was last used before unloading");
6191 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, unload_delay_ms, INT, ZMOD_RW,
6192 "Delay in milliseconds after metaslab was last used before unloading");
6195 ZFS_MODULE_PARAM(zfs_mg, zfs_mg_, noalloc_threshold, INT, ZMOD_RW,
6196 "Percentage of metaslab group size that should be free to make it "
6197 "eligible for allocation");
6199 ZFS_MODULE_PARAM(zfs_mg, zfs_mg_, fragmentation_threshold, INT, ZMOD_RW,
6200 "Percentage of metaslab group size that should be considered eligible "
6201 "for allocations unless all metaslab groups within the metaslab class "
6202 "have also crossed this threshold");
6204 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, fragmentation_threshold, INT,
6205 ZMOD_RW, "Fragmentation for metaslab to allow allocation");
6207 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, fragmentation_factor_enabled, INT, ZMOD_RW,
6208 "Use the fragmentation metric to prefer less fragmented metaslabs");
6211 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, lba_weighting_enabled, INT, ZMOD_RW,
6212 "Prefer metaslabs with lower LBAs");
6214 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, bias_enabled, INT, ZMOD_RW,
6215 "Enable metaslab group biasing");
6217 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, segment_weight_enabled, INT,
6218 ZMOD_RW, "Enable segment-based metaslab selection");
6220 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, switch_threshold, INT, ZMOD_RW,
6221 "Segment-based metaslab selection maximum buckets before switching");
6223 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, force_ganging, ULONG, ZMOD_RW,
6224 "Blocks larger than this size are forced to be gang blocks");
6226 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_max_search, INT, ZMOD_RW,
6227 "Max distance (bytes) to search forward before using size tree");
6229 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_use_largest_segment, INT, ZMOD_RW,
6230 "When looking in size tree, use largest segment instead of exact fit");
6232 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, max_size_cache_sec, ULONG,
6233 ZMOD_RW, "How long to trust the cached max chunk size of a metaslab");
6235 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, mem_limit, INT, ZMOD_RW,
6236 "Percentage of memory that can be used to store metaslab range trees");