4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
24 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
27 #include <sys/zfs_context.h>
29 #include <sys/dmu_tx.h>
30 #include <sys/space_map.h>
31 #include <sys/metaslab_impl.h>
32 #include <sys/vdev_impl.h>
34 #include <sys/spa_impl.h>
35 #include <sys/zfeature.h>
36 #include <sys/vdev_indirect_mapping.h>
39 #define WITH_DF_BLOCK_ALLOCATOR
41 #define GANG_ALLOCATION(flags) \
42 ((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER))
45 * Metaslab granularity, in bytes. This is roughly similar to what would be
46 * referred to as the "stripe size" in traditional RAID arrays. In normal
47 * operation, we will try to write this amount of data to a top-level vdev
48 * before moving on to the next one.
50 unsigned long metaslab_aliquot
= 512 << 10;
53 * For testing, make some blocks above a certain size be gang blocks.
55 unsigned long metaslab_force_ganging
= SPA_MAXBLOCKSIZE
+ 1;
58 * Since we can touch multiple metaslabs (and their respective space maps)
59 * with each transaction group, we benefit from having a smaller space map
60 * block size since it allows us to issue more I/O operations scattered
63 int zfs_metaslab_sm_blksz
= (1 << 12);
66 * The in-core space map representation is more compact than its on-disk form.
67 * The zfs_condense_pct determines how much more compact the in-core
68 * space map representation must be before we compact it on-disk.
69 * Values should be greater than or equal to 100.
71 int zfs_condense_pct
= 200;
74 * Condensing a metaslab is not guaranteed to actually reduce the amount of
75 * space used on disk. In particular, a space map uses data in increments of
76 * MAX(1 << ashift, space_map_blksz), so a metaslab might use the
77 * same number of blocks after condensing. Since the goal of condensing is to
78 * reduce the number of IOPs required to read the space map, we only want to
79 * condense when we can be sure we will reduce the number of blocks used by the
80 * space map. Unfortunately, we cannot precisely compute whether or not this is
81 * the case in metaslab_should_condense since we are holding ms_lock. Instead,
82 * we apply the following heuristic: do not condense a spacemap unless the
83 * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
86 int zfs_metaslab_condense_block_threshold
= 4;
89 * The zfs_mg_noalloc_threshold defines which metaslab groups should
90 * be eligible for allocation. The value is defined as a percentage of
91 * free space. Metaslab groups that have more free space than
92 * zfs_mg_noalloc_threshold are always eligible for allocations. Once
93 * a metaslab group's free space is less than or equal to the
94 * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
95 * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
96 * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
97 * groups are allowed to accept allocations. Gang blocks are always
98 * eligible to allocate on any metaslab group. The default value of 0 means
99 * no metaslab group will be excluded based on this criterion.
101 int zfs_mg_noalloc_threshold
= 0;
104 * Metaslab groups are considered eligible for allocations if their
105 * fragmenation metric (measured as a percentage) is less than or equal to
106 * zfs_mg_fragmentation_threshold. If a metaslab group exceeds this threshold
107 * then it will be skipped unless all metaslab groups within the metaslab
108 * class have also crossed this threshold.
110 int zfs_mg_fragmentation_threshold
= 85;
113 * Allow metaslabs to keep their active state as long as their fragmentation
114 * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
115 * active metaslab that exceeds this threshold will no longer keep its active
116 * status allowing better metaslabs to be selected.
118 int zfs_metaslab_fragmentation_threshold
= 70;
121 * When set will load all metaslabs when pool is first opened.
123 int metaslab_debug_load
= 0;
126 * When set will prevent metaslabs from being unloaded.
128 int metaslab_debug_unload
= 0;
131 * Minimum size which forces the dynamic allocator to change
132 * it's allocation strategy. Once the space map cannot satisfy
133 * an allocation of this size then it switches to using more
134 * aggressive strategy (i.e search by size rather than offset).
136 uint64_t metaslab_df_alloc_threshold
= SPA_OLD_MAXBLOCKSIZE
;
139 * The minimum free space, in percent, which must be available
140 * in a space map to continue allocations in a first-fit fashion.
141 * Once the space map's free space drops below this level we dynamically
142 * switch to using best-fit allocations.
144 int metaslab_df_free_pct
= 4;
147 * Percentage of all cpus that can be used by the metaslab taskq.
149 int metaslab_load_pct
= 50;
152 * Determines how many txgs a metaslab may remain loaded without having any
153 * allocations from it. As long as a metaslab continues to be used we will
156 int metaslab_unload_delay
= TXG_SIZE
* 2;
159 * Max number of metaslabs per group to preload.
161 int metaslab_preload_limit
= SPA_DVAS_PER_BP
;
164 * Enable/disable preloading of metaslab.
166 int metaslab_preload_enabled
= B_TRUE
;
169 * Enable/disable fragmentation weighting on metaslabs.
171 int metaslab_fragmentation_factor_enabled
= B_TRUE
;
174 * Enable/disable lba weighting (i.e. outer tracks are given preference).
176 int metaslab_lba_weighting_enabled
= B_TRUE
;
179 * Enable/disable metaslab group biasing.
181 int metaslab_bias_enabled
= B_TRUE
;
185 * Enable/disable remapping of indirect DVAs to their concrete vdevs.
187 boolean_t zfs_remap_blkptr_enable
= B_TRUE
;
190 * Enable/disable segment-based metaslab selection.
192 int zfs_metaslab_segment_weight_enabled
= B_TRUE
;
195 * When using segment-based metaslab selection, we will continue
196 * allocating from the active metaslab until we have exhausted
197 * zfs_metaslab_switch_threshold of its buckets.
199 int zfs_metaslab_switch_threshold
= 2;
202 * Internal switch to enable/disable the metaslab allocation tracing
205 #ifdef _METASLAB_TRACING
206 boolean_t metaslab_trace_enabled
= B_TRUE
;
210 * Maximum entries that the metaslab allocation tracing facility will keep
211 * in a given list when running in non-debug mode. We limit the number
212 * of entries in non-debug mode to prevent us from using up too much memory.
213 * The limit should be sufficiently large that we don't expect any allocation
214 * to every exceed this value. In debug mode, the system will panic if this
215 * limit is ever reached allowing for further investigation.
217 #ifdef _METASLAB_TRACING
218 uint64_t metaslab_trace_max_entries
= 5000;
221 static uint64_t metaslab_weight(metaslab_t
*);
222 static void metaslab_set_fragmentation(metaslab_t
*);
223 static void metaslab_free_impl(vdev_t
*, uint64_t, uint64_t, boolean_t
);
224 static void metaslab_check_free_impl(vdev_t
*, uint64_t, uint64_t);
226 static void metaslab_passivate(metaslab_t
*msp
, uint64_t weight
);
227 static uint64_t metaslab_weight_from_range_tree(metaslab_t
*msp
);
228 #ifdef _METASLAB_TRACING
229 kmem_cache_t
*metaslab_alloc_trace_cache
;
233 * ==========================================================================
235 * ==========================================================================
238 metaslab_class_create(spa_t
*spa
, metaslab_ops_t
*ops
)
240 metaslab_class_t
*mc
;
242 mc
= kmem_zalloc(sizeof (metaslab_class_t
), KM_SLEEP
);
247 mutex_init(&mc
->mc_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
248 mc
->mc_alloc_slots
= kmem_zalloc(spa
->spa_alloc_count
*
249 sizeof (refcount_t
), KM_SLEEP
);
250 mc
->mc_alloc_max_slots
= kmem_zalloc(spa
->spa_alloc_count
*
251 sizeof (uint64_t), KM_SLEEP
);
252 for (int i
= 0; i
< spa
->spa_alloc_count
; i
++)
253 refcount_create_tracked(&mc
->mc_alloc_slots
[i
]);
259 metaslab_class_destroy(metaslab_class_t
*mc
)
261 ASSERT(mc
->mc_rotor
== NULL
);
262 ASSERT(mc
->mc_alloc
== 0);
263 ASSERT(mc
->mc_deferred
== 0);
264 ASSERT(mc
->mc_space
== 0);
265 ASSERT(mc
->mc_dspace
== 0);
267 for (int i
= 0; i
< mc
->mc_spa
->spa_alloc_count
; i
++)
268 refcount_destroy(&mc
->mc_alloc_slots
[i
]);
269 kmem_free(mc
->mc_alloc_slots
, mc
->mc_spa
->spa_alloc_count
*
270 sizeof (refcount_t
));
271 kmem_free(mc
->mc_alloc_max_slots
, mc
->mc_spa
->spa_alloc_count
*
273 mutex_destroy(&mc
->mc_lock
);
274 kmem_free(mc
, sizeof (metaslab_class_t
));
278 metaslab_class_validate(metaslab_class_t
*mc
)
280 metaslab_group_t
*mg
;
284 * Must hold one of the spa_config locks.
286 ASSERT(spa_config_held(mc
->mc_spa
, SCL_ALL
, RW_READER
) ||
287 spa_config_held(mc
->mc_spa
, SCL_ALL
, RW_WRITER
));
289 if ((mg
= mc
->mc_rotor
) == NULL
)
294 ASSERT(vd
->vdev_mg
!= NULL
);
295 ASSERT3P(vd
->vdev_top
, ==, vd
);
296 ASSERT3P(mg
->mg_class
, ==, mc
);
297 ASSERT3P(vd
->vdev_ops
, !=, &vdev_hole_ops
);
298 } while ((mg
= mg
->mg_next
) != mc
->mc_rotor
);
304 metaslab_class_space_update(metaslab_class_t
*mc
, int64_t alloc_delta
,
305 int64_t defer_delta
, int64_t space_delta
, int64_t dspace_delta
)
307 atomic_add_64(&mc
->mc_alloc
, alloc_delta
);
308 atomic_add_64(&mc
->mc_deferred
, defer_delta
);
309 atomic_add_64(&mc
->mc_space
, space_delta
);
310 atomic_add_64(&mc
->mc_dspace
, dspace_delta
);
314 metaslab_class_get_alloc(metaslab_class_t
*mc
)
316 return (mc
->mc_alloc
);
320 metaslab_class_get_deferred(metaslab_class_t
*mc
)
322 return (mc
->mc_deferred
);
326 metaslab_class_get_space(metaslab_class_t
*mc
)
328 return (mc
->mc_space
);
332 metaslab_class_get_dspace(metaslab_class_t
*mc
)
334 return (spa_deflate(mc
->mc_spa
) ? mc
->mc_dspace
: mc
->mc_space
);
338 metaslab_class_histogram_verify(metaslab_class_t
*mc
)
340 vdev_t
*rvd
= mc
->mc_spa
->spa_root_vdev
;
344 if ((zfs_flags
& ZFS_DEBUG_HISTOGRAM_VERIFY
) == 0)
347 mc_hist
= kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE
,
350 for (int c
= 0; c
< rvd
->vdev_children
; c
++) {
351 vdev_t
*tvd
= rvd
->vdev_child
[c
];
352 metaslab_group_t
*mg
= tvd
->vdev_mg
;
355 * Skip any holes, uninitialized top-levels, or
356 * vdevs that are not in this metalab class.
358 if (!vdev_is_concrete(tvd
) || tvd
->vdev_ms_shift
== 0 ||
359 mg
->mg_class
!= mc
) {
363 for (i
= 0; i
< RANGE_TREE_HISTOGRAM_SIZE
; i
++)
364 mc_hist
[i
] += mg
->mg_histogram
[i
];
367 for (i
= 0; i
< RANGE_TREE_HISTOGRAM_SIZE
; i
++)
368 VERIFY3U(mc_hist
[i
], ==, mc
->mc_histogram
[i
]);
370 kmem_free(mc_hist
, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE
);
374 * Calculate the metaslab class's fragmentation metric. The metric
375 * is weighted based on the space contribution of each metaslab group.
376 * The return value will be a number between 0 and 100 (inclusive), or
377 * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
378 * zfs_frag_table for more information about the metric.
381 metaslab_class_fragmentation(metaslab_class_t
*mc
)
383 vdev_t
*rvd
= mc
->mc_spa
->spa_root_vdev
;
384 uint64_t fragmentation
= 0;
386 spa_config_enter(mc
->mc_spa
, SCL_VDEV
, FTAG
, RW_READER
);
388 for (int c
= 0; c
< rvd
->vdev_children
; c
++) {
389 vdev_t
*tvd
= rvd
->vdev_child
[c
];
390 metaslab_group_t
*mg
= tvd
->vdev_mg
;
393 * Skip any holes, uninitialized top-levels,
394 * or vdevs that are not in this metalab class.
396 if (!vdev_is_concrete(tvd
) || tvd
->vdev_ms_shift
== 0 ||
397 mg
->mg_class
!= mc
) {
402 * If a metaslab group does not contain a fragmentation
403 * metric then just bail out.
405 if (mg
->mg_fragmentation
== ZFS_FRAG_INVALID
) {
406 spa_config_exit(mc
->mc_spa
, SCL_VDEV
, FTAG
);
407 return (ZFS_FRAG_INVALID
);
411 * Determine how much this metaslab_group is contributing
412 * to the overall pool fragmentation metric.
414 fragmentation
+= mg
->mg_fragmentation
*
415 metaslab_group_get_space(mg
);
417 fragmentation
/= metaslab_class_get_space(mc
);
419 ASSERT3U(fragmentation
, <=, 100);
420 spa_config_exit(mc
->mc_spa
, SCL_VDEV
, FTAG
);
421 return (fragmentation
);
425 * Calculate the amount of expandable space that is available in
426 * this metaslab class. If a device is expanded then its expandable
427 * space will be the amount of allocatable space that is currently not
428 * part of this metaslab class.
431 metaslab_class_expandable_space(metaslab_class_t
*mc
)
433 vdev_t
*rvd
= mc
->mc_spa
->spa_root_vdev
;
436 spa_config_enter(mc
->mc_spa
, SCL_VDEV
, FTAG
, RW_READER
);
437 for (int c
= 0; c
< rvd
->vdev_children
; c
++) {
438 vdev_t
*tvd
= rvd
->vdev_child
[c
];
439 metaslab_group_t
*mg
= tvd
->vdev_mg
;
441 if (!vdev_is_concrete(tvd
) || tvd
->vdev_ms_shift
== 0 ||
442 mg
->mg_class
!= mc
) {
447 * Calculate if we have enough space to add additional
448 * metaslabs. We report the expandable space in terms
449 * of the metaslab size since that's the unit of expansion.
451 space
+= P2ALIGN(tvd
->vdev_max_asize
- tvd
->vdev_asize
,
452 1ULL << tvd
->vdev_ms_shift
);
454 spa_config_exit(mc
->mc_spa
, SCL_VDEV
, FTAG
);
459 metaslab_compare(const void *x1
, const void *x2
)
461 const metaslab_t
*m1
= (const metaslab_t
*)x1
;
462 const metaslab_t
*m2
= (const metaslab_t
*)x2
;
466 if (m1
->ms_allocator
!= -1 && m1
->ms_primary
)
468 else if (m1
->ms_allocator
!= -1 && !m1
->ms_primary
)
470 if (m2
->ms_allocator
!= -1 && m2
->ms_primary
)
472 else if (m2
->ms_allocator
!= -1 && !m2
->ms_primary
)
476 * Sort inactive metaslabs first, then primaries, then secondaries. When
477 * selecting a metaslab to allocate from, an allocator first tries its
478 * primary, then secondary active metaslab. If it doesn't have active
479 * metaslabs, or can't allocate from them, it searches for an inactive
480 * metaslab to activate. If it can't find a suitable one, it will steal
481 * a primary or secondary metaslab from another allocator.
488 int cmp
= AVL_CMP(m2
->ms_weight
, m1
->ms_weight
);
492 IMPLY(AVL_CMP(m1
->ms_start
, m2
->ms_start
) == 0, m1
== m2
);
494 return (AVL_CMP(m1
->ms_start
, m2
->ms_start
));
498 * Verify that the space accounting on disk matches the in-core range_trees.
501 metaslab_verify_space(metaslab_t
*msp
, uint64_t txg
)
503 spa_t
*spa
= msp
->ms_group
->mg_vd
->vdev_spa
;
504 uint64_t allocated
= 0;
505 uint64_t sm_free_space
, msp_free_space
;
507 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
509 if ((zfs_flags
& ZFS_DEBUG_METASLAB_VERIFY
) == 0)
513 * We can only verify the metaslab space when we're called
514 * from syncing context with a loaded metaslab that has an allocated
515 * space map. Calling this in non-syncing context does not
516 * provide a consistent view of the metaslab since we're performing
517 * allocations in the future.
519 if (txg
!= spa_syncing_txg(spa
) || msp
->ms_sm
== NULL
||
523 sm_free_space
= msp
->ms_size
- space_map_allocated(msp
->ms_sm
) -
524 space_map_alloc_delta(msp
->ms_sm
);
527 * Account for future allocations since we would have already
528 * deducted that space from the ms_freetree.
530 for (int t
= 0; t
< TXG_CONCURRENT_STATES
; t
++) {
532 range_tree_space(msp
->ms_allocating
[(txg
+ t
) & TXG_MASK
]);
535 msp_free_space
= range_tree_space(msp
->ms_allocatable
) + allocated
+
536 msp
->ms_deferspace
+ range_tree_space(msp
->ms_freed
);
538 VERIFY3U(sm_free_space
, ==, msp_free_space
);
542 * ==========================================================================
544 * ==========================================================================
547 * Update the allocatable flag and the metaslab group's capacity.
548 * The allocatable flag is set to true if the capacity is below
549 * the zfs_mg_noalloc_threshold or has a fragmentation value that is
550 * greater than zfs_mg_fragmentation_threshold. If a metaslab group
551 * transitions from allocatable to non-allocatable or vice versa then the
552 * metaslab group's class is updated to reflect the transition.
555 metaslab_group_alloc_update(metaslab_group_t
*mg
)
557 vdev_t
*vd
= mg
->mg_vd
;
558 metaslab_class_t
*mc
= mg
->mg_class
;
559 vdev_stat_t
*vs
= &vd
->vdev_stat
;
560 boolean_t was_allocatable
;
561 boolean_t was_initialized
;
563 ASSERT(vd
== vd
->vdev_top
);
564 ASSERT3U(spa_config_held(mc
->mc_spa
, SCL_ALLOC
, RW_READER
), ==,
567 mutex_enter(&mg
->mg_lock
);
568 was_allocatable
= mg
->mg_allocatable
;
569 was_initialized
= mg
->mg_initialized
;
571 mg
->mg_free_capacity
= ((vs
->vs_space
- vs
->vs_alloc
) * 100) /
574 mutex_enter(&mc
->mc_lock
);
577 * If the metaslab group was just added then it won't
578 * have any space until we finish syncing out this txg.
579 * At that point we will consider it initialized and available
580 * for allocations. We also don't consider non-activated
581 * metaslab groups (e.g. vdevs that are in the middle of being removed)
582 * to be initialized, because they can't be used for allocation.
584 mg
->mg_initialized
= metaslab_group_initialized(mg
);
585 if (!was_initialized
&& mg
->mg_initialized
) {
587 } else if (was_initialized
&& !mg
->mg_initialized
) {
588 ASSERT3U(mc
->mc_groups
, >, 0);
591 if (mg
->mg_initialized
)
592 mg
->mg_no_free_space
= B_FALSE
;
595 * A metaslab group is considered allocatable if it has plenty
596 * of free space or is not heavily fragmented. We only take
597 * fragmentation into account if the metaslab group has a valid
598 * fragmentation metric (i.e. a value between 0 and 100).
600 mg
->mg_allocatable
= (mg
->mg_activation_count
> 0 &&
601 mg
->mg_free_capacity
> zfs_mg_noalloc_threshold
&&
602 (mg
->mg_fragmentation
== ZFS_FRAG_INVALID
||
603 mg
->mg_fragmentation
<= zfs_mg_fragmentation_threshold
));
606 * The mc_alloc_groups maintains a count of the number of
607 * groups in this metaslab class that are still above the
608 * zfs_mg_noalloc_threshold. This is used by the allocating
609 * threads to determine if they should avoid allocations to
610 * a given group. The allocator will avoid allocations to a group
611 * if that group has reached or is below the zfs_mg_noalloc_threshold
612 * and there are still other groups that are above the threshold.
613 * When a group transitions from allocatable to non-allocatable or
614 * vice versa we update the metaslab class to reflect that change.
615 * When the mc_alloc_groups value drops to 0 that means that all
616 * groups have reached the zfs_mg_noalloc_threshold making all groups
617 * eligible for allocations. This effectively means that all devices
618 * are balanced again.
620 if (was_allocatable
&& !mg
->mg_allocatable
)
621 mc
->mc_alloc_groups
--;
622 else if (!was_allocatable
&& mg
->mg_allocatable
)
623 mc
->mc_alloc_groups
++;
624 mutex_exit(&mc
->mc_lock
);
626 mutex_exit(&mg
->mg_lock
);
630 metaslab_group_create(metaslab_class_t
*mc
, vdev_t
*vd
, int allocators
)
632 metaslab_group_t
*mg
;
634 mg
= kmem_zalloc(sizeof (metaslab_group_t
), KM_SLEEP
);
635 mutex_init(&mg
->mg_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
636 mg
->mg_primaries
= kmem_zalloc(allocators
* sizeof (metaslab_t
*),
638 mg
->mg_secondaries
= kmem_zalloc(allocators
* sizeof (metaslab_t
*),
640 avl_create(&mg
->mg_metaslab_tree
, metaslab_compare
,
641 sizeof (metaslab_t
), offsetof(struct metaslab
, ms_group_node
));
644 mg
->mg_activation_count
= 0;
645 mg
->mg_initialized
= B_FALSE
;
646 mg
->mg_no_free_space
= B_TRUE
;
647 mg
->mg_allocators
= allocators
;
649 mg
->mg_alloc_queue_depth
= kmem_zalloc(allocators
* sizeof (refcount_t
),
651 mg
->mg_cur_max_alloc_queue_depth
= kmem_zalloc(allocators
*
652 sizeof (uint64_t), KM_SLEEP
);
653 for (int i
= 0; i
< allocators
; i
++) {
654 refcount_create_tracked(&mg
->mg_alloc_queue_depth
[i
]);
655 mg
->mg_cur_max_alloc_queue_depth
[i
] = 0;
658 mg
->mg_taskq
= taskq_create("metaslab_group_taskq", metaslab_load_pct
,
659 maxclsyspri
, 10, INT_MAX
, TASKQ_THREADS_CPU_PCT
| TASKQ_DYNAMIC
);
665 metaslab_group_destroy(metaslab_group_t
*mg
)
667 ASSERT(mg
->mg_prev
== NULL
);
668 ASSERT(mg
->mg_next
== NULL
);
670 * We may have gone below zero with the activation count
671 * either because we never activated in the first place or
672 * because we're done, and possibly removing the vdev.
674 ASSERT(mg
->mg_activation_count
<= 0);
676 taskq_destroy(mg
->mg_taskq
);
677 avl_destroy(&mg
->mg_metaslab_tree
);
678 kmem_free(mg
->mg_primaries
, mg
->mg_allocators
* sizeof (metaslab_t
*));
679 kmem_free(mg
->mg_secondaries
, mg
->mg_allocators
*
680 sizeof (metaslab_t
*));
681 mutex_destroy(&mg
->mg_lock
);
683 for (int i
= 0; i
< mg
->mg_allocators
; i
++) {
684 refcount_destroy(&mg
->mg_alloc_queue_depth
[i
]);
685 mg
->mg_cur_max_alloc_queue_depth
[i
] = 0;
687 kmem_free(mg
->mg_alloc_queue_depth
, mg
->mg_allocators
*
688 sizeof (refcount_t
));
689 kmem_free(mg
->mg_cur_max_alloc_queue_depth
, mg
->mg_allocators
*
692 kmem_free(mg
, sizeof (metaslab_group_t
));
696 metaslab_group_activate(metaslab_group_t
*mg
)
698 metaslab_class_t
*mc
= mg
->mg_class
;
699 metaslab_group_t
*mgprev
, *mgnext
;
701 ASSERT3U(spa_config_held(mc
->mc_spa
, SCL_ALLOC
, RW_WRITER
), !=, 0);
703 ASSERT(mc
->mc_rotor
!= mg
);
704 ASSERT(mg
->mg_prev
== NULL
);
705 ASSERT(mg
->mg_next
== NULL
);
706 ASSERT(mg
->mg_activation_count
<= 0);
708 if (++mg
->mg_activation_count
<= 0)
711 mg
->mg_aliquot
= metaslab_aliquot
* MAX(1, mg
->mg_vd
->vdev_children
);
712 metaslab_group_alloc_update(mg
);
714 if ((mgprev
= mc
->mc_rotor
) == NULL
) {
718 mgnext
= mgprev
->mg_next
;
719 mg
->mg_prev
= mgprev
;
720 mg
->mg_next
= mgnext
;
721 mgprev
->mg_next
= mg
;
722 mgnext
->mg_prev
= mg
;
728 * Passivate a metaslab group and remove it from the allocation rotor.
729 * Callers must hold both the SCL_ALLOC and SCL_ZIO lock prior to passivating
730 * a metaslab group. This function will momentarily drop spa_config_locks
731 * that are lower than the SCL_ALLOC lock (see comment below).
734 metaslab_group_passivate(metaslab_group_t
*mg
)
736 metaslab_class_t
*mc
= mg
->mg_class
;
737 spa_t
*spa
= mc
->mc_spa
;
738 metaslab_group_t
*mgprev
, *mgnext
;
739 int locks
= spa_config_held(spa
, SCL_ALL
, RW_WRITER
);
741 ASSERT3U(spa_config_held(spa
, SCL_ALLOC
| SCL_ZIO
, RW_WRITER
), ==,
742 (SCL_ALLOC
| SCL_ZIO
));
744 if (--mg
->mg_activation_count
!= 0) {
745 ASSERT(mc
->mc_rotor
!= mg
);
746 ASSERT(mg
->mg_prev
== NULL
);
747 ASSERT(mg
->mg_next
== NULL
);
748 ASSERT(mg
->mg_activation_count
< 0);
753 * The spa_config_lock is an array of rwlocks, ordered as
754 * follows (from highest to lowest):
755 * SCL_CONFIG > SCL_STATE > SCL_L2ARC > SCL_ALLOC >
756 * SCL_ZIO > SCL_FREE > SCL_VDEV
757 * (For more information about the spa_config_lock see spa_misc.c)
758 * The higher the lock, the broader its coverage. When we passivate
759 * a metaslab group, we must hold both the SCL_ALLOC and the SCL_ZIO
760 * config locks. However, the metaslab group's taskq might be trying
761 * to preload metaslabs so we must drop the SCL_ZIO lock and any
762 * lower locks to allow the I/O to complete. At a minimum,
763 * we continue to hold the SCL_ALLOC lock, which prevents any future
764 * allocations from taking place and any changes to the vdev tree.
766 spa_config_exit(spa
, locks
& ~(SCL_ZIO
- 1), spa
);
767 taskq_wait_outstanding(mg
->mg_taskq
, 0);
768 spa_config_enter(spa
, locks
& ~(SCL_ZIO
- 1), spa
, RW_WRITER
);
769 metaslab_group_alloc_update(mg
);
770 for (int i
= 0; i
< mg
->mg_allocators
; i
++) {
771 metaslab_t
*msp
= mg
->mg_primaries
[i
];
773 mutex_enter(&msp
->ms_lock
);
774 metaslab_passivate(msp
,
775 metaslab_weight_from_range_tree(msp
));
776 mutex_exit(&msp
->ms_lock
);
778 msp
= mg
->mg_secondaries
[i
];
780 mutex_enter(&msp
->ms_lock
);
781 metaslab_passivate(msp
,
782 metaslab_weight_from_range_tree(msp
));
783 mutex_exit(&msp
->ms_lock
);
787 mgprev
= mg
->mg_prev
;
788 mgnext
= mg
->mg_next
;
793 mc
->mc_rotor
= mgnext
;
794 mgprev
->mg_next
= mgnext
;
795 mgnext
->mg_prev
= mgprev
;
803 metaslab_group_initialized(metaslab_group_t
*mg
)
805 vdev_t
*vd
= mg
->mg_vd
;
806 vdev_stat_t
*vs
= &vd
->vdev_stat
;
808 return (vs
->vs_space
!= 0 && mg
->mg_activation_count
> 0);
812 metaslab_group_get_space(metaslab_group_t
*mg
)
814 return ((1ULL << mg
->mg_vd
->vdev_ms_shift
) * mg
->mg_vd
->vdev_ms_count
);
818 metaslab_group_histogram_verify(metaslab_group_t
*mg
)
821 vdev_t
*vd
= mg
->mg_vd
;
822 uint64_t ashift
= vd
->vdev_ashift
;
825 if ((zfs_flags
& ZFS_DEBUG_HISTOGRAM_VERIFY
) == 0)
828 mg_hist
= kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE
,
831 ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE
, >=,
832 SPACE_MAP_HISTOGRAM_SIZE
+ ashift
);
834 for (int m
= 0; m
< vd
->vdev_ms_count
; m
++) {
835 metaslab_t
*msp
= vd
->vdev_ms
[m
];
837 if (msp
->ms_sm
== NULL
)
840 for (i
= 0; i
< SPACE_MAP_HISTOGRAM_SIZE
; i
++)
841 mg_hist
[i
+ ashift
] +=
842 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
845 for (i
= 0; i
< RANGE_TREE_HISTOGRAM_SIZE
; i
++)
846 VERIFY3U(mg_hist
[i
], ==, mg
->mg_histogram
[i
]);
848 kmem_free(mg_hist
, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE
);
852 metaslab_group_histogram_add(metaslab_group_t
*mg
, metaslab_t
*msp
)
854 metaslab_class_t
*mc
= mg
->mg_class
;
855 uint64_t ashift
= mg
->mg_vd
->vdev_ashift
;
857 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
858 if (msp
->ms_sm
== NULL
)
861 mutex_enter(&mg
->mg_lock
);
862 for (int i
= 0; i
< SPACE_MAP_HISTOGRAM_SIZE
; i
++) {
863 mg
->mg_histogram
[i
+ ashift
] +=
864 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
865 mc
->mc_histogram
[i
+ ashift
] +=
866 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
868 mutex_exit(&mg
->mg_lock
);
872 metaslab_group_histogram_remove(metaslab_group_t
*mg
, metaslab_t
*msp
)
874 metaslab_class_t
*mc
= mg
->mg_class
;
875 uint64_t ashift
= mg
->mg_vd
->vdev_ashift
;
877 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
878 if (msp
->ms_sm
== NULL
)
881 mutex_enter(&mg
->mg_lock
);
882 for (int i
= 0; i
< SPACE_MAP_HISTOGRAM_SIZE
; i
++) {
883 ASSERT3U(mg
->mg_histogram
[i
+ ashift
], >=,
884 msp
->ms_sm
->sm_phys
->smp_histogram
[i
]);
885 ASSERT3U(mc
->mc_histogram
[i
+ ashift
], >=,
886 msp
->ms_sm
->sm_phys
->smp_histogram
[i
]);
888 mg
->mg_histogram
[i
+ ashift
] -=
889 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
890 mc
->mc_histogram
[i
+ ashift
] -=
891 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
893 mutex_exit(&mg
->mg_lock
);
897 metaslab_group_add(metaslab_group_t
*mg
, metaslab_t
*msp
)
899 ASSERT(msp
->ms_group
== NULL
);
900 mutex_enter(&mg
->mg_lock
);
903 avl_add(&mg
->mg_metaslab_tree
, msp
);
904 mutex_exit(&mg
->mg_lock
);
906 mutex_enter(&msp
->ms_lock
);
907 metaslab_group_histogram_add(mg
, msp
);
908 mutex_exit(&msp
->ms_lock
);
912 metaslab_group_remove(metaslab_group_t
*mg
, metaslab_t
*msp
)
914 mutex_enter(&msp
->ms_lock
);
915 metaslab_group_histogram_remove(mg
, msp
);
916 mutex_exit(&msp
->ms_lock
);
918 mutex_enter(&mg
->mg_lock
);
919 ASSERT(msp
->ms_group
== mg
);
920 avl_remove(&mg
->mg_metaslab_tree
, msp
);
921 msp
->ms_group
= NULL
;
922 mutex_exit(&mg
->mg_lock
);
926 metaslab_group_sort_impl(metaslab_group_t
*mg
, metaslab_t
*msp
, uint64_t weight
)
928 ASSERT(MUTEX_HELD(&mg
->mg_lock
));
929 ASSERT(msp
->ms_group
== mg
);
930 avl_remove(&mg
->mg_metaslab_tree
, msp
);
931 msp
->ms_weight
= weight
;
932 avl_add(&mg
->mg_metaslab_tree
, msp
);
937 metaslab_group_sort(metaslab_group_t
*mg
, metaslab_t
*msp
, uint64_t weight
)
940 * Although in principle the weight can be any value, in
941 * practice we do not use values in the range [1, 511].
943 ASSERT(weight
>= SPA_MINBLOCKSIZE
|| weight
== 0);
944 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
946 mutex_enter(&mg
->mg_lock
);
947 metaslab_group_sort_impl(mg
, msp
, weight
);
948 mutex_exit(&mg
->mg_lock
);
952 * Calculate the fragmentation for a given metaslab group. We can use
953 * a simple average here since all metaslabs within the group must have
954 * the same size. The return value will be a value between 0 and 100
955 * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
956 * group have a fragmentation metric.
959 metaslab_group_fragmentation(metaslab_group_t
*mg
)
961 vdev_t
*vd
= mg
->mg_vd
;
962 uint64_t fragmentation
= 0;
963 uint64_t valid_ms
= 0;
965 for (int m
= 0; m
< vd
->vdev_ms_count
; m
++) {
966 metaslab_t
*msp
= vd
->vdev_ms
[m
];
968 if (msp
->ms_fragmentation
== ZFS_FRAG_INVALID
)
972 fragmentation
+= msp
->ms_fragmentation
;
975 if (valid_ms
<= vd
->vdev_ms_count
/ 2)
976 return (ZFS_FRAG_INVALID
);
978 fragmentation
/= valid_ms
;
979 ASSERT3U(fragmentation
, <=, 100);
980 return (fragmentation
);
984 * Determine if a given metaslab group should skip allocations. A metaslab
985 * group should avoid allocations if its free capacity is less than the
986 * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
987 * zfs_mg_fragmentation_threshold and there is at least one metaslab group
988 * that can still handle allocations. If the allocation throttle is enabled
989 * then we skip allocations to devices that have reached their maximum
990 * allocation queue depth unless the selected metaslab group is the only
991 * eligible group remaining.
994 metaslab_group_allocatable(metaslab_group_t
*mg
, metaslab_group_t
*rotor
,
995 uint64_t psize
, int allocator
)
997 spa_t
*spa
= mg
->mg_vd
->vdev_spa
;
998 metaslab_class_t
*mc
= mg
->mg_class
;
1001 * We can only consider skipping this metaslab group if it's
1002 * in the normal metaslab class and there are other metaslab
1003 * groups to select from. Otherwise, we always consider it eligible
1006 if (mc
!= spa_normal_class(spa
) || mc
->mc_groups
<= 1)
1010 * If the metaslab group's mg_allocatable flag is set (see comments
1011 * in metaslab_group_alloc_update() for more information) and
1012 * the allocation throttle is disabled then allow allocations to this
1013 * device. However, if the allocation throttle is enabled then
1014 * check if we have reached our allocation limit (mg_alloc_queue_depth)
1015 * to determine if we should allow allocations to this metaslab group.
1016 * If all metaslab groups are no longer considered allocatable
1017 * (mc_alloc_groups == 0) or we're trying to allocate the smallest
1018 * gang block size then we allow allocations on this metaslab group
1019 * regardless of the mg_allocatable or throttle settings.
1021 if (mg
->mg_allocatable
) {
1022 metaslab_group_t
*mgp
;
1024 uint64_t qmax
= mg
->mg_cur_max_alloc_queue_depth
[allocator
];
1026 if (!mc
->mc_alloc_throttle_enabled
)
1030 * If this metaslab group does not have any free space, then
1031 * there is no point in looking further.
1033 if (mg
->mg_no_free_space
)
1036 qdepth
= refcount_count(&mg
->mg_alloc_queue_depth
[allocator
]);
1039 * If this metaslab group is below its qmax or it's
1040 * the only allocatable metasable group, then attempt
1041 * to allocate from it.
1043 if (qdepth
< qmax
|| mc
->mc_alloc_groups
== 1)
1045 ASSERT3U(mc
->mc_alloc_groups
, >, 1);
1048 * Since this metaslab group is at or over its qmax, we
1049 * need to determine if there are metaslab groups after this
1050 * one that might be able to handle this allocation. This is
1051 * racy since we can't hold the locks for all metaslab
1052 * groups at the same time when we make this check.
1054 for (mgp
= mg
->mg_next
; mgp
!= rotor
; mgp
= mgp
->mg_next
) {
1055 qmax
= mgp
->mg_cur_max_alloc_queue_depth
[allocator
];
1057 qdepth
= refcount_count(
1058 &mgp
->mg_alloc_queue_depth
[allocator
]);
1061 * If there is another metaslab group that
1062 * might be able to handle the allocation, then
1063 * we return false so that we skip this group.
1065 if (qdepth
< qmax
&& !mgp
->mg_no_free_space
)
1070 * We didn't find another group to handle the allocation
1071 * so we can't skip this metaslab group even though
1072 * we are at or over our qmax.
1076 } else if (mc
->mc_alloc_groups
== 0 || psize
== SPA_MINBLOCKSIZE
) {
1083 * ==========================================================================
1084 * Range tree callbacks
1085 * ==========================================================================
1089 * Comparison function for the private size-ordered tree. Tree is sorted
1090 * by size, larger sizes at the end of the tree.
1093 metaslab_rangesize_compare(const void *x1
, const void *x2
)
1095 const range_seg_t
*r1
= x1
;
1096 const range_seg_t
*r2
= x2
;
1097 uint64_t rs_size1
= r1
->rs_end
- r1
->rs_start
;
1098 uint64_t rs_size2
= r2
->rs_end
- r2
->rs_start
;
1100 int cmp
= AVL_CMP(rs_size1
, rs_size2
);
1104 return (AVL_CMP(r1
->rs_start
, r2
->rs_start
));
1108 * ==========================================================================
1109 * Common allocator routines
1110 * ==========================================================================
1114 * Return the maximum contiguous segment within the metaslab.
1117 metaslab_block_maxsize(metaslab_t
*msp
)
1119 avl_tree_t
*t
= &msp
->ms_allocatable_by_size
;
1122 if (t
== NULL
|| (rs
= avl_last(t
)) == NULL
)
1125 return (rs
->rs_end
- rs
->rs_start
);
1128 static range_seg_t
*
1129 metaslab_block_find(avl_tree_t
*t
, uint64_t start
, uint64_t size
)
1131 range_seg_t
*rs
, rsearch
;
1134 rsearch
.rs_start
= start
;
1135 rsearch
.rs_end
= start
+ size
;
1137 rs
= avl_find(t
, &rsearch
, &where
);
1139 rs
= avl_nearest(t
, where
, AVL_AFTER
);
1145 #if defined(WITH_FF_BLOCK_ALLOCATOR) || \
1146 defined(WITH_DF_BLOCK_ALLOCATOR) || \
1147 defined(WITH_CF_BLOCK_ALLOCATOR)
1149 * This is a helper function that can be used by the allocator to find
1150 * a suitable block to allocate. This will search the specified AVL
1151 * tree looking for a block that matches the specified criteria.
1154 metaslab_block_picker(avl_tree_t
*t
, uint64_t *cursor
, uint64_t size
,
1157 range_seg_t
*rs
= metaslab_block_find(t
, *cursor
, size
);
1159 while (rs
!= NULL
) {
1160 uint64_t offset
= P2ROUNDUP(rs
->rs_start
, align
);
1162 if (offset
+ size
<= rs
->rs_end
) {
1163 *cursor
= offset
+ size
;
1166 rs
= AVL_NEXT(t
, rs
);
1170 * If we know we've searched the whole map (*cursor == 0), give up.
1171 * Otherwise, reset the cursor to the beginning and try again.
1177 return (metaslab_block_picker(t
, cursor
, size
, align
));
1179 #endif /* WITH_FF/DF/CF_BLOCK_ALLOCATOR */
1181 #if defined(WITH_FF_BLOCK_ALLOCATOR)
1183 * ==========================================================================
1184 * The first-fit block allocator
1185 * ==========================================================================
1188 metaslab_ff_alloc(metaslab_t
*msp
, uint64_t size
)
1191 * Find the largest power of 2 block size that evenly divides the
1192 * requested size. This is used to try to allocate blocks with similar
1193 * alignment from the same area of the metaslab (i.e. same cursor
1194 * bucket) but it does not guarantee that other allocations sizes
1195 * may exist in the same region.
1197 uint64_t align
= size
& -size
;
1198 uint64_t *cursor
= &msp
->ms_lbas
[highbit64(align
) - 1];
1199 avl_tree_t
*t
= &msp
->ms_allocatable
->rt_root
;
1201 return (metaslab_block_picker(t
, cursor
, size
, align
));
1204 static metaslab_ops_t metaslab_ff_ops
= {
1208 metaslab_ops_t
*zfs_metaslab_ops
= &metaslab_ff_ops
;
1209 #endif /* WITH_FF_BLOCK_ALLOCATOR */
1211 #if defined(WITH_DF_BLOCK_ALLOCATOR)
1213 * ==========================================================================
1214 * Dynamic block allocator -
1215 * Uses the first fit allocation scheme until space get low and then
1216 * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
1217 * and metaslab_df_free_pct to determine when to switch the allocation scheme.
1218 * ==========================================================================
1221 metaslab_df_alloc(metaslab_t
*msp
, uint64_t size
)
1224 * Find the largest power of 2 block size that evenly divides the
1225 * requested size. This is used to try to allocate blocks with similar
1226 * alignment from the same area of the metaslab (i.e. same cursor
1227 * bucket) but it does not guarantee that other allocations sizes
1228 * may exist in the same region.
1230 uint64_t align
= size
& -size
;
1231 uint64_t *cursor
= &msp
->ms_lbas
[highbit64(align
) - 1];
1232 range_tree_t
*rt
= msp
->ms_allocatable
;
1233 avl_tree_t
*t
= &rt
->rt_root
;
1234 uint64_t max_size
= metaslab_block_maxsize(msp
);
1235 int free_pct
= range_tree_space(rt
) * 100 / msp
->ms_size
;
1237 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1238 ASSERT3U(avl_numnodes(t
), ==,
1239 avl_numnodes(&msp
->ms_allocatable_by_size
));
1241 if (max_size
< size
)
1245 * If we're running low on space switch to using the size
1246 * sorted AVL tree (best-fit).
1248 if (max_size
< metaslab_df_alloc_threshold
||
1249 free_pct
< metaslab_df_free_pct
) {
1250 t
= &msp
->ms_allocatable_by_size
;
1254 return (metaslab_block_picker(t
, cursor
, size
, 1ULL));
1257 static metaslab_ops_t metaslab_df_ops
= {
1261 metaslab_ops_t
*zfs_metaslab_ops
= &metaslab_df_ops
;
1262 #endif /* WITH_DF_BLOCK_ALLOCATOR */
1264 #if defined(WITH_CF_BLOCK_ALLOCATOR)
1266 * ==========================================================================
1267 * Cursor fit block allocator -
1268 * Select the largest region in the metaslab, set the cursor to the beginning
1269 * of the range and the cursor_end to the end of the range. As allocations
1270 * are made advance the cursor. Continue allocating from the cursor until
1271 * the range is exhausted and then find a new range.
1272 * ==========================================================================
1275 metaslab_cf_alloc(metaslab_t
*msp
, uint64_t size
)
1277 range_tree_t
*rt
= msp
->ms_allocatable
;
1278 avl_tree_t
*t
= &msp
->ms_allocatable_by_size
;
1279 uint64_t *cursor
= &msp
->ms_lbas
[0];
1280 uint64_t *cursor_end
= &msp
->ms_lbas
[1];
1281 uint64_t offset
= 0;
1283 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1284 ASSERT3U(avl_numnodes(t
), ==, avl_numnodes(&rt
->rt_root
));
1286 ASSERT3U(*cursor_end
, >=, *cursor
);
1288 if ((*cursor
+ size
) > *cursor_end
) {
1291 rs
= avl_last(&msp
->ms_allocatable_by_size
);
1292 if (rs
== NULL
|| (rs
->rs_end
- rs
->rs_start
) < size
)
1295 *cursor
= rs
->rs_start
;
1296 *cursor_end
= rs
->rs_end
;
1305 static metaslab_ops_t metaslab_cf_ops
= {
1309 metaslab_ops_t
*zfs_metaslab_ops
= &metaslab_cf_ops
;
1310 #endif /* WITH_CF_BLOCK_ALLOCATOR */
1312 #if defined(WITH_NDF_BLOCK_ALLOCATOR)
1314 * ==========================================================================
1315 * New dynamic fit allocator -
1316 * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1317 * contiguous blocks. If no region is found then just use the largest segment
1319 * ==========================================================================
1323 * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1324 * to request from the allocator.
1326 uint64_t metaslab_ndf_clump_shift
= 4;
1329 metaslab_ndf_alloc(metaslab_t
*msp
, uint64_t size
)
1331 avl_tree_t
*t
= &msp
->ms_allocatable
->rt_root
;
1333 range_seg_t
*rs
, rsearch
;
1334 uint64_t hbit
= highbit64(size
);
1335 uint64_t *cursor
= &msp
->ms_lbas
[hbit
- 1];
1336 uint64_t max_size
= metaslab_block_maxsize(msp
);
1338 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1339 ASSERT3U(avl_numnodes(t
), ==,
1340 avl_numnodes(&msp
->ms_allocatable_by_size
));
1342 if (max_size
< size
)
1345 rsearch
.rs_start
= *cursor
;
1346 rsearch
.rs_end
= *cursor
+ size
;
1348 rs
= avl_find(t
, &rsearch
, &where
);
1349 if (rs
== NULL
|| (rs
->rs_end
- rs
->rs_start
) < size
) {
1350 t
= &msp
->ms_allocatable_by_size
;
1352 rsearch
.rs_start
= 0;
1353 rsearch
.rs_end
= MIN(max_size
,
1354 1ULL << (hbit
+ metaslab_ndf_clump_shift
));
1355 rs
= avl_find(t
, &rsearch
, &where
);
1357 rs
= avl_nearest(t
, where
, AVL_AFTER
);
1361 if ((rs
->rs_end
- rs
->rs_start
) >= size
) {
1362 *cursor
= rs
->rs_start
+ size
;
1363 return (rs
->rs_start
);
1368 static metaslab_ops_t metaslab_ndf_ops
= {
1372 metaslab_ops_t
*zfs_metaslab_ops
= &metaslab_ndf_ops
;
1373 #endif /* WITH_NDF_BLOCK_ALLOCATOR */
1377 * ==========================================================================
1379 * ==========================================================================
1383 * Wait for any in-progress metaslab loads to complete.
1386 metaslab_load_wait(metaslab_t
*msp
)
1388 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1390 while (msp
->ms_loading
) {
1391 ASSERT(!msp
->ms_loaded
);
1392 cv_wait(&msp
->ms_load_cv
, &msp
->ms_lock
);
1397 metaslab_load(metaslab_t
*msp
)
1400 boolean_t success
= B_FALSE
;
1402 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1403 ASSERT(!msp
->ms_loaded
);
1404 ASSERT(!msp
->ms_loading
);
1406 msp
->ms_loading
= B_TRUE
;
1408 * Nobody else can manipulate a loading metaslab, so it's now safe
1409 * to drop the lock. This way we don't have to hold the lock while
1410 * reading the spacemap from disk.
1412 mutex_exit(&msp
->ms_lock
);
1415 * If the space map has not been allocated yet, then treat
1416 * all the space in the metaslab as free and add it to ms_allocatable.
1418 if (msp
->ms_sm
!= NULL
) {
1419 error
= space_map_load(msp
->ms_sm
, msp
->ms_allocatable
,
1422 range_tree_add(msp
->ms_allocatable
,
1423 msp
->ms_start
, msp
->ms_size
);
1426 success
= (error
== 0);
1428 mutex_enter(&msp
->ms_lock
);
1429 msp
->ms_loading
= B_FALSE
;
1432 ASSERT3P(msp
->ms_group
, !=, NULL
);
1433 msp
->ms_loaded
= B_TRUE
;
1436 * If the metaslab already has a spacemap, then we need to
1437 * remove all segments from the defer tree; otherwise, the
1438 * metaslab is completely empty and we can skip this.
1440 if (msp
->ms_sm
!= NULL
) {
1441 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
1442 range_tree_walk(msp
->ms_defer
[t
],
1443 range_tree_remove
, msp
->ms_allocatable
);
1446 msp
->ms_max_size
= metaslab_block_maxsize(msp
);
1448 cv_broadcast(&msp
->ms_load_cv
);
1453 metaslab_unload(metaslab_t
*msp
)
1455 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1456 range_tree_vacate(msp
->ms_allocatable
, NULL
, NULL
);
1457 msp
->ms_loaded
= B_FALSE
;
1458 msp
->ms_weight
&= ~METASLAB_ACTIVE_MASK
;
1459 msp
->ms_max_size
= 0;
1463 metaslab_init(metaslab_group_t
*mg
, uint64_t id
, uint64_t object
, uint64_t txg
,
1466 vdev_t
*vd
= mg
->mg_vd
;
1467 objset_t
*mos
= vd
->vdev_spa
->spa_meta_objset
;
1471 ms
= kmem_zalloc(sizeof (metaslab_t
), KM_SLEEP
);
1472 mutex_init(&ms
->ms_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
1473 mutex_init(&ms
->ms_sync_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
1474 cv_init(&ms
->ms_load_cv
, NULL
, CV_DEFAULT
, NULL
);
1476 ms
->ms_start
= id
<< vd
->vdev_ms_shift
;
1477 ms
->ms_size
= 1ULL << vd
->vdev_ms_shift
;
1478 ms
->ms_allocator
= -1;
1479 ms
->ms_new
= B_TRUE
;
1482 * We only open space map objects that already exist. All others
1483 * will be opened when we finally allocate an object for it.
1486 error
= space_map_open(&ms
->ms_sm
, mos
, object
, ms
->ms_start
,
1487 ms
->ms_size
, vd
->vdev_ashift
);
1490 kmem_free(ms
, sizeof (metaslab_t
));
1494 ASSERT(ms
->ms_sm
!= NULL
);
1498 * We create the main range tree here, but we don't create the
1499 * other range trees until metaslab_sync_done(). This serves
1500 * two purposes: it allows metaslab_sync_done() to detect the
1501 * addition of new space; and for debugging, it ensures that we'd
1502 * data fault on any attempt to use this metaslab before it's ready.
1504 ms
->ms_allocatable
= range_tree_create_impl(&rt_avl_ops
,
1505 &ms
->ms_allocatable_by_size
, metaslab_rangesize_compare
, 0);
1506 metaslab_group_add(mg
, ms
);
1508 metaslab_set_fragmentation(ms
);
1511 * If we're opening an existing pool (txg == 0) or creating
1512 * a new one (txg == TXG_INITIAL), all space is available now.
1513 * If we're adding space to an existing pool, the new space
1514 * does not become available until after this txg has synced.
1515 * The metaslab's weight will also be initialized when we sync
1516 * out this txg. This ensures that we don't attempt to allocate
1517 * from it before we have initialized it completely.
1519 if (txg
<= TXG_INITIAL
)
1520 metaslab_sync_done(ms
, 0);
1523 * If metaslab_debug_load is set and we're initializing a metaslab
1524 * that has an allocated space map object then load the its space
1525 * map so that can verify frees.
1527 if (metaslab_debug_load
&& ms
->ms_sm
!= NULL
) {
1528 mutex_enter(&ms
->ms_lock
);
1529 VERIFY0(metaslab_load(ms
));
1530 mutex_exit(&ms
->ms_lock
);
1534 vdev_dirty(vd
, 0, NULL
, txg
);
1535 vdev_dirty(vd
, VDD_METASLAB
, ms
, txg
);
1544 metaslab_fini(metaslab_t
*msp
)
1546 metaslab_group_t
*mg
= msp
->ms_group
;
1548 metaslab_group_remove(mg
, msp
);
1550 mutex_enter(&msp
->ms_lock
);
1551 VERIFY(msp
->ms_group
== NULL
);
1552 vdev_space_update(mg
->mg_vd
, -space_map_allocated(msp
->ms_sm
),
1554 space_map_close(msp
->ms_sm
);
1556 metaslab_unload(msp
);
1557 range_tree_destroy(msp
->ms_allocatable
);
1558 range_tree_destroy(msp
->ms_freeing
);
1559 range_tree_destroy(msp
->ms_freed
);
1561 for (int t
= 0; t
< TXG_SIZE
; t
++) {
1562 range_tree_destroy(msp
->ms_allocating
[t
]);
1565 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
1566 range_tree_destroy(msp
->ms_defer
[t
]);
1568 ASSERT0(msp
->ms_deferspace
);
1570 range_tree_destroy(msp
->ms_checkpointing
);
1572 mutex_exit(&msp
->ms_lock
);
1573 cv_destroy(&msp
->ms_load_cv
);
1574 mutex_destroy(&msp
->ms_lock
);
1575 mutex_destroy(&msp
->ms_sync_lock
);
1576 ASSERT3U(msp
->ms_allocator
, ==, -1);
1578 kmem_free(msp
, sizeof (metaslab_t
));
1581 #define FRAGMENTATION_TABLE_SIZE 17
1584 * This table defines a segment size based fragmentation metric that will
1585 * allow each metaslab to derive its own fragmentation value. This is done
1586 * by calculating the space in each bucket of the spacemap histogram and
1587 * multiplying that by the fragmetation metric in this table. Doing
1588 * this for all buckets and dividing it by the total amount of free
1589 * space in this metaslab (i.e. the total free space in all buckets) gives
1590 * us the fragmentation metric. This means that a high fragmentation metric
1591 * equates to most of the free space being comprised of small segments.
1592 * Conversely, if the metric is low, then most of the free space is in
1593 * large segments. A 10% change in fragmentation equates to approximately
1594 * double the number of segments.
1596 * This table defines 0% fragmented space using 16MB segments. Testing has
1597 * shown that segments that are greater than or equal to 16MB do not suffer
1598 * from drastic performance problems. Using this value, we derive the rest
1599 * of the table. Since the fragmentation value is never stored on disk, it
1600 * is possible to change these calculations in the future.
1602 int zfs_frag_table
[FRAGMENTATION_TABLE_SIZE
] = {
1622 * Calclate the metaslab's fragmentation metric. A return value
1623 * of ZFS_FRAG_INVALID means that the metaslab has not been upgraded and does
1624 * not support this metric. Otherwise, the return value should be in the
1628 metaslab_set_fragmentation(metaslab_t
*msp
)
1630 spa_t
*spa
= msp
->ms_group
->mg_vd
->vdev_spa
;
1631 uint64_t fragmentation
= 0;
1633 boolean_t feature_enabled
= spa_feature_is_enabled(spa
,
1634 SPA_FEATURE_SPACEMAP_HISTOGRAM
);
1636 if (!feature_enabled
) {
1637 msp
->ms_fragmentation
= ZFS_FRAG_INVALID
;
1642 * A null space map means that the entire metaslab is free
1643 * and thus is not fragmented.
1645 if (msp
->ms_sm
== NULL
) {
1646 msp
->ms_fragmentation
= 0;
1651 * If this metaslab's space map has not been upgraded, flag it
1652 * so that we upgrade next time we encounter it.
1654 if (msp
->ms_sm
->sm_dbuf
->db_size
!= sizeof (space_map_phys_t
)) {
1655 uint64_t txg
= spa_syncing_txg(spa
);
1656 vdev_t
*vd
= msp
->ms_group
->mg_vd
;
1659 * If we've reached the final dirty txg, then we must
1660 * be shutting down the pool. We don't want to dirty
1661 * any data past this point so skip setting the condense
1662 * flag. We can retry this action the next time the pool
1665 if (spa_writeable(spa
) && txg
< spa_final_dirty_txg(spa
)) {
1666 msp
->ms_condense_wanted
= B_TRUE
;
1667 vdev_dirty(vd
, VDD_METASLAB
, msp
, txg
+ 1);
1668 zfs_dbgmsg("txg %llu, requesting force condense: "
1669 "ms_id %llu, vdev_id %llu", txg
, msp
->ms_id
,
1672 msp
->ms_fragmentation
= ZFS_FRAG_INVALID
;
1676 for (int i
= 0; i
< SPACE_MAP_HISTOGRAM_SIZE
; i
++) {
1678 uint8_t shift
= msp
->ms_sm
->sm_shift
;
1680 int idx
= MIN(shift
- SPA_MINBLOCKSHIFT
+ i
,
1681 FRAGMENTATION_TABLE_SIZE
- 1);
1683 if (msp
->ms_sm
->sm_phys
->smp_histogram
[i
] == 0)
1686 space
= msp
->ms_sm
->sm_phys
->smp_histogram
[i
] << (i
+ shift
);
1689 ASSERT3U(idx
, <, FRAGMENTATION_TABLE_SIZE
);
1690 fragmentation
+= space
* zfs_frag_table
[idx
];
1694 fragmentation
/= total
;
1695 ASSERT3U(fragmentation
, <=, 100);
1697 msp
->ms_fragmentation
= fragmentation
;
1701 * Compute a weight -- a selection preference value -- for the given metaslab.
1702 * This is based on the amount of free space, the level of fragmentation,
1703 * the LBA range, and whether the metaslab is loaded.
1706 metaslab_space_weight(metaslab_t
*msp
)
1708 metaslab_group_t
*mg
= msp
->ms_group
;
1709 vdev_t
*vd
= mg
->mg_vd
;
1710 uint64_t weight
, space
;
1712 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1713 ASSERT(!vd
->vdev_removing
);
1716 * The baseline weight is the metaslab's free space.
1718 space
= msp
->ms_size
- space_map_allocated(msp
->ms_sm
);
1720 if (metaslab_fragmentation_factor_enabled
&&
1721 msp
->ms_fragmentation
!= ZFS_FRAG_INVALID
) {
1723 * Use the fragmentation information to inversely scale
1724 * down the baseline weight. We need to ensure that we
1725 * don't exclude this metaslab completely when it's 100%
1726 * fragmented. To avoid this we reduce the fragmented value
1729 space
= (space
* (100 - (msp
->ms_fragmentation
- 1))) / 100;
1732 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
1733 * this metaslab again. The fragmentation metric may have
1734 * decreased the space to something smaller than
1735 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
1736 * so that we can consume any remaining space.
1738 if (space
> 0 && space
< SPA_MINBLOCKSIZE
)
1739 space
= SPA_MINBLOCKSIZE
;
1744 * Modern disks have uniform bit density and constant angular velocity.
1745 * Therefore, the outer recording zones are faster (higher bandwidth)
1746 * than the inner zones by the ratio of outer to inner track diameter,
1747 * which is typically around 2:1. We account for this by assigning
1748 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
1749 * In effect, this means that we'll select the metaslab with the most
1750 * free bandwidth rather than simply the one with the most free space.
1752 if (!vd
->vdev_nonrot
&& metaslab_lba_weighting_enabled
) {
1753 weight
= 2 * weight
- (msp
->ms_id
* weight
) / vd
->vdev_ms_count
;
1754 ASSERT(weight
>= space
&& weight
<= 2 * space
);
1758 * If this metaslab is one we're actively using, adjust its
1759 * weight to make it preferable to any inactive metaslab so
1760 * we'll polish it off. If the fragmentation on this metaslab
1761 * has exceed our threshold, then don't mark it active.
1763 if (msp
->ms_loaded
&& msp
->ms_fragmentation
!= ZFS_FRAG_INVALID
&&
1764 msp
->ms_fragmentation
<= zfs_metaslab_fragmentation_threshold
) {
1765 weight
|= (msp
->ms_weight
& METASLAB_ACTIVE_MASK
);
1768 WEIGHT_SET_SPACEBASED(weight
);
1773 * Return the weight of the specified metaslab, according to the segment-based
1774 * weighting algorithm. The metaslab must be loaded. This function can
1775 * be called within a sync pass since it relies only on the metaslab's
1776 * range tree which is always accurate when the metaslab is loaded.
1779 metaslab_weight_from_range_tree(metaslab_t
*msp
)
1781 uint64_t weight
= 0;
1782 uint32_t segments
= 0;
1784 ASSERT(msp
->ms_loaded
);
1786 for (int i
= RANGE_TREE_HISTOGRAM_SIZE
- 1; i
>= SPA_MINBLOCKSHIFT
;
1788 uint8_t shift
= msp
->ms_group
->mg_vd
->vdev_ashift
;
1789 int max_idx
= SPACE_MAP_HISTOGRAM_SIZE
+ shift
- 1;
1792 segments
+= msp
->ms_allocatable
->rt_histogram
[i
];
1795 * The range tree provides more precision than the space map
1796 * and must be downgraded so that all values fit within the
1797 * space map's histogram. This allows us to compare loaded
1798 * vs. unloaded metaslabs to determine which metaslab is
1799 * considered "best".
1804 if (segments
!= 0) {
1805 WEIGHT_SET_COUNT(weight
, segments
);
1806 WEIGHT_SET_INDEX(weight
, i
);
1807 WEIGHT_SET_ACTIVE(weight
, 0);
1815 * Calculate the weight based on the on-disk histogram. This should only
1816 * be called after a sync pass has completely finished since the on-disk
1817 * information is updated in metaslab_sync().
1820 metaslab_weight_from_spacemap(metaslab_t
*msp
)
1822 uint64_t weight
= 0;
1824 for (int i
= SPACE_MAP_HISTOGRAM_SIZE
- 1; i
>= 0; i
--) {
1825 if (msp
->ms_sm
->sm_phys
->smp_histogram
[i
] != 0) {
1826 WEIGHT_SET_COUNT(weight
,
1827 msp
->ms_sm
->sm_phys
->smp_histogram
[i
]);
1828 WEIGHT_SET_INDEX(weight
, i
+
1829 msp
->ms_sm
->sm_shift
);
1830 WEIGHT_SET_ACTIVE(weight
, 0);
1838 * Compute a segment-based weight for the specified metaslab. The weight
1839 * is determined by highest bucket in the histogram. The information
1840 * for the highest bucket is encoded into the weight value.
1843 metaslab_segment_weight(metaslab_t
*msp
)
1845 metaslab_group_t
*mg
= msp
->ms_group
;
1846 uint64_t weight
= 0;
1847 uint8_t shift
= mg
->mg_vd
->vdev_ashift
;
1849 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1852 * The metaslab is completely free.
1854 if (space_map_allocated(msp
->ms_sm
) == 0) {
1855 int idx
= highbit64(msp
->ms_size
) - 1;
1856 int max_idx
= SPACE_MAP_HISTOGRAM_SIZE
+ shift
- 1;
1858 if (idx
< max_idx
) {
1859 WEIGHT_SET_COUNT(weight
, 1ULL);
1860 WEIGHT_SET_INDEX(weight
, idx
);
1862 WEIGHT_SET_COUNT(weight
, 1ULL << (idx
- max_idx
));
1863 WEIGHT_SET_INDEX(weight
, max_idx
);
1865 WEIGHT_SET_ACTIVE(weight
, 0);
1866 ASSERT(!WEIGHT_IS_SPACEBASED(weight
));
1871 ASSERT3U(msp
->ms_sm
->sm_dbuf
->db_size
, ==, sizeof (space_map_phys_t
));
1874 * If the metaslab is fully allocated then just make the weight 0.
1876 if (space_map_allocated(msp
->ms_sm
) == msp
->ms_size
)
1879 * If the metaslab is already loaded, then use the range tree to
1880 * determine the weight. Otherwise, we rely on the space map information
1881 * to generate the weight.
1883 if (msp
->ms_loaded
) {
1884 weight
= metaslab_weight_from_range_tree(msp
);
1886 weight
= metaslab_weight_from_spacemap(msp
);
1890 * If the metaslab was active the last time we calculated its weight
1891 * then keep it active. We want to consume the entire region that
1892 * is associated with this weight.
1894 if (msp
->ms_activation_weight
!= 0 && weight
!= 0)
1895 WEIGHT_SET_ACTIVE(weight
, WEIGHT_GET_ACTIVE(msp
->ms_weight
));
1900 * Determine if we should attempt to allocate from this metaslab. If the
1901 * metaslab has a maximum size then we can quickly determine if the desired
1902 * allocation size can be satisfied. Otherwise, if we're using segment-based
1903 * weighting then we can determine the maximum allocation that this metaslab
1904 * can accommodate based on the index encoded in the weight. If we're using
1905 * space-based weights then rely on the entire weight (excluding the weight
1909 metaslab_should_allocate(metaslab_t
*msp
, uint64_t asize
)
1911 boolean_t should_allocate
;
1913 if (msp
->ms_max_size
!= 0)
1914 return (msp
->ms_max_size
>= asize
);
1916 if (!WEIGHT_IS_SPACEBASED(msp
->ms_weight
)) {
1918 * The metaslab segment weight indicates segments in the
1919 * range [2^i, 2^(i+1)), where i is the index in the weight.
1920 * Since the asize might be in the middle of the range, we
1921 * should attempt the allocation if asize < 2^(i+1).
1923 should_allocate
= (asize
<
1924 1ULL << (WEIGHT_GET_INDEX(msp
->ms_weight
) + 1));
1926 should_allocate
= (asize
<=
1927 (msp
->ms_weight
& ~METASLAB_WEIGHT_TYPE
));
1929 return (should_allocate
);
1932 metaslab_weight(metaslab_t
*msp
)
1934 vdev_t
*vd
= msp
->ms_group
->mg_vd
;
1935 spa_t
*spa
= vd
->vdev_spa
;
1938 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1941 * If this vdev is in the process of being removed, there is nothing
1942 * for us to do here.
1944 if (vd
->vdev_removing
)
1947 metaslab_set_fragmentation(msp
);
1950 * Update the maximum size if the metaslab is loaded. This will
1951 * ensure that we get an accurate maximum size if newly freed space
1952 * has been added back into the free tree.
1955 msp
->ms_max_size
= metaslab_block_maxsize(msp
);
1958 * Segment-based weighting requires space map histogram support.
1960 if (zfs_metaslab_segment_weight_enabled
&&
1961 spa_feature_is_enabled(spa
, SPA_FEATURE_SPACEMAP_HISTOGRAM
) &&
1962 (msp
->ms_sm
== NULL
|| msp
->ms_sm
->sm_dbuf
->db_size
==
1963 sizeof (space_map_phys_t
))) {
1964 weight
= metaslab_segment_weight(msp
);
1966 weight
= metaslab_space_weight(msp
);
1972 metaslab_activate_allocator(metaslab_group_t
*mg
, metaslab_t
*msp
,
1973 int allocator
, uint64_t activation_weight
)
1976 * If we're activating for the claim code, we don't want to actually
1977 * set the metaslab up for a specific allocator.
1979 if (activation_weight
== METASLAB_WEIGHT_CLAIM
)
1981 metaslab_t
**arr
= (activation_weight
== METASLAB_WEIGHT_PRIMARY
?
1982 mg
->mg_primaries
: mg
->mg_secondaries
);
1984 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1985 mutex_enter(&mg
->mg_lock
);
1986 if (arr
[allocator
] != NULL
) {
1987 mutex_exit(&mg
->mg_lock
);
1991 arr
[allocator
] = msp
;
1992 ASSERT3S(msp
->ms_allocator
, ==, -1);
1993 msp
->ms_allocator
= allocator
;
1994 msp
->ms_primary
= (activation_weight
== METASLAB_WEIGHT_PRIMARY
);
1995 mutex_exit(&mg
->mg_lock
);
2001 metaslab_activate(metaslab_t
*msp
, int allocator
, uint64_t activation_weight
)
2003 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2005 if ((msp
->ms_weight
& METASLAB_ACTIVE_MASK
) == 0) {
2007 metaslab_load_wait(msp
);
2008 if (!msp
->ms_loaded
) {
2009 if ((error
= metaslab_load(msp
)) != 0) {
2010 metaslab_group_sort(msp
->ms_group
, msp
, 0);
2014 if ((msp
->ms_weight
& METASLAB_ACTIVE_MASK
) != 0) {
2016 * The metaslab was activated for another allocator
2017 * while we were waiting, we should reselect.
2021 if ((error
= metaslab_activate_allocator(msp
->ms_group
, msp
,
2022 allocator
, activation_weight
)) != 0) {
2026 msp
->ms_activation_weight
= msp
->ms_weight
;
2027 metaslab_group_sort(msp
->ms_group
, msp
,
2028 msp
->ms_weight
| activation_weight
);
2030 ASSERT(msp
->ms_loaded
);
2031 ASSERT(msp
->ms_weight
& METASLAB_ACTIVE_MASK
);
2037 metaslab_passivate_allocator(metaslab_group_t
*mg
, metaslab_t
*msp
,
2040 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2041 if (msp
->ms_weight
& METASLAB_WEIGHT_CLAIM
) {
2042 metaslab_group_sort(mg
, msp
, weight
);
2046 mutex_enter(&mg
->mg_lock
);
2047 ASSERT3P(msp
->ms_group
, ==, mg
);
2048 if (msp
->ms_primary
) {
2049 ASSERT3U(0, <=, msp
->ms_allocator
);
2050 ASSERT3U(msp
->ms_allocator
, <, mg
->mg_allocators
);
2051 ASSERT3P(mg
->mg_primaries
[msp
->ms_allocator
], ==, msp
);
2052 ASSERT(msp
->ms_weight
& METASLAB_WEIGHT_PRIMARY
);
2053 mg
->mg_primaries
[msp
->ms_allocator
] = NULL
;
2055 ASSERT(msp
->ms_weight
& METASLAB_WEIGHT_SECONDARY
);
2056 ASSERT3P(mg
->mg_secondaries
[msp
->ms_allocator
], ==, msp
);
2057 mg
->mg_secondaries
[msp
->ms_allocator
] = NULL
;
2059 msp
->ms_allocator
= -1;
2060 metaslab_group_sort_impl(mg
, msp
, weight
);
2061 mutex_exit(&mg
->mg_lock
);
2065 metaslab_passivate(metaslab_t
*msp
, uint64_t weight
)
2067 ASSERTV(uint64_t size
= weight
& ~METASLAB_WEIGHT_TYPE
);
2070 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
2071 * this metaslab again. In that case, it had better be empty,
2072 * or we would be leaving space on the table.
2074 ASSERT(!WEIGHT_IS_SPACEBASED(msp
->ms_weight
) ||
2075 size
>= SPA_MINBLOCKSIZE
||
2076 range_tree_space(msp
->ms_allocatable
) == 0);
2077 ASSERT0(weight
& METASLAB_ACTIVE_MASK
);
2079 msp
->ms_activation_weight
= 0;
2080 metaslab_passivate_allocator(msp
->ms_group
, msp
, weight
);
2081 ASSERT((msp
->ms_weight
& METASLAB_ACTIVE_MASK
) == 0);
2085 * Segment-based metaslabs are activated once and remain active until
2086 * we either fail an allocation attempt (similar to space-based metaslabs)
2087 * or have exhausted the free space in zfs_metaslab_switch_threshold
2088 * buckets since the metaslab was activated. This function checks to see
2089 * if we've exhaused the zfs_metaslab_switch_threshold buckets in the
2090 * metaslab and passivates it proactively. This will allow us to select a
2091 * metaslab with a larger contiguous region, if any, remaining within this
2092 * metaslab group. If we're in sync pass > 1, then we continue using this
2093 * metaslab so that we don't dirty more block and cause more sync passes.
2096 metaslab_segment_may_passivate(metaslab_t
*msp
)
2098 spa_t
*spa
= msp
->ms_group
->mg_vd
->vdev_spa
;
2100 if (WEIGHT_IS_SPACEBASED(msp
->ms_weight
) || spa_sync_pass(spa
) > 1)
2104 * Since we are in the middle of a sync pass, the most accurate
2105 * information that is accessible to us is the in-core range tree
2106 * histogram; calculate the new weight based on that information.
2108 uint64_t weight
= metaslab_weight_from_range_tree(msp
);
2109 int activation_idx
= WEIGHT_GET_INDEX(msp
->ms_activation_weight
);
2110 int current_idx
= WEIGHT_GET_INDEX(weight
);
2112 if (current_idx
<= activation_idx
- zfs_metaslab_switch_threshold
)
2113 metaslab_passivate(msp
, weight
);
2117 metaslab_preload(void *arg
)
2119 metaslab_t
*msp
= arg
;
2120 spa_t
*spa
= msp
->ms_group
->mg_vd
->vdev_spa
;
2121 fstrans_cookie_t cookie
= spl_fstrans_mark();
2123 ASSERT(!MUTEX_HELD(&msp
->ms_group
->mg_lock
));
2125 mutex_enter(&msp
->ms_lock
);
2126 metaslab_load_wait(msp
);
2127 if (!msp
->ms_loaded
)
2128 (void) metaslab_load(msp
);
2129 msp
->ms_selected_txg
= spa_syncing_txg(spa
);
2130 mutex_exit(&msp
->ms_lock
);
2131 spl_fstrans_unmark(cookie
);
2135 metaslab_group_preload(metaslab_group_t
*mg
)
2137 spa_t
*spa
= mg
->mg_vd
->vdev_spa
;
2139 avl_tree_t
*t
= &mg
->mg_metaslab_tree
;
2142 if (spa_shutting_down(spa
) || !metaslab_preload_enabled
) {
2143 taskq_wait_outstanding(mg
->mg_taskq
, 0);
2147 mutex_enter(&mg
->mg_lock
);
2150 * Load the next potential metaslabs
2152 for (msp
= avl_first(t
); msp
!= NULL
; msp
= AVL_NEXT(t
, msp
)) {
2153 ASSERT3P(msp
->ms_group
, ==, mg
);
2156 * We preload only the maximum number of metaslabs specified
2157 * by metaslab_preload_limit. If a metaslab is being forced
2158 * to condense then we preload it too. This will ensure
2159 * that force condensing happens in the next txg.
2161 if (++m
> metaslab_preload_limit
&& !msp
->ms_condense_wanted
) {
2165 VERIFY(taskq_dispatch(mg
->mg_taskq
, metaslab_preload
,
2166 msp
, TQ_SLEEP
) != TASKQID_INVALID
);
2168 mutex_exit(&mg
->mg_lock
);
2172 * Determine if the space map's on-disk footprint is past our tolerance
2173 * for inefficiency. We would like to use the following criteria to make
2176 * 1. The size of the space map object should not dramatically increase as a
2177 * result of writing out the free space range tree.
2179 * 2. The minimal on-disk space map representation is zfs_condense_pct/100
2180 * times the size than the free space range tree representation
2181 * (i.e. zfs_condense_pct = 110 and in-core = 1MB, minimal = 1.1MB).
2183 * 3. The on-disk size of the space map should actually decrease.
2185 * Unfortunately, we cannot compute the on-disk size of the space map in this
2186 * context because we cannot accurately compute the effects of compression, etc.
2187 * Instead, we apply the heuristic described in the block comment for
2188 * zfs_metaslab_condense_block_threshold - we only condense if the space used
2189 * is greater than a threshold number of blocks.
2192 metaslab_should_condense(metaslab_t
*msp
)
2194 space_map_t
*sm
= msp
->ms_sm
;
2195 vdev_t
*vd
= msp
->ms_group
->mg_vd
;
2196 uint64_t vdev_blocksize
= 1 << vd
->vdev_ashift
;
2197 uint64_t current_txg
= spa_syncing_txg(vd
->vdev_spa
);
2199 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2200 ASSERT(msp
->ms_loaded
);
2203 * Allocations and frees in early passes are generally more space
2204 * efficient (in terms of blocks described in space map entries)
2205 * than the ones in later passes (e.g. we don't compress after
2206 * sync pass 5) and condensing a metaslab multiple times in a txg
2207 * could degrade performance.
2209 * Thus we prefer condensing each metaslab at most once every txg at
2210 * the earliest sync pass possible. If a metaslab is eligible for
2211 * condensing again after being considered for condensing within the
2212 * same txg, it will hopefully be dirty in the next txg where it will
2213 * be condensed at an earlier pass.
2215 if (msp
->ms_condense_checked_txg
== current_txg
)
2217 msp
->ms_condense_checked_txg
= current_txg
;
2220 * We always condense metaslabs that are empty and metaslabs for
2221 * which a condense request has been made.
2223 if (avl_is_empty(&msp
->ms_allocatable_by_size
) ||
2224 msp
->ms_condense_wanted
)
2227 uint64_t object_size
= space_map_length(msp
->ms_sm
);
2228 uint64_t optimal_size
= space_map_estimate_optimal_size(sm
,
2229 msp
->ms_allocatable
, SM_NO_VDEVID
);
2231 dmu_object_info_t doi
;
2232 dmu_object_info_from_db(sm
->sm_dbuf
, &doi
);
2233 uint64_t record_size
= MAX(doi
.doi_data_block_size
, vdev_blocksize
);
2235 return (object_size
>= (optimal_size
* zfs_condense_pct
/ 100) &&
2236 object_size
> zfs_metaslab_condense_block_threshold
* record_size
);
2240 * Condense the on-disk space map representation to its minimized form.
2241 * The minimized form consists of a small number of allocations followed by
2242 * the entries of the free range tree.
2245 metaslab_condense(metaslab_t
*msp
, uint64_t txg
, dmu_tx_t
*tx
)
2247 range_tree_t
*condense_tree
;
2248 space_map_t
*sm
= msp
->ms_sm
;
2250 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2251 ASSERT(msp
->ms_loaded
);
2254 zfs_dbgmsg("condensing: txg %llu, msp[%llu] %p, vdev id %llu, "
2255 "spa %s, smp size %llu, segments %lu, forcing condense=%s", txg
,
2256 msp
->ms_id
, msp
, msp
->ms_group
->mg_vd
->vdev_id
,
2257 msp
->ms_group
->mg_vd
->vdev_spa
->spa_name
,
2258 space_map_length(msp
->ms_sm
),
2259 avl_numnodes(&msp
->ms_allocatable
->rt_root
),
2260 msp
->ms_condense_wanted
? "TRUE" : "FALSE");
2262 msp
->ms_condense_wanted
= B_FALSE
;
2265 * Create an range tree that is 100% allocated. We remove segments
2266 * that have been freed in this txg, any deferred frees that exist,
2267 * and any allocation in the future. Removing segments should be
2268 * a relatively inexpensive operation since we expect these trees to
2269 * have a small number of nodes.
2271 condense_tree
= range_tree_create(NULL
, NULL
);
2272 range_tree_add(condense_tree
, msp
->ms_start
, msp
->ms_size
);
2274 range_tree_walk(msp
->ms_freeing
, range_tree_remove
, condense_tree
);
2275 range_tree_walk(msp
->ms_freed
, range_tree_remove
, condense_tree
);
2277 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
2278 range_tree_walk(msp
->ms_defer
[t
],
2279 range_tree_remove
, condense_tree
);
2282 for (int t
= 1; t
< TXG_CONCURRENT_STATES
; t
++) {
2283 range_tree_walk(msp
->ms_allocating
[(txg
+ t
) & TXG_MASK
],
2284 range_tree_remove
, condense_tree
);
2288 * We're about to drop the metaslab's lock thus allowing
2289 * other consumers to change it's content. Set the
2290 * metaslab's ms_condensing flag to ensure that
2291 * allocations on this metaslab do not occur while we're
2292 * in the middle of committing it to disk. This is only critical
2293 * for ms_allocatable as all other range trees use per txg
2294 * views of their content.
2296 msp
->ms_condensing
= B_TRUE
;
2298 mutex_exit(&msp
->ms_lock
);
2299 space_map_truncate(sm
, zfs_metaslab_sm_blksz
, tx
);
2302 * While we would ideally like to create a space map representation
2303 * that consists only of allocation records, doing so can be
2304 * prohibitively expensive because the in-core free tree can be
2305 * large, and therefore computationally expensive to subtract
2306 * from the condense_tree. Instead we sync out two trees, a cheap
2307 * allocation only tree followed by the in-core free tree. While not
2308 * optimal, this is typically close to optimal, and much cheaper to
2311 space_map_write(sm
, condense_tree
, SM_ALLOC
, SM_NO_VDEVID
, tx
);
2312 range_tree_vacate(condense_tree
, NULL
, NULL
);
2313 range_tree_destroy(condense_tree
);
2315 space_map_write(sm
, msp
->ms_allocatable
, SM_FREE
, SM_NO_VDEVID
, tx
);
2316 mutex_enter(&msp
->ms_lock
);
2317 msp
->ms_condensing
= B_FALSE
;
2321 * Write a metaslab to disk in the context of the specified transaction group.
2324 metaslab_sync(metaslab_t
*msp
, uint64_t txg
)
2326 metaslab_group_t
*mg
= msp
->ms_group
;
2327 vdev_t
*vd
= mg
->mg_vd
;
2328 spa_t
*spa
= vd
->vdev_spa
;
2329 objset_t
*mos
= spa_meta_objset(spa
);
2330 range_tree_t
*alloctree
= msp
->ms_allocating
[txg
& TXG_MASK
];
2332 uint64_t object
= space_map_object(msp
->ms_sm
);
2334 ASSERT(!vd
->vdev_ishole
);
2337 * This metaslab has just been added so there's no work to do now.
2339 if (msp
->ms_freeing
== NULL
) {
2340 ASSERT3P(alloctree
, ==, NULL
);
2344 ASSERT3P(alloctree
, !=, NULL
);
2345 ASSERT3P(msp
->ms_freeing
, !=, NULL
);
2346 ASSERT3P(msp
->ms_freed
, !=, NULL
);
2347 ASSERT3P(msp
->ms_checkpointing
, !=, NULL
);
2350 * Normally, we don't want to process a metaslab if there are no
2351 * allocations or frees to perform. However, if the metaslab is being
2352 * forced to condense and it's loaded, we need to let it through.
2354 if (range_tree_is_empty(alloctree
) &&
2355 range_tree_is_empty(msp
->ms_freeing
) &&
2356 range_tree_is_empty(msp
->ms_checkpointing
) &&
2357 !(msp
->ms_loaded
&& msp
->ms_condense_wanted
))
2361 VERIFY(txg
<= spa_final_dirty_txg(spa
));
2364 * The only state that can actually be changing concurrently with
2365 * metaslab_sync() is the metaslab's ms_allocatable. No other
2366 * thread can be modifying this txg's alloc, freeing,
2367 * freed, or space_map_phys_t. We drop ms_lock whenever we
2368 * could call into the DMU, because the DMU can call down to us
2369 * (e.g. via zio_free()) at any time.
2371 * The spa_vdev_remove_thread() can be reading metaslab state
2372 * concurrently, and it is locked out by the ms_sync_lock. Note
2373 * that the ms_lock is insufficient for this, because it is dropped
2374 * by space_map_write().
2376 tx
= dmu_tx_create_assigned(spa_get_dsl(spa
), txg
);
2378 if (msp
->ms_sm
== NULL
) {
2379 uint64_t new_object
;
2381 new_object
= space_map_alloc(mos
, zfs_metaslab_sm_blksz
, tx
);
2382 VERIFY3U(new_object
, !=, 0);
2384 VERIFY0(space_map_open(&msp
->ms_sm
, mos
, new_object
,
2385 msp
->ms_start
, msp
->ms_size
, vd
->vdev_ashift
));
2386 ASSERT(msp
->ms_sm
!= NULL
);
2389 if (!range_tree_is_empty(msp
->ms_checkpointing
) &&
2390 vd
->vdev_checkpoint_sm
== NULL
) {
2391 ASSERT(spa_has_checkpoint(spa
));
2393 uint64_t new_object
= space_map_alloc(mos
,
2394 vdev_standard_sm_blksz
, tx
);
2395 VERIFY3U(new_object
, !=, 0);
2397 VERIFY0(space_map_open(&vd
->vdev_checkpoint_sm
,
2398 mos
, new_object
, 0, vd
->vdev_asize
, vd
->vdev_ashift
));
2399 ASSERT3P(vd
->vdev_checkpoint_sm
, !=, NULL
);
2402 * We save the space map object as an entry in vdev_top_zap
2403 * so it can be retrieved when the pool is reopened after an
2404 * export or through zdb.
2406 VERIFY0(zap_add(vd
->vdev_spa
->spa_meta_objset
,
2407 vd
->vdev_top_zap
, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM
,
2408 sizeof (new_object
), 1, &new_object
, tx
));
2411 mutex_enter(&msp
->ms_sync_lock
);
2412 mutex_enter(&msp
->ms_lock
);
2415 * Note: metaslab_condense() clears the space map's histogram.
2416 * Therefore we must verify and remove this histogram before
2419 metaslab_group_histogram_verify(mg
);
2420 metaslab_class_histogram_verify(mg
->mg_class
);
2421 metaslab_group_histogram_remove(mg
, msp
);
2423 if (msp
->ms_loaded
&& metaslab_should_condense(msp
)) {
2424 metaslab_condense(msp
, txg
, tx
);
2426 mutex_exit(&msp
->ms_lock
);
2427 space_map_write(msp
->ms_sm
, alloctree
, SM_ALLOC
,
2429 space_map_write(msp
->ms_sm
, msp
->ms_freeing
, SM_FREE
,
2431 mutex_enter(&msp
->ms_lock
);
2434 if (!range_tree_is_empty(msp
->ms_checkpointing
)) {
2435 ASSERT(spa_has_checkpoint(spa
));
2436 ASSERT3P(vd
->vdev_checkpoint_sm
, !=, NULL
);
2439 * Since we are doing writes to disk and the ms_checkpointing
2440 * tree won't be changing during that time, we drop the
2441 * ms_lock while writing to the checkpoint space map.
2443 mutex_exit(&msp
->ms_lock
);
2444 space_map_write(vd
->vdev_checkpoint_sm
,
2445 msp
->ms_checkpointing
, SM_FREE
, SM_NO_VDEVID
, tx
);
2446 mutex_enter(&msp
->ms_lock
);
2447 space_map_update(vd
->vdev_checkpoint_sm
);
2449 spa
->spa_checkpoint_info
.sci_dspace
+=
2450 range_tree_space(msp
->ms_checkpointing
);
2451 vd
->vdev_stat
.vs_checkpoint_space
+=
2452 range_tree_space(msp
->ms_checkpointing
);
2453 ASSERT3U(vd
->vdev_stat
.vs_checkpoint_space
, ==,
2454 -vd
->vdev_checkpoint_sm
->sm_alloc
);
2456 range_tree_vacate(msp
->ms_checkpointing
, NULL
, NULL
);
2459 if (msp
->ms_loaded
) {
2461 * When the space map is loaded, we have an accurate
2462 * histogram in the range tree. This gives us an opportunity
2463 * to bring the space map's histogram up-to-date so we clear
2464 * it first before updating it.
2466 space_map_histogram_clear(msp
->ms_sm
);
2467 space_map_histogram_add(msp
->ms_sm
, msp
->ms_allocatable
, tx
);
2470 * Since we've cleared the histogram we need to add back
2471 * any free space that has already been processed, plus
2472 * any deferred space. This allows the on-disk histogram
2473 * to accurately reflect all free space even if some space
2474 * is not yet available for allocation (i.e. deferred).
2476 space_map_histogram_add(msp
->ms_sm
, msp
->ms_freed
, tx
);
2479 * Add back any deferred free space that has not been
2480 * added back into the in-core free tree yet. This will
2481 * ensure that we don't end up with a space map histogram
2482 * that is completely empty unless the metaslab is fully
2485 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
2486 space_map_histogram_add(msp
->ms_sm
,
2487 msp
->ms_defer
[t
], tx
);
2492 * Always add the free space from this sync pass to the space
2493 * map histogram. We want to make sure that the on-disk histogram
2494 * accounts for all free space. If the space map is not loaded,
2495 * then we will lose some accuracy but will correct it the next
2496 * time we load the space map.
2498 space_map_histogram_add(msp
->ms_sm
, msp
->ms_freeing
, tx
);
2500 metaslab_group_histogram_add(mg
, msp
);
2501 metaslab_group_histogram_verify(mg
);
2502 metaslab_class_histogram_verify(mg
->mg_class
);
2505 * For sync pass 1, we avoid traversing this txg's free range tree
2506 * and instead will just swap the pointers for freeing and
2507 * freed. We can safely do this since the freed_tree is
2508 * guaranteed to be empty on the initial pass.
2510 if (spa_sync_pass(spa
) == 1) {
2511 range_tree_swap(&msp
->ms_freeing
, &msp
->ms_freed
);
2513 range_tree_vacate(msp
->ms_freeing
,
2514 range_tree_add
, msp
->ms_freed
);
2516 range_tree_vacate(alloctree
, NULL
, NULL
);
2518 ASSERT0(range_tree_space(msp
->ms_allocating
[txg
& TXG_MASK
]));
2519 ASSERT0(range_tree_space(msp
->ms_allocating
[TXG_CLEAN(txg
)
2521 ASSERT0(range_tree_space(msp
->ms_freeing
));
2522 ASSERT0(range_tree_space(msp
->ms_checkpointing
));
2524 mutex_exit(&msp
->ms_lock
);
2526 if (object
!= space_map_object(msp
->ms_sm
)) {
2527 object
= space_map_object(msp
->ms_sm
);
2528 dmu_write(mos
, vd
->vdev_ms_array
, sizeof (uint64_t) *
2529 msp
->ms_id
, sizeof (uint64_t), &object
, tx
);
2531 mutex_exit(&msp
->ms_sync_lock
);
2536 * Called after a transaction group has completely synced to mark
2537 * all of the metaslab's free space as usable.
2540 metaslab_sync_done(metaslab_t
*msp
, uint64_t txg
)
2542 metaslab_group_t
*mg
= msp
->ms_group
;
2543 vdev_t
*vd
= mg
->mg_vd
;
2544 spa_t
*spa
= vd
->vdev_spa
;
2545 range_tree_t
**defer_tree
;
2546 int64_t alloc_delta
, defer_delta
;
2547 boolean_t defer_allowed
= B_TRUE
;
2549 ASSERT(!vd
->vdev_ishole
);
2551 mutex_enter(&msp
->ms_lock
);
2554 * If this metaslab is just becoming available, initialize its
2555 * range trees and add its capacity to the vdev.
2557 if (msp
->ms_freed
== NULL
) {
2558 for (int t
= 0; t
< TXG_SIZE
; t
++) {
2559 ASSERT(msp
->ms_allocating
[t
] == NULL
);
2561 msp
->ms_allocating
[t
] = range_tree_create(NULL
, NULL
);
2564 ASSERT3P(msp
->ms_freeing
, ==, NULL
);
2565 msp
->ms_freeing
= range_tree_create(NULL
, NULL
);
2567 ASSERT3P(msp
->ms_freed
, ==, NULL
);
2568 msp
->ms_freed
= range_tree_create(NULL
, NULL
);
2570 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
2571 ASSERT(msp
->ms_defer
[t
] == NULL
);
2573 msp
->ms_defer
[t
] = range_tree_create(NULL
, NULL
);
2576 ASSERT3P(msp
->ms_checkpointing
, ==, NULL
);
2577 msp
->ms_checkpointing
= range_tree_create(NULL
, NULL
);
2579 vdev_space_update(vd
, 0, 0, msp
->ms_size
);
2581 ASSERT0(range_tree_space(msp
->ms_freeing
));
2582 ASSERT0(range_tree_space(msp
->ms_checkpointing
));
2584 defer_tree
= &msp
->ms_defer
[txg
% TXG_DEFER_SIZE
];
2586 uint64_t free_space
= metaslab_class_get_space(spa_normal_class(spa
)) -
2587 metaslab_class_get_alloc(spa_normal_class(spa
));
2588 if (free_space
<= spa_get_slop_space(spa
) || vd
->vdev_removing
) {
2589 defer_allowed
= B_FALSE
;
2593 alloc_delta
= space_map_alloc_delta(msp
->ms_sm
);
2594 if (defer_allowed
) {
2595 defer_delta
= range_tree_space(msp
->ms_freed
) -
2596 range_tree_space(*defer_tree
);
2598 defer_delta
-= range_tree_space(*defer_tree
);
2601 vdev_space_update(vd
, alloc_delta
+ defer_delta
, defer_delta
, 0);
2604 * If there's a metaslab_load() in progress, wait for it to complete
2605 * so that we have a consistent view of the in-core space map.
2607 metaslab_load_wait(msp
);
2610 * Move the frees from the defer_tree back to the free
2611 * range tree (if it's loaded). Swap the freed_tree and
2612 * the defer_tree -- this is safe to do because we've
2613 * just emptied out the defer_tree.
2615 range_tree_vacate(*defer_tree
,
2616 msp
->ms_loaded
? range_tree_add
: NULL
, msp
->ms_allocatable
);
2617 if (defer_allowed
) {
2618 range_tree_swap(&msp
->ms_freed
, defer_tree
);
2620 range_tree_vacate(msp
->ms_freed
,
2621 msp
->ms_loaded
? range_tree_add
: NULL
,
2622 msp
->ms_allocatable
);
2624 space_map_update(msp
->ms_sm
);
2626 msp
->ms_deferspace
+= defer_delta
;
2627 ASSERT3S(msp
->ms_deferspace
, >=, 0);
2628 ASSERT3S(msp
->ms_deferspace
, <=, msp
->ms_size
);
2629 if (msp
->ms_deferspace
!= 0) {
2631 * Keep syncing this metaslab until all deferred frees
2632 * are back in circulation.
2634 vdev_dirty(vd
, VDD_METASLAB
, msp
, txg
+ 1);
2638 msp
->ms_new
= B_FALSE
;
2639 mutex_enter(&mg
->mg_lock
);
2641 mutex_exit(&mg
->mg_lock
);
2644 * Calculate the new weights before unloading any metaslabs.
2645 * This will give us the most accurate weighting.
2647 metaslab_group_sort(mg
, msp
, metaslab_weight(msp
) |
2648 (msp
->ms_weight
& METASLAB_ACTIVE_MASK
));
2651 * If the metaslab is loaded and we've not tried to load or allocate
2652 * from it in 'metaslab_unload_delay' txgs, then unload it.
2654 if (msp
->ms_loaded
&&
2655 msp
->ms_selected_txg
+ metaslab_unload_delay
< txg
) {
2657 for (int t
= 1; t
< TXG_CONCURRENT_STATES
; t
++) {
2658 VERIFY0(range_tree_space(
2659 msp
->ms_allocating
[(txg
+ t
) & TXG_MASK
]));
2661 if (msp
->ms_allocator
!= -1) {
2662 metaslab_passivate(msp
, msp
->ms_weight
&
2663 ~METASLAB_ACTIVE_MASK
);
2666 if (!metaslab_debug_unload
)
2667 metaslab_unload(msp
);
2670 ASSERT0(range_tree_space(msp
->ms_allocating
[txg
& TXG_MASK
]));
2671 ASSERT0(range_tree_space(msp
->ms_freeing
));
2672 ASSERT0(range_tree_space(msp
->ms_freed
));
2673 ASSERT0(range_tree_space(msp
->ms_checkpointing
));
2675 mutex_exit(&msp
->ms_lock
);
2679 metaslab_sync_reassess(metaslab_group_t
*mg
)
2681 spa_t
*spa
= mg
->mg_class
->mc_spa
;
2683 spa_config_enter(spa
, SCL_ALLOC
, FTAG
, RW_READER
);
2684 metaslab_group_alloc_update(mg
);
2685 mg
->mg_fragmentation
= metaslab_group_fragmentation(mg
);
2688 * Preload the next potential metaslabs but only on active
2689 * metaslab groups. We can get into a state where the metaslab
2690 * is no longer active since we dirty metaslabs as we remove a
2691 * a device, thus potentially making the metaslab group eligible
2694 if (mg
->mg_activation_count
> 0) {
2695 metaslab_group_preload(mg
);
2697 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
2701 metaslab_distance(metaslab_t
*msp
, dva_t
*dva
)
2703 uint64_t ms_shift
= msp
->ms_group
->mg_vd
->vdev_ms_shift
;
2704 uint64_t offset
= DVA_GET_OFFSET(dva
) >> ms_shift
;
2705 uint64_t start
= msp
->ms_id
;
2707 if (msp
->ms_group
->mg_vd
->vdev_id
!= DVA_GET_VDEV(dva
))
2708 return (1ULL << 63);
2711 return ((start
- offset
) << ms_shift
);
2713 return ((offset
- start
) << ms_shift
);
2718 * ==========================================================================
2719 * Metaslab allocation tracing facility
2720 * ==========================================================================
2722 #ifdef _METASLAB_TRACING
2723 kstat_t
*metaslab_trace_ksp
;
2724 kstat_named_t metaslab_trace_over_limit
;
2727 metaslab_alloc_trace_init(void)
2729 ASSERT(metaslab_alloc_trace_cache
== NULL
);
2730 metaslab_alloc_trace_cache
= kmem_cache_create(
2731 "metaslab_alloc_trace_cache", sizeof (metaslab_alloc_trace_t
),
2732 0, NULL
, NULL
, NULL
, NULL
, NULL
, 0);
2733 metaslab_trace_ksp
= kstat_create("zfs", 0, "metaslab_trace_stats",
2734 "misc", KSTAT_TYPE_NAMED
, 1, KSTAT_FLAG_VIRTUAL
);
2735 if (metaslab_trace_ksp
!= NULL
) {
2736 metaslab_trace_ksp
->ks_data
= &metaslab_trace_over_limit
;
2737 kstat_named_init(&metaslab_trace_over_limit
,
2738 "metaslab_trace_over_limit", KSTAT_DATA_UINT64
);
2739 kstat_install(metaslab_trace_ksp
);
2744 metaslab_alloc_trace_fini(void)
2746 if (metaslab_trace_ksp
!= NULL
) {
2747 kstat_delete(metaslab_trace_ksp
);
2748 metaslab_trace_ksp
= NULL
;
2750 kmem_cache_destroy(metaslab_alloc_trace_cache
);
2751 metaslab_alloc_trace_cache
= NULL
;
2755 * Add an allocation trace element to the allocation tracing list.
2758 metaslab_trace_add(zio_alloc_list_t
*zal
, metaslab_group_t
*mg
,
2759 metaslab_t
*msp
, uint64_t psize
, uint32_t dva_id
, uint64_t offset
,
2762 metaslab_alloc_trace_t
*mat
;
2764 if (!metaslab_trace_enabled
)
2768 * When the tracing list reaches its maximum we remove
2769 * the second element in the list before adding a new one.
2770 * By removing the second element we preserve the original
2771 * entry as a clue to what allocations steps have already been
2774 if (zal
->zal_size
== metaslab_trace_max_entries
) {
2775 metaslab_alloc_trace_t
*mat_next
;
2777 panic("too many entries in allocation list");
2779 atomic_inc_64(&metaslab_trace_over_limit
.value
.ui64
);
2781 mat_next
= list_next(&zal
->zal_list
, list_head(&zal
->zal_list
));
2782 list_remove(&zal
->zal_list
, mat_next
);
2783 kmem_cache_free(metaslab_alloc_trace_cache
, mat_next
);
2786 mat
= kmem_cache_alloc(metaslab_alloc_trace_cache
, KM_SLEEP
);
2787 list_link_init(&mat
->mat_list_node
);
2790 mat
->mat_size
= psize
;
2791 mat
->mat_dva_id
= dva_id
;
2792 mat
->mat_offset
= offset
;
2793 mat
->mat_weight
= 0;
2794 mat
->mat_allocator
= allocator
;
2797 mat
->mat_weight
= msp
->ms_weight
;
2800 * The list is part of the zio so locking is not required. Only
2801 * a single thread will perform allocations for a given zio.
2803 list_insert_tail(&zal
->zal_list
, mat
);
2806 ASSERT3U(zal
->zal_size
, <=, metaslab_trace_max_entries
);
2810 metaslab_trace_init(zio_alloc_list_t
*zal
)
2812 list_create(&zal
->zal_list
, sizeof (metaslab_alloc_trace_t
),
2813 offsetof(metaslab_alloc_trace_t
, mat_list_node
));
2818 metaslab_trace_fini(zio_alloc_list_t
*zal
)
2820 metaslab_alloc_trace_t
*mat
;
2822 while ((mat
= list_remove_head(&zal
->zal_list
)) != NULL
)
2823 kmem_cache_free(metaslab_alloc_trace_cache
, mat
);
2824 list_destroy(&zal
->zal_list
);
2829 #define metaslab_trace_add(zal, mg, msp, psize, id, off, alloc)
2832 metaslab_alloc_trace_init(void)
2837 metaslab_alloc_trace_fini(void)
2842 metaslab_trace_init(zio_alloc_list_t
*zal
)
2847 metaslab_trace_fini(zio_alloc_list_t
*zal
)
2851 #endif /* _METASLAB_TRACING */
2854 * ==========================================================================
2855 * Metaslab block operations
2856 * ==========================================================================
2860 metaslab_group_alloc_increment(spa_t
*spa
, uint64_t vdev
, void *tag
, int flags
,
2863 if (!(flags
& METASLAB_ASYNC_ALLOC
) ||
2864 (flags
& METASLAB_DONT_THROTTLE
))
2867 metaslab_group_t
*mg
= vdev_lookup_top(spa
, vdev
)->vdev_mg
;
2868 if (!mg
->mg_class
->mc_alloc_throttle_enabled
)
2871 (void) refcount_add(&mg
->mg_alloc_queue_depth
[allocator
], tag
);
2875 metaslab_group_increment_qdepth(metaslab_group_t
*mg
, int allocator
)
2877 uint64_t max
= mg
->mg_max_alloc_queue_depth
;
2878 uint64_t cur
= mg
->mg_cur_max_alloc_queue_depth
[allocator
];
2880 if (atomic_cas_64(&mg
->mg_cur_max_alloc_queue_depth
[allocator
],
2881 cur
, cur
+ 1) == cur
) {
2883 &mg
->mg_class
->mc_alloc_max_slots
[allocator
]);
2886 cur
= mg
->mg_cur_max_alloc_queue_depth
[allocator
];
2891 metaslab_group_alloc_decrement(spa_t
*spa
, uint64_t vdev
, void *tag
, int flags
,
2892 int allocator
, boolean_t io_complete
)
2894 if (!(flags
& METASLAB_ASYNC_ALLOC
) ||
2895 (flags
& METASLAB_DONT_THROTTLE
))
2898 metaslab_group_t
*mg
= vdev_lookup_top(spa
, vdev
)->vdev_mg
;
2899 if (!mg
->mg_class
->mc_alloc_throttle_enabled
)
2902 (void) refcount_remove(&mg
->mg_alloc_queue_depth
[allocator
], tag
);
2904 metaslab_group_increment_qdepth(mg
, allocator
);
2908 metaslab_group_alloc_verify(spa_t
*spa
, const blkptr_t
*bp
, void *tag
,
2912 const dva_t
*dva
= bp
->blk_dva
;
2913 int ndvas
= BP_GET_NDVAS(bp
);
2915 for (int d
= 0; d
< ndvas
; d
++) {
2916 uint64_t vdev
= DVA_GET_VDEV(&dva
[d
]);
2917 metaslab_group_t
*mg
= vdev_lookup_top(spa
, vdev
)->vdev_mg
;
2918 VERIFY(refcount_not_held(&mg
->mg_alloc_queue_depth
[allocator
],
2925 metaslab_block_alloc(metaslab_t
*msp
, uint64_t size
, uint64_t txg
)
2928 range_tree_t
*rt
= msp
->ms_allocatable
;
2929 metaslab_class_t
*mc
= msp
->ms_group
->mg_class
;
2931 VERIFY(!msp
->ms_condensing
);
2933 start
= mc
->mc_ops
->msop_alloc(msp
, size
);
2934 if (start
!= -1ULL) {
2935 metaslab_group_t
*mg
= msp
->ms_group
;
2936 vdev_t
*vd
= mg
->mg_vd
;
2938 VERIFY0(P2PHASE(start
, 1ULL << vd
->vdev_ashift
));
2939 VERIFY0(P2PHASE(size
, 1ULL << vd
->vdev_ashift
));
2940 VERIFY3U(range_tree_space(rt
) - size
, <=, msp
->ms_size
);
2941 range_tree_remove(rt
, start
, size
);
2943 if (range_tree_is_empty(msp
->ms_allocating
[txg
& TXG_MASK
]))
2944 vdev_dirty(mg
->mg_vd
, VDD_METASLAB
, msp
, txg
);
2946 range_tree_add(msp
->ms_allocating
[txg
& TXG_MASK
], start
, size
);
2948 /* Track the last successful allocation */
2949 msp
->ms_alloc_txg
= txg
;
2950 metaslab_verify_space(msp
, txg
);
2954 * Now that we've attempted the allocation we need to update the
2955 * metaslab's maximum block size since it may have changed.
2957 msp
->ms_max_size
= metaslab_block_maxsize(msp
);
2962 * Find the metaslab with the highest weight that is less than what we've
2963 * already tried. In the common case, this means that we will examine each
2964 * metaslab at most once. Note that concurrent callers could reorder metaslabs
2965 * by activation/passivation once we have dropped the mg_lock. If a metaslab is
2966 * activated by another thread, and we fail to allocate from the metaslab we
2967 * have selected, we may not try the newly-activated metaslab, and instead
2968 * activate another metaslab. This is not optimal, but generally does not cause
2969 * any problems (a possible exception being if every metaslab is completely full
2970 * except for the the newly-activated metaslab which we fail to examine).
2973 find_valid_metaslab(metaslab_group_t
*mg
, uint64_t activation_weight
,
2974 dva_t
*dva
, int d
, uint64_t min_distance
, uint64_t asize
, int allocator
,
2975 zio_alloc_list_t
*zal
, metaslab_t
*search
, boolean_t
*was_active
)
2978 avl_tree_t
*t
= &mg
->mg_metaslab_tree
;
2979 metaslab_t
*msp
= avl_find(t
, search
, &idx
);
2981 msp
= avl_nearest(t
, idx
, AVL_AFTER
);
2983 for (; msp
!= NULL
; msp
= AVL_NEXT(t
, msp
)) {
2985 if (!metaslab_should_allocate(msp
, asize
)) {
2986 metaslab_trace_add(zal
, mg
, msp
, asize
, d
,
2987 TRACE_TOO_SMALL
, allocator
);
2992 * If the selected metaslab is condensing, skip it.
2994 if (msp
->ms_condensing
)
2997 *was_active
= msp
->ms_allocator
!= -1;
2999 * If we're activating as primary, this is our first allocation
3000 * from this disk, so we don't need to check how close we are.
3001 * If the metaslab under consideration was already active,
3002 * we're getting desperate enough to steal another allocator's
3003 * metaslab, so we still don't care about distances.
3005 if (activation_weight
== METASLAB_WEIGHT_PRIMARY
|| *was_active
)
3008 uint64_t target_distance
= min_distance
3009 + (space_map_allocated(msp
->ms_sm
) != 0 ? 0 :
3012 for (i
= 0; i
< d
; i
++) {
3013 if (metaslab_distance(msp
, &dva
[i
]) < target_distance
)
3021 search
->ms_weight
= msp
->ms_weight
;
3022 search
->ms_start
= msp
->ms_start
+ 1;
3023 search
->ms_allocator
= msp
->ms_allocator
;
3024 search
->ms_primary
= msp
->ms_primary
;
3031 metaslab_group_alloc_normal(metaslab_group_t
*mg
, zio_alloc_list_t
*zal
,
3032 uint64_t asize
, uint64_t txg
, uint64_t min_distance
, dva_t
*dva
, int d
,
3035 metaslab_t
*msp
= NULL
;
3036 uint64_t offset
= -1ULL;
3037 uint64_t activation_weight
;
3039 activation_weight
= METASLAB_WEIGHT_PRIMARY
;
3040 for (int i
= 0; i
< d
; i
++) {
3041 if (activation_weight
== METASLAB_WEIGHT_PRIMARY
&&
3042 DVA_GET_VDEV(&dva
[i
]) == mg
->mg_vd
->vdev_id
) {
3043 activation_weight
= METASLAB_WEIGHT_SECONDARY
;
3044 } else if (activation_weight
== METASLAB_WEIGHT_SECONDARY
&&
3045 DVA_GET_VDEV(&dva
[i
]) == mg
->mg_vd
->vdev_id
) {
3046 activation_weight
= METASLAB_WEIGHT_CLAIM
;
3052 * If we don't have enough metaslabs active to fill the entire array, we
3053 * just use the 0th slot.
3055 if (mg
->mg_ms_ready
< mg
->mg_allocators
* 3)
3058 ASSERT3U(mg
->mg_vd
->vdev_ms_count
, >=, 2);
3060 metaslab_t
*search
= kmem_alloc(sizeof (*search
), KM_SLEEP
);
3061 search
->ms_weight
= UINT64_MAX
;
3062 search
->ms_start
= 0;
3064 * At the end of the metaslab tree are the already-active metaslabs,
3065 * first the primaries, then the secondaries. When we resume searching
3066 * through the tree, we need to consider ms_allocator and ms_primary so
3067 * we start in the location right after where we left off, and don't
3068 * accidentally loop forever considering the same metaslabs.
3070 search
->ms_allocator
= -1;
3071 search
->ms_primary
= B_TRUE
;
3073 boolean_t was_active
= B_FALSE
;
3075 mutex_enter(&mg
->mg_lock
);
3077 if (activation_weight
== METASLAB_WEIGHT_PRIMARY
&&
3078 mg
->mg_primaries
[allocator
] != NULL
) {
3079 msp
= mg
->mg_primaries
[allocator
];
3080 was_active
= B_TRUE
;
3081 } else if (activation_weight
== METASLAB_WEIGHT_SECONDARY
&&
3082 mg
->mg_secondaries
[allocator
] != NULL
) {
3083 msp
= mg
->mg_secondaries
[allocator
];
3084 was_active
= B_TRUE
;
3086 msp
= find_valid_metaslab(mg
, activation_weight
, dva
, d
,
3087 min_distance
, asize
, allocator
, zal
, search
,
3091 mutex_exit(&mg
->mg_lock
);
3093 kmem_free(search
, sizeof (*search
));
3097 mutex_enter(&msp
->ms_lock
);
3099 * Ensure that the metaslab we have selected is still
3100 * capable of handling our request. It's possible that
3101 * another thread may have changed the weight while we
3102 * were blocked on the metaslab lock. We check the
3103 * active status first to see if we need to reselect
3106 if (was_active
&& !(msp
->ms_weight
& METASLAB_ACTIVE_MASK
)) {
3107 mutex_exit(&msp
->ms_lock
);
3112 * If the metaslab is freshly activated for an allocator that
3113 * isn't the one we're allocating from, or if it's a primary and
3114 * we're seeking a secondary (or vice versa), we go back and
3115 * select a new metaslab.
3117 if (!was_active
&& (msp
->ms_weight
& METASLAB_ACTIVE_MASK
) &&
3118 (msp
->ms_allocator
!= -1) &&
3119 (msp
->ms_allocator
!= allocator
|| ((activation_weight
==
3120 METASLAB_WEIGHT_PRIMARY
) != msp
->ms_primary
))) {
3121 mutex_exit(&msp
->ms_lock
);
3125 if (msp
->ms_weight
& METASLAB_WEIGHT_CLAIM
&&
3126 activation_weight
!= METASLAB_WEIGHT_CLAIM
) {
3127 metaslab_passivate(msp
, msp
->ms_weight
&
3128 ~METASLAB_WEIGHT_CLAIM
);
3129 mutex_exit(&msp
->ms_lock
);
3133 if (metaslab_activate(msp
, allocator
, activation_weight
) != 0) {
3134 mutex_exit(&msp
->ms_lock
);
3138 msp
->ms_selected_txg
= txg
;
3141 * Now that we have the lock, recheck to see if we should
3142 * continue to use this metaslab for this allocation. The
3143 * the metaslab is now loaded so metaslab_should_allocate() can
3144 * accurately determine if the allocation attempt should
3147 if (!metaslab_should_allocate(msp
, asize
)) {
3148 /* Passivate this metaslab and select a new one. */
3149 metaslab_trace_add(zal
, mg
, msp
, asize
, d
,
3150 TRACE_TOO_SMALL
, allocator
);
3156 * If this metaslab is currently condensing then pick again as
3157 * we can't manipulate this metaslab until it's committed
3160 if (msp
->ms_condensing
) {
3161 metaslab_trace_add(zal
, mg
, msp
, asize
, d
,
3162 TRACE_CONDENSING
, allocator
);
3163 metaslab_passivate(msp
, msp
->ms_weight
&
3164 ~METASLAB_ACTIVE_MASK
);
3165 mutex_exit(&msp
->ms_lock
);
3169 offset
= metaslab_block_alloc(msp
, asize
, txg
);
3170 metaslab_trace_add(zal
, mg
, msp
, asize
, d
, offset
, allocator
);
3172 if (offset
!= -1ULL) {
3173 /* Proactively passivate the metaslab, if needed */
3174 metaslab_segment_may_passivate(msp
);
3178 ASSERT(msp
->ms_loaded
);
3181 * We were unable to allocate from this metaslab so determine
3182 * a new weight for this metaslab. Now that we have loaded
3183 * the metaslab we can provide a better hint to the metaslab
3186 * For space-based metaslabs, we use the maximum block size.
3187 * This information is only available when the metaslab
3188 * is loaded and is more accurate than the generic free
3189 * space weight that was calculated by metaslab_weight().
3190 * This information allows us to quickly compare the maximum
3191 * available allocation in the metaslab to the allocation
3192 * size being requested.
3194 * For segment-based metaslabs, determine the new weight
3195 * based on the highest bucket in the range tree. We
3196 * explicitly use the loaded segment weight (i.e. the range
3197 * tree histogram) since it contains the space that is
3198 * currently available for allocation and is accurate
3199 * even within a sync pass.
3201 if (WEIGHT_IS_SPACEBASED(msp
->ms_weight
)) {
3202 uint64_t weight
= metaslab_block_maxsize(msp
);
3203 WEIGHT_SET_SPACEBASED(weight
);
3204 metaslab_passivate(msp
, weight
);
3206 metaslab_passivate(msp
,
3207 metaslab_weight_from_range_tree(msp
));
3211 * We have just failed an allocation attempt, check
3212 * that metaslab_should_allocate() agrees. Otherwise,
3213 * we may end up in an infinite loop retrying the same
3216 ASSERT(!metaslab_should_allocate(msp
, asize
));
3217 mutex_exit(&msp
->ms_lock
);
3219 mutex_exit(&msp
->ms_lock
);
3220 kmem_free(search
, sizeof (*search
));
3225 metaslab_group_alloc(metaslab_group_t
*mg
, zio_alloc_list_t
*zal
,
3226 uint64_t asize
, uint64_t txg
, uint64_t min_distance
, dva_t
*dva
, int d
,
3230 ASSERT(mg
->mg_initialized
);
3232 offset
= metaslab_group_alloc_normal(mg
, zal
, asize
, txg
,
3233 min_distance
, dva
, d
, allocator
);
3235 mutex_enter(&mg
->mg_lock
);
3236 if (offset
== -1ULL) {
3237 mg
->mg_failed_allocations
++;
3238 metaslab_trace_add(zal
, mg
, NULL
, asize
, d
,
3239 TRACE_GROUP_FAILURE
, allocator
);
3240 if (asize
== SPA_GANGBLOCKSIZE
) {
3242 * This metaslab group was unable to allocate
3243 * the minimum gang block size so it must be out of
3244 * space. We must notify the allocation throttle
3245 * to start skipping allocation attempts to this
3246 * metaslab group until more space becomes available.
3247 * Note: this failure cannot be caused by the
3248 * allocation throttle since the allocation throttle
3249 * is only responsible for skipping devices and
3250 * not failing block allocations.
3252 mg
->mg_no_free_space
= B_TRUE
;
3255 mg
->mg_allocations
++;
3256 mutex_exit(&mg
->mg_lock
);
3261 * If we have to write a ditto block (i.e. more than one DVA for a given BP)
3262 * on the same vdev as an existing DVA of this BP, then try to allocate it
3263 * at least (vdev_asize / (2 ^ ditto_same_vdev_distance_shift)) away from the
3266 int ditto_same_vdev_distance_shift
= 3;
3269 * Allocate a block for the specified i/o.
3272 metaslab_alloc_dva(spa_t
*spa
, metaslab_class_t
*mc
, uint64_t psize
,
3273 dva_t
*dva
, int d
, dva_t
*hintdva
, uint64_t txg
, int flags
,
3274 zio_alloc_list_t
*zal
, int allocator
)
3276 metaslab_group_t
*mg
, *fast_mg
, *rotor
;
3278 boolean_t try_hard
= B_FALSE
;
3280 ASSERT(!DVA_IS_VALID(&dva
[d
]));
3283 * For testing, make some blocks above a certain size be gang blocks.
3285 if (psize
>= metaslab_force_ganging
&& (ddi_get_lbolt() & 3) == 0) {
3286 metaslab_trace_add(zal
, NULL
, NULL
, psize
, d
, TRACE_FORCE_GANG
,
3288 return (SET_ERROR(ENOSPC
));
3292 * Start at the rotor and loop through all mgs until we find something.
3293 * Note that there's no locking on mc_rotor or mc_aliquot because
3294 * nothing actually breaks if we miss a few updates -- we just won't
3295 * allocate quite as evenly. It all balances out over time.
3297 * If we are doing ditto or log blocks, try to spread them across
3298 * consecutive vdevs. If we're forced to reuse a vdev before we've
3299 * allocated all of our ditto blocks, then try and spread them out on
3300 * that vdev as much as possible. If it turns out to not be possible,
3301 * gradually lower our standards until anything becomes acceptable.
3302 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
3303 * gives us hope of containing our fault domains to something we're
3304 * able to reason about. Otherwise, any two top-level vdev failures
3305 * will guarantee the loss of data. With consecutive allocation,
3306 * only two adjacent top-level vdev failures will result in data loss.
3308 * If we are doing gang blocks (hintdva is non-NULL), try to keep
3309 * ourselves on the same vdev as our gang block header. That
3310 * way, we can hope for locality in vdev_cache, plus it makes our
3311 * fault domains something tractable.
3314 vd
= vdev_lookup_top(spa
, DVA_GET_VDEV(&hintdva
[d
]));
3317 * It's possible the vdev we're using as the hint no
3318 * longer exists or its mg has been closed (e.g. by
3319 * device removal). Consult the rotor when
3322 if (vd
!= NULL
&& vd
->vdev_mg
!= NULL
) {
3325 if (flags
& METASLAB_HINTBP_AVOID
&&
3326 mg
->mg_next
!= NULL
)
3331 } else if (d
!= 0) {
3332 vd
= vdev_lookup_top(spa
, DVA_GET_VDEV(&dva
[d
- 1]));
3333 mg
= vd
->vdev_mg
->mg_next
;
3334 } else if (flags
& METASLAB_FASTWRITE
) {
3335 mg
= fast_mg
= mc
->mc_rotor
;
3338 if (fast_mg
->mg_vd
->vdev_pending_fastwrite
<
3339 mg
->mg_vd
->vdev_pending_fastwrite
)
3341 } while ((fast_mg
= fast_mg
->mg_next
) != mc
->mc_rotor
);
3348 * If the hint put us into the wrong metaslab class, or into a
3349 * metaslab group that has been passivated, just follow the rotor.
3351 if (mg
->mg_class
!= mc
|| mg
->mg_activation_count
<= 0)
3357 boolean_t allocatable
;
3359 ASSERT(mg
->mg_activation_count
== 1);
3363 * Don't allocate from faulted devices.
3366 spa_config_enter(spa
, SCL_ZIO
, FTAG
, RW_READER
);
3367 allocatable
= vdev_allocatable(vd
);
3368 spa_config_exit(spa
, SCL_ZIO
, FTAG
);
3370 allocatable
= vdev_allocatable(vd
);
3374 * Determine if the selected metaslab group is eligible
3375 * for allocations. If we're ganging then don't allow
3376 * this metaslab group to skip allocations since that would
3377 * inadvertently return ENOSPC and suspend the pool
3378 * even though space is still available.
3380 if (allocatable
&& !GANG_ALLOCATION(flags
) && !try_hard
) {
3381 allocatable
= metaslab_group_allocatable(mg
, rotor
,
3386 metaslab_trace_add(zal
, mg
, NULL
, psize
, d
,
3387 TRACE_NOT_ALLOCATABLE
, allocator
);
3391 ASSERT(mg
->mg_initialized
);
3394 * Avoid writing single-copy data to a failing,
3395 * non-redundant vdev, unless we've already tried all
3398 if ((vd
->vdev_stat
.vs_write_errors
> 0 ||
3399 vd
->vdev_state
< VDEV_STATE_HEALTHY
) &&
3400 d
== 0 && !try_hard
&& vd
->vdev_children
== 0) {
3401 metaslab_trace_add(zal
, mg
, NULL
, psize
, d
,
3402 TRACE_VDEV_ERROR
, allocator
);
3406 ASSERT(mg
->mg_class
== mc
);
3409 * If we don't need to try hard, then require that the
3410 * block be 1/8th of the device away from any other DVAs
3411 * in this BP. If we are trying hard, allow any offset
3412 * to be used (distance=0).
3414 uint64_t distance
= 0;
3416 distance
= vd
->vdev_asize
>>
3417 ditto_same_vdev_distance_shift
;
3418 if (distance
<= (1ULL << vd
->vdev_ms_shift
))
3422 uint64_t asize
= vdev_psize_to_asize(vd
, psize
);
3423 ASSERT(P2PHASE(asize
, 1ULL << vd
->vdev_ashift
) == 0);
3425 uint64_t offset
= metaslab_group_alloc(mg
, zal
, asize
, txg
,
3426 distance
, dva
, d
, allocator
);
3428 if (offset
!= -1ULL) {
3430 * If we've just selected this metaslab group,
3431 * figure out whether the corresponding vdev is
3432 * over- or under-used relative to the pool,
3433 * and set an allocation bias to even it out.
3435 * Bias is also used to compensate for unequally
3436 * sized vdevs so that space is allocated fairly.
3438 if (mc
->mc_aliquot
== 0 && metaslab_bias_enabled
) {
3439 vdev_stat_t
*vs
= &vd
->vdev_stat
;
3440 int64_t vs_free
= vs
->vs_space
- vs
->vs_alloc
;
3441 int64_t mc_free
= mc
->mc_space
- mc
->mc_alloc
;
3445 * Calculate how much more or less we should
3446 * try to allocate from this device during
3447 * this iteration around the rotor.
3449 * This basically introduces a zero-centered
3450 * bias towards the devices with the most
3451 * free space, while compensating for vdev
3455 * vdev V1 = 16M/128M
3456 * vdev V2 = 16M/128M
3457 * ratio(V1) = 100% ratio(V2) = 100%
3459 * vdev V1 = 16M/128M
3460 * vdev V2 = 64M/128M
3461 * ratio(V1) = 127% ratio(V2) = 72%
3463 * vdev V1 = 16M/128M
3464 * vdev V2 = 64M/512M
3465 * ratio(V1) = 40% ratio(V2) = 160%
3467 ratio
= (vs_free
* mc
->mc_alloc_groups
* 100) /
3469 mg
->mg_bias
= ((ratio
- 100) *
3470 (int64_t)mg
->mg_aliquot
) / 100;
3471 } else if (!metaslab_bias_enabled
) {
3475 if ((flags
& METASLAB_FASTWRITE
) ||
3476 atomic_add_64_nv(&mc
->mc_aliquot
, asize
) >=
3477 mg
->mg_aliquot
+ mg
->mg_bias
) {
3478 mc
->mc_rotor
= mg
->mg_next
;
3482 DVA_SET_VDEV(&dva
[d
], vd
->vdev_id
);
3483 DVA_SET_OFFSET(&dva
[d
], offset
);
3484 DVA_SET_GANG(&dva
[d
],
3485 ((flags
& METASLAB_GANG_HEADER
) ? 1 : 0));
3486 DVA_SET_ASIZE(&dva
[d
], asize
);
3488 if (flags
& METASLAB_FASTWRITE
) {
3489 atomic_add_64(&vd
->vdev_pending_fastwrite
,
3496 mc
->mc_rotor
= mg
->mg_next
;
3498 } while ((mg
= mg
->mg_next
) != rotor
);
3501 * If we haven't tried hard, do so now.
3508 bzero(&dva
[d
], sizeof (dva_t
));
3510 metaslab_trace_add(zal
, rotor
, NULL
, psize
, d
, TRACE_ENOSPC
, allocator
);
3511 return (SET_ERROR(ENOSPC
));
3515 metaslab_free_concrete(vdev_t
*vd
, uint64_t offset
, uint64_t asize
,
3516 boolean_t checkpoint
)
3519 spa_t
*spa
= vd
->vdev_spa
;
3521 ASSERT(vdev_is_concrete(vd
));
3522 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
3523 ASSERT3U(offset
>> vd
->vdev_ms_shift
, <, vd
->vdev_ms_count
);
3525 msp
= vd
->vdev_ms
[offset
>> vd
->vdev_ms_shift
];
3527 VERIFY(!msp
->ms_condensing
);
3528 VERIFY3U(offset
, >=, msp
->ms_start
);
3529 VERIFY3U(offset
+ asize
, <=, msp
->ms_start
+ msp
->ms_size
);
3530 VERIFY0(P2PHASE(offset
, 1ULL << vd
->vdev_ashift
));
3531 VERIFY0(P2PHASE(asize
, 1ULL << vd
->vdev_ashift
));
3533 metaslab_check_free_impl(vd
, offset
, asize
);
3535 mutex_enter(&msp
->ms_lock
);
3536 if (range_tree_is_empty(msp
->ms_freeing
) &&
3537 range_tree_is_empty(msp
->ms_checkpointing
)) {
3538 vdev_dirty(vd
, VDD_METASLAB
, msp
, spa_syncing_txg(spa
));
3542 ASSERT(spa_has_checkpoint(spa
));
3543 range_tree_add(msp
->ms_checkpointing
, offset
, asize
);
3545 range_tree_add(msp
->ms_freeing
, offset
, asize
);
3547 mutex_exit(&msp
->ms_lock
);
3552 metaslab_free_impl_cb(uint64_t inner_offset
, vdev_t
*vd
, uint64_t offset
,
3553 uint64_t size
, void *arg
)
3555 boolean_t
*checkpoint
= arg
;
3557 ASSERT3P(checkpoint
, !=, NULL
);
3559 if (vd
->vdev_ops
->vdev_op_remap
!= NULL
)
3560 vdev_indirect_mark_obsolete(vd
, offset
, size
);
3562 metaslab_free_impl(vd
, offset
, size
, *checkpoint
);
3566 metaslab_free_impl(vdev_t
*vd
, uint64_t offset
, uint64_t size
,
3567 boolean_t checkpoint
)
3569 spa_t
*spa
= vd
->vdev_spa
;
3571 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
3573 if (spa_syncing_txg(spa
) > spa_freeze_txg(spa
))
3576 if (spa
->spa_vdev_removal
!= NULL
&&
3577 spa
->spa_vdev_removal
->svr_vdev_id
== vd
->vdev_id
&&
3578 vdev_is_concrete(vd
)) {
3580 * Note: we check if the vdev is concrete because when
3581 * we complete the removal, we first change the vdev to be
3582 * an indirect vdev (in open context), and then (in syncing
3583 * context) clear spa_vdev_removal.
3585 free_from_removing_vdev(vd
, offset
, size
);
3586 } else if (vd
->vdev_ops
->vdev_op_remap
!= NULL
) {
3587 vdev_indirect_mark_obsolete(vd
, offset
, size
);
3588 vd
->vdev_ops
->vdev_op_remap(vd
, offset
, size
,
3589 metaslab_free_impl_cb
, &checkpoint
);
3591 metaslab_free_concrete(vd
, offset
, size
, checkpoint
);
3595 typedef struct remap_blkptr_cb_arg
{
3597 spa_remap_cb_t rbca_cb
;
3598 vdev_t
*rbca_remap_vd
;
3599 uint64_t rbca_remap_offset
;
3601 } remap_blkptr_cb_arg_t
;
3604 remap_blkptr_cb(uint64_t inner_offset
, vdev_t
*vd
, uint64_t offset
,
3605 uint64_t size
, void *arg
)
3607 remap_blkptr_cb_arg_t
*rbca
= arg
;
3608 blkptr_t
*bp
= rbca
->rbca_bp
;
3610 /* We can not remap split blocks. */
3611 if (size
!= DVA_GET_ASIZE(&bp
->blk_dva
[0]))
3613 ASSERT0(inner_offset
);
3615 if (rbca
->rbca_cb
!= NULL
) {
3617 * At this point we know that we are not handling split
3618 * blocks and we invoke the callback on the previous
3619 * vdev which must be indirect.
3621 ASSERT3P(rbca
->rbca_remap_vd
->vdev_ops
, ==, &vdev_indirect_ops
);
3623 rbca
->rbca_cb(rbca
->rbca_remap_vd
->vdev_id
,
3624 rbca
->rbca_remap_offset
, size
, rbca
->rbca_cb_arg
);
3626 /* set up remap_blkptr_cb_arg for the next call */
3627 rbca
->rbca_remap_vd
= vd
;
3628 rbca
->rbca_remap_offset
= offset
;
3632 * The phys birth time is that of dva[0]. This ensures that we know
3633 * when each dva was written, so that resilver can determine which
3634 * blocks need to be scrubbed (i.e. those written during the time
3635 * the vdev was offline). It also ensures that the key used in
3636 * the ARC hash table is unique (i.e. dva[0] + phys_birth). If
3637 * we didn't change the phys_birth, a lookup in the ARC for a
3638 * remapped BP could find the data that was previously stored at
3639 * this vdev + offset.
3641 vdev_t
*oldvd
= vdev_lookup_top(vd
->vdev_spa
,
3642 DVA_GET_VDEV(&bp
->blk_dva
[0]));
3643 vdev_indirect_births_t
*vib
= oldvd
->vdev_indirect_births
;
3644 bp
->blk_phys_birth
= vdev_indirect_births_physbirth(vib
,
3645 DVA_GET_OFFSET(&bp
->blk_dva
[0]), DVA_GET_ASIZE(&bp
->blk_dva
[0]));
3647 DVA_SET_VDEV(&bp
->blk_dva
[0], vd
->vdev_id
);
3648 DVA_SET_OFFSET(&bp
->blk_dva
[0], offset
);
3652 * If the block pointer contains any indirect DVAs, modify them to refer to
3653 * concrete DVAs. Note that this will sometimes not be possible, leaving
3654 * the indirect DVA in place. This happens if the indirect DVA spans multiple
3655 * segments in the mapping (i.e. it is a "split block").
3657 * If the BP was remapped, calls the callback on the original dva (note the
3658 * callback can be called multiple times if the original indirect DVA refers
3659 * to another indirect DVA, etc).
3661 * Returns TRUE if the BP was remapped.
3664 spa_remap_blkptr(spa_t
*spa
, blkptr_t
*bp
, spa_remap_cb_t callback
, void *arg
)
3666 remap_blkptr_cb_arg_t rbca
;
3668 if (!zfs_remap_blkptr_enable
)
3671 if (!spa_feature_is_enabled(spa
, SPA_FEATURE_OBSOLETE_COUNTS
))
3675 * Dedup BP's can not be remapped, because ddt_phys_select() depends
3676 * on DVA[0] being the same in the BP as in the DDT (dedup table).
3678 if (BP_GET_DEDUP(bp
))
3682 * Gang blocks can not be remapped, because
3683 * zio_checksum_gang_verifier() depends on the DVA[0] that's in
3684 * the BP used to read the gang block header (GBH) being the same
3685 * as the DVA[0] that we allocated for the GBH.
3691 * Embedded BP's have no DVA to remap.
3693 if (BP_GET_NDVAS(bp
) < 1)
3697 * Note: we only remap dva[0]. If we remapped other dvas, we
3698 * would no longer know what their phys birth txg is.
3700 dva_t
*dva
= &bp
->blk_dva
[0];
3702 uint64_t offset
= DVA_GET_OFFSET(dva
);
3703 uint64_t size
= DVA_GET_ASIZE(dva
);
3704 vdev_t
*vd
= vdev_lookup_top(spa
, DVA_GET_VDEV(dva
));
3706 if (vd
->vdev_ops
->vdev_op_remap
== NULL
)
3710 rbca
.rbca_cb
= callback
;
3711 rbca
.rbca_remap_vd
= vd
;
3712 rbca
.rbca_remap_offset
= offset
;
3713 rbca
.rbca_cb_arg
= arg
;
3716 * remap_blkptr_cb() will be called in order for each level of
3717 * indirection, until a concrete vdev is reached or a split block is
3718 * encountered. old_vd and old_offset are updated within the callback
3719 * as we go from the one indirect vdev to the next one (either concrete
3720 * or indirect again) in that order.
3722 vd
->vdev_ops
->vdev_op_remap(vd
, offset
, size
, remap_blkptr_cb
, &rbca
);
3724 /* Check if the DVA wasn't remapped because it is a split block */
3725 if (DVA_GET_VDEV(&rbca
.rbca_bp
->blk_dva
[0]) == vd
->vdev_id
)
3732 * Undo the allocation of a DVA which happened in the given transaction group.
3735 metaslab_unalloc_dva(spa_t
*spa
, const dva_t
*dva
, uint64_t txg
)
3739 uint64_t vdev
= DVA_GET_VDEV(dva
);
3740 uint64_t offset
= DVA_GET_OFFSET(dva
);
3741 uint64_t size
= DVA_GET_ASIZE(dva
);
3743 ASSERT(DVA_IS_VALID(dva
));
3744 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
3746 if (txg
> spa_freeze_txg(spa
))
3749 if ((vd
= vdev_lookup_top(spa
, vdev
)) == NULL
|| !DVA_IS_VALID(dva
) ||
3750 (offset
>> vd
->vdev_ms_shift
) >= vd
->vdev_ms_count
) {
3751 zfs_panic_recover("metaslab_free_dva(): bad DVA %llu:%llu:%llu",
3752 (u_longlong_t
)vdev
, (u_longlong_t
)offset
,
3753 (u_longlong_t
)size
);
3757 ASSERT(!vd
->vdev_removing
);
3758 ASSERT(vdev_is_concrete(vd
));
3759 ASSERT0(vd
->vdev_indirect_config
.vic_mapping_object
);
3760 ASSERT3P(vd
->vdev_indirect_mapping
, ==, NULL
);
3762 if (DVA_GET_GANG(dva
))
3763 size
= vdev_psize_to_asize(vd
, SPA_GANGBLOCKSIZE
);
3765 msp
= vd
->vdev_ms
[offset
>> vd
->vdev_ms_shift
];
3767 mutex_enter(&msp
->ms_lock
);
3768 range_tree_remove(msp
->ms_allocating
[txg
& TXG_MASK
],
3771 VERIFY(!msp
->ms_condensing
);
3772 VERIFY3U(offset
, >=, msp
->ms_start
);
3773 VERIFY3U(offset
+ size
, <=, msp
->ms_start
+ msp
->ms_size
);
3774 VERIFY3U(range_tree_space(msp
->ms_allocatable
) + size
, <=,
3776 VERIFY0(P2PHASE(offset
, 1ULL << vd
->vdev_ashift
));
3777 VERIFY0(P2PHASE(size
, 1ULL << vd
->vdev_ashift
));
3778 range_tree_add(msp
->ms_allocatable
, offset
, size
);
3779 mutex_exit(&msp
->ms_lock
);
3783 * Free the block represented by the given DVA.
3786 metaslab_free_dva(spa_t
*spa
, const dva_t
*dva
, boolean_t checkpoint
)
3788 uint64_t vdev
= DVA_GET_VDEV(dva
);
3789 uint64_t offset
= DVA_GET_OFFSET(dva
);
3790 uint64_t size
= DVA_GET_ASIZE(dva
);
3791 vdev_t
*vd
= vdev_lookup_top(spa
, vdev
);
3793 ASSERT(DVA_IS_VALID(dva
));
3794 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
3796 if (DVA_GET_GANG(dva
)) {
3797 size
= vdev_psize_to_asize(vd
, SPA_GANGBLOCKSIZE
);
3800 metaslab_free_impl(vd
, offset
, size
, checkpoint
);
3804 * Reserve some allocation slots. The reservation system must be called
3805 * before we call into the allocator. If there aren't any available slots
3806 * then the I/O will be throttled until an I/O completes and its slots are
3807 * freed up. The function returns true if it was successful in placing
3811 metaslab_class_throttle_reserve(metaslab_class_t
*mc
, int slots
, int allocator
,
3812 zio_t
*zio
, int flags
)
3814 uint64_t available_slots
= 0;
3815 boolean_t slot_reserved
= B_FALSE
;
3816 uint64_t max
= mc
->mc_alloc_max_slots
[allocator
];
3818 ASSERT(mc
->mc_alloc_throttle_enabled
);
3819 mutex_enter(&mc
->mc_lock
);
3821 uint64_t reserved_slots
=
3822 refcount_count(&mc
->mc_alloc_slots
[allocator
]);
3823 if (reserved_slots
< max
)
3824 available_slots
= max
- reserved_slots
;
3826 if (slots
<= available_slots
|| GANG_ALLOCATION(flags
)) {
3828 * We reserve the slots individually so that we can unreserve
3829 * them individually when an I/O completes.
3831 for (int d
= 0; d
< slots
; d
++) {
3833 refcount_add(&mc
->mc_alloc_slots
[allocator
],
3836 zio
->io_flags
|= ZIO_FLAG_IO_ALLOCATING
;
3837 slot_reserved
= B_TRUE
;
3840 mutex_exit(&mc
->mc_lock
);
3841 return (slot_reserved
);
3845 metaslab_class_throttle_unreserve(metaslab_class_t
*mc
, int slots
,
3846 int allocator
, zio_t
*zio
)
3848 ASSERT(mc
->mc_alloc_throttle_enabled
);
3849 mutex_enter(&mc
->mc_lock
);
3850 for (int d
= 0; d
< slots
; d
++) {
3851 (void) refcount_remove(&mc
->mc_alloc_slots
[allocator
],
3854 mutex_exit(&mc
->mc_lock
);
3858 metaslab_claim_concrete(vdev_t
*vd
, uint64_t offset
, uint64_t size
,
3862 spa_t
*spa
= vd
->vdev_spa
;
3865 if (offset
>> vd
->vdev_ms_shift
>= vd
->vdev_ms_count
)
3868 ASSERT3P(vd
->vdev_ms
, !=, NULL
);
3869 msp
= vd
->vdev_ms
[offset
>> vd
->vdev_ms_shift
];
3871 mutex_enter(&msp
->ms_lock
);
3873 if ((txg
!= 0 && spa_writeable(spa
)) || !msp
->ms_loaded
)
3874 error
= metaslab_activate(msp
, 0, METASLAB_WEIGHT_CLAIM
);
3877 !range_tree_contains(msp
->ms_allocatable
, offset
, size
))
3878 error
= SET_ERROR(ENOENT
);
3880 if (error
|| txg
== 0) { /* txg == 0 indicates dry run */
3881 mutex_exit(&msp
->ms_lock
);
3885 VERIFY(!msp
->ms_condensing
);
3886 VERIFY0(P2PHASE(offset
, 1ULL << vd
->vdev_ashift
));
3887 VERIFY0(P2PHASE(size
, 1ULL << vd
->vdev_ashift
));
3888 VERIFY3U(range_tree_space(msp
->ms_allocatable
) - size
, <=,
3890 range_tree_remove(msp
->ms_allocatable
, offset
, size
);
3892 if (spa_writeable(spa
)) { /* don't dirty if we're zdb(1M) */
3893 if (range_tree_is_empty(msp
->ms_allocating
[txg
& TXG_MASK
]))
3894 vdev_dirty(vd
, VDD_METASLAB
, msp
, txg
);
3895 range_tree_add(msp
->ms_allocating
[txg
& TXG_MASK
],
3899 mutex_exit(&msp
->ms_lock
);
3904 typedef struct metaslab_claim_cb_arg_t
{
3907 } metaslab_claim_cb_arg_t
;
3911 metaslab_claim_impl_cb(uint64_t inner_offset
, vdev_t
*vd
, uint64_t offset
,
3912 uint64_t size
, void *arg
)
3914 metaslab_claim_cb_arg_t
*mcca_arg
= arg
;
3916 if (mcca_arg
->mcca_error
== 0) {
3917 mcca_arg
->mcca_error
= metaslab_claim_concrete(vd
, offset
,
3918 size
, mcca_arg
->mcca_txg
);
3923 metaslab_claim_impl(vdev_t
*vd
, uint64_t offset
, uint64_t size
, uint64_t txg
)
3925 if (vd
->vdev_ops
->vdev_op_remap
!= NULL
) {
3926 metaslab_claim_cb_arg_t arg
;
3929 * Only zdb(1M) can claim on indirect vdevs. This is used
3930 * to detect leaks of mapped space (that are not accounted
3931 * for in the obsolete counts, spacemap, or bpobj).
3933 ASSERT(!spa_writeable(vd
->vdev_spa
));
3937 vd
->vdev_ops
->vdev_op_remap(vd
, offset
, size
,
3938 metaslab_claim_impl_cb
, &arg
);
3940 if (arg
.mcca_error
== 0) {
3941 arg
.mcca_error
= metaslab_claim_concrete(vd
,
3944 return (arg
.mcca_error
);
3946 return (metaslab_claim_concrete(vd
, offset
, size
, txg
));
3951 * Intent log support: upon opening the pool after a crash, notify the SPA
3952 * of blocks that the intent log has allocated for immediate write, but
3953 * which are still considered free by the SPA because the last transaction
3954 * group didn't commit yet.
3957 metaslab_claim_dva(spa_t
*spa
, const dva_t
*dva
, uint64_t txg
)
3959 uint64_t vdev
= DVA_GET_VDEV(dva
);
3960 uint64_t offset
= DVA_GET_OFFSET(dva
);
3961 uint64_t size
= DVA_GET_ASIZE(dva
);
3964 if ((vd
= vdev_lookup_top(spa
, vdev
)) == NULL
) {
3965 return (SET_ERROR(ENXIO
));
3968 ASSERT(DVA_IS_VALID(dva
));
3970 if (DVA_GET_GANG(dva
))
3971 size
= vdev_psize_to_asize(vd
, SPA_GANGBLOCKSIZE
);
3973 return (metaslab_claim_impl(vd
, offset
, size
, txg
));
3977 metaslab_alloc(spa_t
*spa
, metaslab_class_t
*mc
, uint64_t psize
, blkptr_t
*bp
,
3978 int ndvas
, uint64_t txg
, blkptr_t
*hintbp
, int flags
,
3979 zio_alloc_list_t
*zal
, zio_t
*zio
, int allocator
)
3981 dva_t
*dva
= bp
->blk_dva
;
3982 dva_t
*hintdva
= hintbp
->blk_dva
;
3985 ASSERT(bp
->blk_birth
== 0);
3986 ASSERT(BP_PHYSICAL_BIRTH(bp
) == 0);
3988 spa_config_enter(spa
, SCL_ALLOC
, FTAG
, RW_READER
);
3990 if (mc
->mc_rotor
== NULL
) { /* no vdevs in this class */
3991 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
3992 return (SET_ERROR(ENOSPC
));
3995 ASSERT(ndvas
> 0 && ndvas
<= spa_max_replication(spa
));
3996 ASSERT(BP_GET_NDVAS(bp
) == 0);
3997 ASSERT(hintbp
== NULL
|| ndvas
<= BP_GET_NDVAS(hintbp
));
3998 ASSERT3P(zal
, !=, NULL
);
4000 for (int d
= 0; d
< ndvas
; d
++) {
4001 error
= metaslab_alloc_dva(spa
, mc
, psize
, dva
, d
, hintdva
,
4002 txg
, flags
, zal
, allocator
);
4004 for (d
--; d
>= 0; d
--) {
4005 metaslab_unalloc_dva(spa
, &dva
[d
], txg
);
4006 metaslab_group_alloc_decrement(spa
,
4007 DVA_GET_VDEV(&dva
[d
]), zio
, flags
,
4008 allocator
, B_FALSE
);
4009 bzero(&dva
[d
], sizeof (dva_t
));
4011 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
4015 * Update the metaslab group's queue depth
4016 * based on the newly allocated dva.
4018 metaslab_group_alloc_increment(spa
,
4019 DVA_GET_VDEV(&dva
[d
]), zio
, flags
, allocator
);
4024 ASSERT(BP_GET_NDVAS(bp
) == ndvas
);
4026 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
4028 BP_SET_BIRTH(bp
, txg
, 0);
4034 metaslab_free(spa_t
*spa
, const blkptr_t
*bp
, uint64_t txg
, boolean_t now
)
4036 const dva_t
*dva
= bp
->blk_dva
;
4037 int ndvas
= BP_GET_NDVAS(bp
);
4039 ASSERT(!BP_IS_HOLE(bp
));
4040 ASSERT(!now
|| bp
->blk_birth
>= spa_syncing_txg(spa
));
4043 * If we have a checkpoint for the pool we need to make sure that
4044 * the blocks that we free that are part of the checkpoint won't be
4045 * reused until the checkpoint is discarded or we revert to it.
4047 * The checkpoint flag is passed down the metaslab_free code path
4048 * and is set whenever we want to add a block to the checkpoint's
4049 * accounting. That is, we "checkpoint" blocks that existed at the
4050 * time the checkpoint was created and are therefore referenced by
4051 * the checkpointed uberblock.
4053 * Note that, we don't checkpoint any blocks if the current
4054 * syncing txg <= spa_checkpoint_txg. We want these frees to sync
4055 * normally as they will be referenced by the checkpointed uberblock.
4057 boolean_t checkpoint
= B_FALSE
;
4058 if (bp
->blk_birth
<= spa
->spa_checkpoint_txg
&&
4059 spa_syncing_txg(spa
) > spa
->spa_checkpoint_txg
) {
4061 * At this point, if the block is part of the checkpoint
4062 * there is no way it was created in the current txg.
4065 ASSERT3U(spa_syncing_txg(spa
), ==, txg
);
4066 checkpoint
= B_TRUE
;
4069 spa_config_enter(spa
, SCL_FREE
, FTAG
, RW_READER
);
4071 for (int d
= 0; d
< ndvas
; d
++) {
4073 metaslab_unalloc_dva(spa
, &dva
[d
], txg
);
4075 ASSERT3U(txg
, ==, spa_syncing_txg(spa
));
4076 metaslab_free_dva(spa
, &dva
[d
], checkpoint
);
4080 spa_config_exit(spa
, SCL_FREE
, FTAG
);
4084 metaslab_claim(spa_t
*spa
, const blkptr_t
*bp
, uint64_t txg
)
4086 const dva_t
*dva
= bp
->blk_dva
;
4087 int ndvas
= BP_GET_NDVAS(bp
);
4090 ASSERT(!BP_IS_HOLE(bp
));
4094 * First do a dry run to make sure all DVAs are claimable,
4095 * so we don't have to unwind from partial failures below.
4097 if ((error
= metaslab_claim(spa
, bp
, 0)) != 0)
4101 spa_config_enter(spa
, SCL_ALLOC
, FTAG
, RW_READER
);
4103 for (int d
= 0; d
< ndvas
; d
++)
4104 if ((error
= metaslab_claim_dva(spa
, &dva
[d
], txg
)) != 0)
4107 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
4109 ASSERT(error
== 0 || txg
== 0);
4115 metaslab_fastwrite_mark(spa_t
*spa
, const blkptr_t
*bp
)
4117 const dva_t
*dva
= bp
->blk_dva
;
4118 int ndvas
= BP_GET_NDVAS(bp
);
4119 uint64_t psize
= BP_GET_PSIZE(bp
);
4123 ASSERT(!BP_IS_HOLE(bp
));
4124 ASSERT(!BP_IS_EMBEDDED(bp
));
4127 spa_config_enter(spa
, SCL_VDEV
, FTAG
, RW_READER
);
4129 for (d
= 0; d
< ndvas
; d
++) {
4130 if ((vd
= vdev_lookup_top(spa
, DVA_GET_VDEV(&dva
[d
]))) == NULL
)
4132 atomic_add_64(&vd
->vdev_pending_fastwrite
, psize
);
4135 spa_config_exit(spa
, SCL_VDEV
, FTAG
);
4139 metaslab_fastwrite_unmark(spa_t
*spa
, const blkptr_t
*bp
)
4141 const dva_t
*dva
= bp
->blk_dva
;
4142 int ndvas
= BP_GET_NDVAS(bp
);
4143 uint64_t psize
= BP_GET_PSIZE(bp
);
4147 ASSERT(!BP_IS_HOLE(bp
));
4148 ASSERT(!BP_IS_EMBEDDED(bp
));
4151 spa_config_enter(spa
, SCL_VDEV
, FTAG
, RW_READER
);
4153 for (d
= 0; d
< ndvas
; d
++) {
4154 if ((vd
= vdev_lookup_top(spa
, DVA_GET_VDEV(&dva
[d
]))) == NULL
)
4156 ASSERT3U(vd
->vdev_pending_fastwrite
, >=, psize
);
4157 atomic_sub_64(&vd
->vdev_pending_fastwrite
, psize
);
4160 spa_config_exit(spa
, SCL_VDEV
, FTAG
);
4165 metaslab_check_free_impl_cb(uint64_t inner
, vdev_t
*vd
, uint64_t offset
,
4166 uint64_t size
, void *arg
)
4168 if (vd
->vdev_ops
== &vdev_indirect_ops
)
4171 metaslab_check_free_impl(vd
, offset
, size
);
4175 metaslab_check_free_impl(vdev_t
*vd
, uint64_t offset
, uint64_t size
)
4178 ASSERTV(spa_t
*spa
= vd
->vdev_spa
);
4180 if ((zfs_flags
& ZFS_DEBUG_ZIO_FREE
) == 0)
4183 if (vd
->vdev_ops
->vdev_op_remap
!= NULL
) {
4184 vd
->vdev_ops
->vdev_op_remap(vd
, offset
, size
,
4185 metaslab_check_free_impl_cb
, NULL
);
4189 ASSERT(vdev_is_concrete(vd
));
4190 ASSERT3U(offset
>> vd
->vdev_ms_shift
, <, vd
->vdev_ms_count
);
4191 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
4193 msp
= vd
->vdev_ms
[offset
>> vd
->vdev_ms_shift
];
4195 mutex_enter(&msp
->ms_lock
);
4197 range_tree_verify(msp
->ms_allocatable
, offset
, size
);
4199 range_tree_verify(msp
->ms_freeing
, offset
, size
);
4200 range_tree_verify(msp
->ms_checkpointing
, offset
, size
);
4201 range_tree_verify(msp
->ms_freed
, offset
, size
);
4202 for (int j
= 0; j
< TXG_DEFER_SIZE
; j
++)
4203 range_tree_verify(msp
->ms_defer
[j
], offset
, size
);
4204 mutex_exit(&msp
->ms_lock
);
4208 metaslab_check_free(spa_t
*spa
, const blkptr_t
*bp
)
4210 if ((zfs_flags
& ZFS_DEBUG_ZIO_FREE
) == 0)
4213 spa_config_enter(spa
, SCL_VDEV
, FTAG
, RW_READER
);
4214 for (int i
= 0; i
< BP_GET_NDVAS(bp
); i
++) {
4215 uint64_t vdev
= DVA_GET_VDEV(&bp
->blk_dva
[i
]);
4216 vdev_t
*vd
= vdev_lookup_top(spa
, vdev
);
4217 uint64_t offset
= DVA_GET_OFFSET(&bp
->blk_dva
[i
]);
4218 uint64_t size
= DVA_GET_ASIZE(&bp
->blk_dva
[i
]);
4220 if (DVA_GET_GANG(&bp
->blk_dva
[i
]))
4221 size
= vdev_psize_to_asize(vd
, SPA_GANGBLOCKSIZE
);
4223 ASSERT3P(vd
, !=, NULL
);
4225 metaslab_check_free_impl(vd
, offset
, size
);
4227 spa_config_exit(spa
, SCL_VDEV
, FTAG
);
4230 #if defined(_KERNEL)
4232 module_param(metaslab_aliquot
, ulong
, 0644);
4233 MODULE_PARM_DESC(metaslab_aliquot
,
4234 "allocation granularity (a.k.a. stripe size)");
4236 module_param(metaslab_debug_load
, int, 0644);
4237 MODULE_PARM_DESC(metaslab_debug_load
,
4238 "load all metaslabs when pool is first opened");
4240 module_param(metaslab_debug_unload
, int, 0644);
4241 MODULE_PARM_DESC(metaslab_debug_unload
,
4242 "prevent metaslabs from being unloaded");
4244 module_param(metaslab_preload_enabled
, int, 0644);
4245 MODULE_PARM_DESC(metaslab_preload_enabled
,
4246 "preload potential metaslabs during reassessment");
4248 module_param(zfs_mg_noalloc_threshold
, int, 0644);
4249 MODULE_PARM_DESC(zfs_mg_noalloc_threshold
,
4250 "percentage of free space for metaslab group to allow allocation");
4252 module_param(zfs_mg_fragmentation_threshold
, int, 0644);
4253 MODULE_PARM_DESC(zfs_mg_fragmentation_threshold
,
4254 "fragmentation for metaslab group to allow allocation");
4256 module_param(zfs_metaslab_fragmentation_threshold
, int, 0644);
4257 MODULE_PARM_DESC(zfs_metaslab_fragmentation_threshold
,
4258 "fragmentation for metaslab to allow allocation");
4260 module_param(metaslab_fragmentation_factor_enabled
, int, 0644);
4261 MODULE_PARM_DESC(metaslab_fragmentation_factor_enabled
,
4262 "use the fragmentation metric to prefer less fragmented metaslabs");
4264 module_param(metaslab_lba_weighting_enabled
, int, 0644);
4265 MODULE_PARM_DESC(metaslab_lba_weighting_enabled
,
4266 "prefer metaslabs with lower LBAs");
4268 module_param(metaslab_bias_enabled
, int, 0644);
4269 MODULE_PARM_DESC(metaslab_bias_enabled
,
4270 "enable metaslab group biasing");
4272 module_param(zfs_metaslab_segment_weight_enabled
, int, 0644);
4273 MODULE_PARM_DESC(zfs_metaslab_segment_weight_enabled
,
4274 "enable segment-based metaslab selection");
4276 module_param(zfs_metaslab_switch_threshold
, int, 0644);
4277 MODULE_PARM_DESC(zfs_metaslab_switch_threshold
,
4278 "segment-based metaslab selection maximum buckets before switching");
4281 module_param(metaslab_force_ganging
, ulong
, 0644);
4282 MODULE_PARM_DESC(metaslab_force_ganging
,
4283 "blocks larger than this size are forced to be gang blocks");