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, 2018 by Delphix. All rights reserved.
24 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
25 * Copyright (c) 2014 Integros [integros.com]
28 #include <sys/zfs_context.h>
30 #include <sys/dmu_tx.h>
31 #include <sys/space_map.h>
32 #include <sys/metaslab_impl.h>
33 #include <sys/vdev_impl.h>
35 #include <sys/spa_impl.h>
36 #include <sys/zfeature.h>
37 #include <sys/vdev_indirect_mapping.h>
40 #define GANG_ALLOCATION(flags) \
41 ((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER))
43 uint64_t metaslab_aliquot
= 512ULL << 10;
44 uint64_t metaslab_force_ganging
= SPA_MAXBLOCKSIZE
+ 1; /* force gang blocks */
47 * Since we can touch multiple metaslabs (and their respective space maps)
48 * with each transaction group, we benefit from having a smaller space map
49 * block size since it allows us to issue more I/O operations scattered
52 int zfs_metaslab_sm_blksz
= (1 << 12);
55 * The in-core space map representation is more compact than its on-disk form.
56 * The zfs_condense_pct determines how much more compact the in-core
57 * space map representation must be before we compact it on-disk.
58 * Values should be greater than or equal to 100.
60 int zfs_condense_pct
= 200;
63 * Condensing a metaslab is not guaranteed to actually reduce the amount of
64 * space used on disk. In particular, a space map uses data in increments of
65 * MAX(1 << ashift, space_map_blksize), so a metaslab might use the
66 * same number of blocks after condensing. Since the goal of condensing is to
67 * reduce the number of IOPs required to read the space map, we only want to
68 * condense when we can be sure we will reduce the number of blocks used by the
69 * space map. Unfortunately, we cannot precisely compute whether or not this is
70 * the case in metaslab_should_condense since we are holding ms_lock. Instead,
71 * we apply the following heuristic: do not condense a spacemap unless the
72 * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
75 int zfs_metaslab_condense_block_threshold
= 4;
78 * The zfs_mg_noalloc_threshold defines which metaslab groups should
79 * be eligible for allocation. The value is defined as a percentage of
80 * free space. Metaslab groups that have more free space than
81 * zfs_mg_noalloc_threshold are always eligible for allocations. Once
82 * a metaslab group's free space is less than or equal to the
83 * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
84 * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
85 * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
86 * groups are allowed to accept allocations. Gang blocks are always
87 * eligible to allocate on any metaslab group. The default value of 0 means
88 * no metaslab group will be excluded based on this criterion.
90 int zfs_mg_noalloc_threshold
= 0;
93 * Metaslab groups are considered eligible for allocations if their
94 * fragmenation metric (measured as a percentage) is less than or equal to
95 * zfs_mg_fragmentation_threshold. If a metaslab group exceeds this threshold
96 * then it will be skipped unless all metaslab groups within the metaslab
97 * class have also crossed this threshold.
99 int zfs_mg_fragmentation_threshold
= 85;
102 * Allow metaslabs to keep their active state as long as their fragmentation
103 * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
104 * active metaslab that exceeds this threshold will no longer keep its active
105 * status allowing better metaslabs to be selected.
107 int zfs_metaslab_fragmentation_threshold
= 70;
110 * When set will load all metaslabs when pool is first opened.
112 int metaslab_debug_load
= 0;
115 * When set will prevent metaslabs from being unloaded.
117 int metaslab_debug_unload
= 0;
120 * Minimum size which forces the dynamic allocator to change
121 * it's allocation strategy. Once the space map cannot satisfy
122 * an allocation of this size then it switches to using more
123 * aggressive strategy (i.e search by size rather than offset).
125 uint64_t metaslab_df_alloc_threshold
= SPA_OLD_MAXBLOCKSIZE
;
128 * The minimum free space, in percent, which must be available
129 * in a space map to continue allocations in a first-fit fashion.
130 * Once the space map's free space drops below this level we dynamically
131 * switch to using best-fit allocations.
133 int metaslab_df_free_pct
= 4;
136 * A metaslab is considered "free" if it contains a contiguous
137 * segment which is greater than metaslab_min_alloc_size.
139 uint64_t metaslab_min_alloc_size
= DMU_MAX_ACCESS
;
142 * Percentage of all cpus that can be used by the metaslab taskq.
144 int metaslab_load_pct
= 50;
147 * Determines how many txgs a metaslab may remain loaded without having any
148 * allocations from it. As long as a metaslab continues to be used we will
151 int metaslab_unload_delay
= TXG_SIZE
* 2;
154 * Max number of metaslabs per group to preload.
156 int metaslab_preload_limit
= SPA_DVAS_PER_BP
;
159 * Enable/disable preloading of metaslab.
161 boolean_t metaslab_preload_enabled
= B_TRUE
;
164 * Enable/disable fragmentation weighting on metaslabs.
166 boolean_t metaslab_fragmentation_factor_enabled
= B_TRUE
;
169 * Enable/disable lba weighting (i.e. outer tracks are given preference).
171 boolean_t metaslab_lba_weighting_enabled
= B_TRUE
;
174 * Enable/disable metaslab group biasing.
176 boolean_t metaslab_bias_enabled
= B_TRUE
;
179 * Enable/disable remapping of indirect DVAs to their concrete vdevs.
181 boolean_t zfs_remap_blkptr_enable
= B_TRUE
;
184 * Enable/disable segment-based metaslab selection.
186 boolean_t zfs_metaslab_segment_weight_enabled
= B_TRUE
;
189 * When using segment-based metaslab selection, we will continue
190 * allocating from the active metaslab until we have exhausted
191 * zfs_metaslab_switch_threshold of its buckets.
193 int zfs_metaslab_switch_threshold
= 2;
196 * Internal switch to enable/disable the metaslab allocation tracing
199 boolean_t metaslab_trace_enabled
= B_TRUE
;
202 * Maximum entries that the metaslab allocation tracing facility will keep
203 * in a given list when running in non-debug mode. We limit the number
204 * of entries in non-debug mode to prevent us from using up too much memory.
205 * The limit should be sufficiently large that we don't expect any allocation
206 * to every exceed this value. In debug mode, the system will panic if this
207 * limit is ever reached allowing for further investigation.
209 uint64_t metaslab_trace_max_entries
= 5000;
211 static uint64_t metaslab_weight(metaslab_t
*);
212 static void metaslab_set_fragmentation(metaslab_t
*);
213 static void metaslab_free_impl(vdev_t
*, uint64_t, uint64_t, boolean_t
);
214 static void metaslab_check_free_impl(vdev_t
*, uint64_t, uint64_t);
215 static void metaslab_passivate(metaslab_t
*msp
, uint64_t weight
);
216 static uint64_t metaslab_weight_from_range_tree(metaslab_t
*msp
);
218 kmem_cache_t
*metaslab_alloc_trace_cache
;
221 * ==========================================================================
223 * ==========================================================================
226 metaslab_class_create(spa_t
*spa
, metaslab_ops_t
*ops
)
228 metaslab_class_t
*mc
;
230 mc
= kmem_zalloc(sizeof (metaslab_class_t
), KM_SLEEP
);
235 mutex_init(&mc
->mc_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
236 mc
->mc_alloc_slots
= kmem_zalloc(spa
->spa_alloc_count
*
237 sizeof (refcount_t
), KM_SLEEP
);
238 mc
->mc_alloc_max_slots
= kmem_zalloc(spa
->spa_alloc_count
*
239 sizeof (uint64_t), KM_SLEEP
);
240 for (int i
= 0; i
< spa
->spa_alloc_count
; i
++)
241 refcount_create_tracked(&mc
->mc_alloc_slots
[i
]);
247 metaslab_class_destroy(metaslab_class_t
*mc
)
249 ASSERT(mc
->mc_rotor
== NULL
);
250 ASSERT(mc
->mc_alloc
== 0);
251 ASSERT(mc
->mc_deferred
== 0);
252 ASSERT(mc
->mc_space
== 0);
253 ASSERT(mc
->mc_dspace
== 0);
255 for (int i
= 0; i
< mc
->mc_spa
->spa_alloc_count
; i
++)
256 refcount_destroy(&mc
->mc_alloc_slots
[i
]);
257 kmem_free(mc
->mc_alloc_slots
, mc
->mc_spa
->spa_alloc_count
*
258 sizeof (refcount_t
));
259 kmem_free(mc
->mc_alloc_max_slots
, mc
->mc_spa
->spa_alloc_count
*
261 mutex_destroy(&mc
->mc_lock
);
262 kmem_free(mc
, sizeof (metaslab_class_t
));
266 metaslab_class_validate(metaslab_class_t
*mc
)
268 metaslab_group_t
*mg
;
272 * Must hold one of the spa_config locks.
274 ASSERT(spa_config_held(mc
->mc_spa
, SCL_ALL
, RW_READER
) ||
275 spa_config_held(mc
->mc_spa
, SCL_ALL
, RW_WRITER
));
277 if ((mg
= mc
->mc_rotor
) == NULL
)
282 ASSERT(vd
->vdev_mg
!= NULL
);
283 ASSERT3P(vd
->vdev_top
, ==, vd
);
284 ASSERT3P(mg
->mg_class
, ==, mc
);
285 ASSERT3P(vd
->vdev_ops
, !=, &vdev_hole_ops
);
286 } while ((mg
= mg
->mg_next
) != mc
->mc_rotor
);
292 metaslab_class_space_update(metaslab_class_t
*mc
, int64_t alloc_delta
,
293 int64_t defer_delta
, int64_t space_delta
, int64_t dspace_delta
)
295 atomic_add_64(&mc
->mc_alloc
, alloc_delta
);
296 atomic_add_64(&mc
->mc_deferred
, defer_delta
);
297 atomic_add_64(&mc
->mc_space
, space_delta
);
298 atomic_add_64(&mc
->mc_dspace
, dspace_delta
);
302 metaslab_class_get_alloc(metaslab_class_t
*mc
)
304 return (mc
->mc_alloc
);
308 metaslab_class_get_deferred(metaslab_class_t
*mc
)
310 return (mc
->mc_deferred
);
314 metaslab_class_get_space(metaslab_class_t
*mc
)
316 return (mc
->mc_space
);
320 metaslab_class_get_dspace(metaslab_class_t
*mc
)
322 return (spa_deflate(mc
->mc_spa
) ? mc
->mc_dspace
: mc
->mc_space
);
326 metaslab_class_histogram_verify(metaslab_class_t
*mc
)
328 vdev_t
*rvd
= mc
->mc_spa
->spa_root_vdev
;
332 if ((zfs_flags
& ZFS_DEBUG_HISTOGRAM_VERIFY
) == 0)
335 mc_hist
= kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE
,
338 for (int c
= 0; c
< rvd
->vdev_children
; c
++) {
339 vdev_t
*tvd
= rvd
->vdev_child
[c
];
340 metaslab_group_t
*mg
= tvd
->vdev_mg
;
343 * Skip any holes, uninitialized top-levels, or
344 * vdevs that are not in this metalab class.
346 if (!vdev_is_concrete(tvd
) || tvd
->vdev_ms_shift
== 0 ||
347 mg
->mg_class
!= mc
) {
351 for (i
= 0; i
< RANGE_TREE_HISTOGRAM_SIZE
; i
++)
352 mc_hist
[i
] += mg
->mg_histogram
[i
];
355 for (i
= 0; i
< RANGE_TREE_HISTOGRAM_SIZE
; i
++)
356 VERIFY3U(mc_hist
[i
], ==, mc
->mc_histogram
[i
]);
358 kmem_free(mc_hist
, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE
);
362 * Calculate the metaslab class's fragmentation metric. The metric
363 * is weighted based on the space contribution of each metaslab group.
364 * The return value will be a number between 0 and 100 (inclusive), or
365 * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
366 * zfs_frag_table for more information about the metric.
369 metaslab_class_fragmentation(metaslab_class_t
*mc
)
371 vdev_t
*rvd
= mc
->mc_spa
->spa_root_vdev
;
372 uint64_t fragmentation
= 0;
374 spa_config_enter(mc
->mc_spa
, SCL_VDEV
, FTAG
, RW_READER
);
376 for (int c
= 0; c
< rvd
->vdev_children
; c
++) {
377 vdev_t
*tvd
= rvd
->vdev_child
[c
];
378 metaslab_group_t
*mg
= tvd
->vdev_mg
;
381 * Skip any holes, uninitialized top-levels,
382 * or vdevs that are not in this metalab class.
384 if (!vdev_is_concrete(tvd
) || tvd
->vdev_ms_shift
== 0 ||
385 mg
->mg_class
!= mc
) {
390 * If a metaslab group does not contain a fragmentation
391 * metric then just bail out.
393 if (mg
->mg_fragmentation
== ZFS_FRAG_INVALID
) {
394 spa_config_exit(mc
->mc_spa
, SCL_VDEV
, FTAG
);
395 return (ZFS_FRAG_INVALID
);
399 * Determine how much this metaslab_group is contributing
400 * to the overall pool fragmentation metric.
402 fragmentation
+= mg
->mg_fragmentation
*
403 metaslab_group_get_space(mg
);
405 fragmentation
/= metaslab_class_get_space(mc
);
407 ASSERT3U(fragmentation
, <=, 100);
408 spa_config_exit(mc
->mc_spa
, SCL_VDEV
, FTAG
);
409 return (fragmentation
);
413 * Calculate the amount of expandable space that is available in
414 * this metaslab class. If a device is expanded then its expandable
415 * space will be the amount of allocatable space that is currently not
416 * part of this metaslab class.
419 metaslab_class_expandable_space(metaslab_class_t
*mc
)
421 vdev_t
*rvd
= mc
->mc_spa
->spa_root_vdev
;
424 spa_config_enter(mc
->mc_spa
, SCL_VDEV
, FTAG
, RW_READER
);
425 for (int c
= 0; c
< rvd
->vdev_children
; c
++) {
427 vdev_t
*tvd
= rvd
->vdev_child
[c
];
428 metaslab_group_t
*mg
= tvd
->vdev_mg
;
430 if (!vdev_is_concrete(tvd
) || tvd
->vdev_ms_shift
== 0 ||
431 mg
->mg_class
!= mc
) {
436 * Calculate if we have enough space to add additional
437 * metaslabs. We report the expandable space in terms
438 * of the metaslab size since that's the unit of expansion.
439 * Adjust by efi system partition size.
441 tspace
= tvd
->vdev_max_asize
- tvd
->vdev_asize
;
442 if (tspace
> mc
->mc_spa
->spa_bootsize
) {
443 tspace
-= mc
->mc_spa
->spa_bootsize
;
445 space
+= P2ALIGN(tspace
, 1ULL << tvd
->vdev_ms_shift
);
447 spa_config_exit(mc
->mc_spa
, SCL_VDEV
, FTAG
);
452 metaslab_compare(const void *x1
, const void *x2
)
454 const metaslab_t
*m1
= x1
;
455 const metaslab_t
*m2
= x2
;
459 if (m1
->ms_allocator
!= -1 && m1
->ms_primary
)
461 else if (m1
->ms_allocator
!= -1 && !m1
->ms_primary
)
463 if (m2
->ms_allocator
!= -1 && m2
->ms_primary
)
465 else if (m2
->ms_allocator
!= -1 && !m2
->ms_primary
)
469 * Sort inactive metaslabs first, then primaries, then secondaries. When
470 * selecting a metaslab to allocate from, an allocator first tries its
471 * primary, then secondary active metaslab. If it doesn't have active
472 * metaslabs, or can't allocate from them, it searches for an inactive
473 * metaslab to activate. If it can't find a suitable one, it will steal
474 * a primary or secondary metaslab from another allocator.
481 if (m1
->ms_weight
< m2
->ms_weight
)
483 if (m1
->ms_weight
> m2
->ms_weight
)
487 * If the weights are identical, use the offset to force uniqueness.
489 if (m1
->ms_start
< m2
->ms_start
)
491 if (m1
->ms_start
> m2
->ms_start
)
494 ASSERT3P(m1
, ==, m2
);
500 * Verify that the space accounting on disk matches the in-core range_trees.
503 metaslab_verify_space(metaslab_t
*msp
, uint64_t txg
)
505 spa_t
*spa
= msp
->ms_group
->mg_vd
->vdev_spa
;
506 uint64_t allocated
= 0;
507 uint64_t sm_free_space
, msp_free_space
;
509 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
511 if ((zfs_flags
& ZFS_DEBUG_METASLAB_VERIFY
) == 0)
515 * We can only verify the metaslab space when we're called
516 * from syncing context with a loaded metaslab that has an allocated
517 * space map. Calling this in non-syncing context does not
518 * provide a consistent view of the metaslab since we're performing
519 * allocations in the future.
521 if (txg
!= spa_syncing_txg(spa
) || msp
->ms_sm
== NULL
||
525 sm_free_space
= msp
->ms_size
- space_map_allocated(msp
->ms_sm
) -
526 space_map_alloc_delta(msp
->ms_sm
);
529 * Account for future allocations since we would have already
530 * deducted that space from the ms_freetree.
532 for (int t
= 0; t
< TXG_CONCURRENT_STATES
; t
++) {
534 range_tree_space(msp
->ms_allocating
[(txg
+ t
) & TXG_MASK
]);
537 msp_free_space
= range_tree_space(msp
->ms_allocatable
) + allocated
+
538 msp
->ms_deferspace
+ range_tree_space(msp
->ms_freed
);
540 VERIFY3U(sm_free_space
, ==, msp_free_space
);
544 * ==========================================================================
546 * ==========================================================================
549 * Update the allocatable flag and the metaslab group's capacity.
550 * The allocatable flag is set to true if the capacity is below
551 * the zfs_mg_noalloc_threshold or has a fragmentation value that is
552 * greater than zfs_mg_fragmentation_threshold. If a metaslab group
553 * transitions from allocatable to non-allocatable or vice versa then the
554 * metaslab group's class is updated to reflect the transition.
557 metaslab_group_alloc_update(metaslab_group_t
*mg
)
559 vdev_t
*vd
= mg
->mg_vd
;
560 metaslab_class_t
*mc
= mg
->mg_class
;
561 vdev_stat_t
*vs
= &vd
->vdev_stat
;
562 boolean_t was_allocatable
;
563 boolean_t was_initialized
;
565 ASSERT(vd
== vd
->vdev_top
);
566 ASSERT3U(spa_config_held(mc
->mc_spa
, SCL_ALLOC
, RW_READER
), ==,
569 mutex_enter(&mg
->mg_lock
);
570 was_allocatable
= mg
->mg_allocatable
;
571 was_initialized
= mg
->mg_initialized
;
573 mg
->mg_free_capacity
= ((vs
->vs_space
- vs
->vs_alloc
) * 100) /
576 mutex_enter(&mc
->mc_lock
);
579 * If the metaslab group was just added then it won't
580 * have any space until we finish syncing out this txg.
581 * At that point we will consider it initialized and available
582 * for allocations. We also don't consider non-activated
583 * metaslab groups (e.g. vdevs that are in the middle of being removed)
584 * to be initialized, because they can't be used for allocation.
586 mg
->mg_initialized
= metaslab_group_initialized(mg
);
587 if (!was_initialized
&& mg
->mg_initialized
) {
589 } else if (was_initialized
&& !mg
->mg_initialized
) {
590 ASSERT3U(mc
->mc_groups
, >, 0);
593 if (mg
->mg_initialized
)
594 mg
->mg_no_free_space
= B_FALSE
;
597 * A metaslab group is considered allocatable if it has plenty
598 * of free space or is not heavily fragmented. We only take
599 * fragmentation into account if the metaslab group has a valid
600 * fragmentation metric (i.e. a value between 0 and 100).
602 mg
->mg_allocatable
= (mg
->mg_activation_count
> 0 &&
603 mg
->mg_free_capacity
> zfs_mg_noalloc_threshold
&&
604 (mg
->mg_fragmentation
== ZFS_FRAG_INVALID
||
605 mg
->mg_fragmentation
<= zfs_mg_fragmentation_threshold
));
608 * The mc_alloc_groups maintains a count of the number of
609 * groups in this metaslab class that are still above the
610 * zfs_mg_noalloc_threshold. This is used by the allocating
611 * threads to determine if they should avoid allocations to
612 * a given group. The allocator will avoid allocations to a group
613 * if that group has reached or is below the zfs_mg_noalloc_threshold
614 * and there are still other groups that are above the threshold.
615 * When a group transitions from allocatable to non-allocatable or
616 * vice versa we update the metaslab class to reflect that change.
617 * When the mc_alloc_groups value drops to 0 that means that all
618 * groups have reached the zfs_mg_noalloc_threshold making all groups
619 * eligible for allocations. This effectively means that all devices
620 * are balanced again.
622 if (was_allocatable
&& !mg
->mg_allocatable
)
623 mc
->mc_alloc_groups
--;
624 else if (!was_allocatable
&& mg
->mg_allocatable
)
625 mc
->mc_alloc_groups
++;
626 mutex_exit(&mc
->mc_lock
);
628 mutex_exit(&mg
->mg_lock
);
632 metaslab_group_create(metaslab_class_t
*mc
, vdev_t
*vd
, int allocators
)
634 metaslab_group_t
*mg
;
636 mg
= kmem_zalloc(sizeof (metaslab_group_t
), KM_SLEEP
);
637 mutex_init(&mg
->mg_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
638 mutex_init(&mg
->mg_ms_initialize_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
639 cv_init(&mg
->mg_ms_initialize_cv
, NULL
, CV_DEFAULT
, NULL
);
640 mg
->mg_primaries
= kmem_zalloc(allocators
* sizeof (metaslab_t
*),
642 mg
->mg_secondaries
= kmem_zalloc(allocators
* sizeof (metaslab_t
*),
644 avl_create(&mg
->mg_metaslab_tree
, metaslab_compare
,
645 sizeof (metaslab_t
), offsetof(struct metaslab
, ms_group_node
));
648 mg
->mg_activation_count
= 0;
649 mg
->mg_initialized
= B_FALSE
;
650 mg
->mg_no_free_space
= B_TRUE
;
651 mg
->mg_allocators
= allocators
;
653 mg
->mg_alloc_queue_depth
= kmem_zalloc(allocators
* sizeof (refcount_t
),
655 mg
->mg_cur_max_alloc_queue_depth
= kmem_zalloc(allocators
*
656 sizeof (uint64_t), KM_SLEEP
);
657 for (int i
= 0; i
< allocators
; i
++) {
658 refcount_create_tracked(&mg
->mg_alloc_queue_depth
[i
]);
659 mg
->mg_cur_max_alloc_queue_depth
[i
] = 0;
662 mg
->mg_taskq
= taskq_create("metaslab_group_taskq", metaslab_load_pct
,
663 minclsyspri
, 10, INT_MAX
, TASKQ_THREADS_CPU_PCT
);
669 metaslab_group_destroy(metaslab_group_t
*mg
)
671 ASSERT(mg
->mg_prev
== NULL
);
672 ASSERT(mg
->mg_next
== NULL
);
674 * We may have gone below zero with the activation count
675 * either because we never activated in the first place or
676 * because we're done, and possibly removing the vdev.
678 ASSERT(mg
->mg_activation_count
<= 0);
680 taskq_destroy(mg
->mg_taskq
);
681 avl_destroy(&mg
->mg_metaslab_tree
);
682 kmem_free(mg
->mg_primaries
, mg
->mg_allocators
* sizeof (metaslab_t
*));
683 kmem_free(mg
->mg_secondaries
, mg
->mg_allocators
*
684 sizeof (metaslab_t
*));
685 mutex_destroy(&mg
->mg_lock
);
686 mutex_destroy(&mg
->mg_ms_initialize_lock
);
687 cv_destroy(&mg
->mg_ms_initialize_cv
);
689 for (int i
= 0; i
< mg
->mg_allocators
; i
++) {
690 refcount_destroy(&mg
->mg_alloc_queue_depth
[i
]);
691 mg
->mg_cur_max_alloc_queue_depth
[i
] = 0;
693 kmem_free(mg
->mg_alloc_queue_depth
, mg
->mg_allocators
*
694 sizeof (refcount_t
));
695 kmem_free(mg
->mg_cur_max_alloc_queue_depth
, mg
->mg_allocators
*
698 kmem_free(mg
, sizeof (metaslab_group_t
));
702 metaslab_group_activate(metaslab_group_t
*mg
)
704 metaslab_class_t
*mc
= mg
->mg_class
;
705 metaslab_group_t
*mgprev
, *mgnext
;
707 ASSERT3U(spa_config_held(mc
->mc_spa
, SCL_ALLOC
, RW_WRITER
), !=, 0);
709 ASSERT(mc
->mc_rotor
!= mg
);
710 ASSERT(mg
->mg_prev
== NULL
);
711 ASSERT(mg
->mg_next
== NULL
);
712 ASSERT(mg
->mg_activation_count
<= 0);
714 if (++mg
->mg_activation_count
<= 0)
717 mg
->mg_aliquot
= metaslab_aliquot
* MAX(1, mg
->mg_vd
->vdev_children
);
718 metaslab_group_alloc_update(mg
);
720 if ((mgprev
= mc
->mc_rotor
) == NULL
) {
724 mgnext
= mgprev
->mg_next
;
725 mg
->mg_prev
= mgprev
;
726 mg
->mg_next
= mgnext
;
727 mgprev
->mg_next
= mg
;
728 mgnext
->mg_prev
= mg
;
734 * Passivate a metaslab group and remove it from the allocation rotor.
735 * Callers must hold both the SCL_ALLOC and SCL_ZIO lock prior to passivating
736 * a metaslab group. This function will momentarily drop spa_config_locks
737 * that are lower than the SCL_ALLOC lock (see comment below).
740 metaslab_group_passivate(metaslab_group_t
*mg
)
742 metaslab_class_t
*mc
= mg
->mg_class
;
743 spa_t
*spa
= mc
->mc_spa
;
744 metaslab_group_t
*mgprev
, *mgnext
;
745 int locks
= spa_config_held(spa
, SCL_ALL
, RW_WRITER
);
747 ASSERT3U(spa_config_held(spa
, SCL_ALLOC
| SCL_ZIO
, RW_WRITER
), ==,
748 (SCL_ALLOC
| SCL_ZIO
));
750 if (--mg
->mg_activation_count
!= 0) {
751 ASSERT(mc
->mc_rotor
!= mg
);
752 ASSERT(mg
->mg_prev
== NULL
);
753 ASSERT(mg
->mg_next
== NULL
);
754 ASSERT(mg
->mg_activation_count
< 0);
759 * The spa_config_lock is an array of rwlocks, ordered as
760 * follows (from highest to lowest):
761 * SCL_CONFIG > SCL_STATE > SCL_L2ARC > SCL_ALLOC >
762 * SCL_ZIO > SCL_FREE > SCL_VDEV
763 * (For more information about the spa_config_lock see spa_misc.c)
764 * The higher the lock, the broader its coverage. When we passivate
765 * a metaslab group, we must hold both the SCL_ALLOC and the SCL_ZIO
766 * config locks. However, the metaslab group's taskq might be trying
767 * to preload metaslabs so we must drop the SCL_ZIO lock and any
768 * lower locks to allow the I/O to complete. At a minimum,
769 * we continue to hold the SCL_ALLOC lock, which prevents any future
770 * allocations from taking place and any changes to the vdev tree.
772 spa_config_exit(spa
, locks
& ~(SCL_ZIO
- 1), spa
);
773 taskq_wait(mg
->mg_taskq
);
774 spa_config_enter(spa
, locks
& ~(SCL_ZIO
- 1), spa
, RW_WRITER
);
775 metaslab_group_alloc_update(mg
);
776 for (int i
= 0; i
< mg
->mg_allocators
; i
++) {
777 metaslab_t
*msp
= mg
->mg_primaries
[i
];
779 mutex_enter(&msp
->ms_lock
);
780 metaslab_passivate(msp
,
781 metaslab_weight_from_range_tree(msp
));
782 mutex_exit(&msp
->ms_lock
);
784 msp
= mg
->mg_secondaries
[i
];
786 mutex_enter(&msp
->ms_lock
);
787 metaslab_passivate(msp
,
788 metaslab_weight_from_range_tree(msp
));
789 mutex_exit(&msp
->ms_lock
);
793 mgprev
= mg
->mg_prev
;
794 mgnext
= mg
->mg_next
;
799 mc
->mc_rotor
= mgnext
;
800 mgprev
->mg_next
= mgnext
;
801 mgnext
->mg_prev
= mgprev
;
809 metaslab_group_initialized(metaslab_group_t
*mg
)
811 vdev_t
*vd
= mg
->mg_vd
;
812 vdev_stat_t
*vs
= &vd
->vdev_stat
;
814 return (vs
->vs_space
!= 0 && mg
->mg_activation_count
> 0);
818 metaslab_group_get_space(metaslab_group_t
*mg
)
820 return ((1ULL << mg
->mg_vd
->vdev_ms_shift
) * mg
->mg_vd
->vdev_ms_count
);
824 metaslab_group_histogram_verify(metaslab_group_t
*mg
)
827 vdev_t
*vd
= mg
->mg_vd
;
828 uint64_t ashift
= vd
->vdev_ashift
;
831 if ((zfs_flags
& ZFS_DEBUG_HISTOGRAM_VERIFY
) == 0)
834 mg_hist
= kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE
,
837 ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE
, >=,
838 SPACE_MAP_HISTOGRAM_SIZE
+ ashift
);
840 for (int m
= 0; m
< vd
->vdev_ms_count
; m
++) {
841 metaslab_t
*msp
= vd
->vdev_ms
[m
];
843 if (msp
->ms_sm
== NULL
)
846 for (i
= 0; i
< SPACE_MAP_HISTOGRAM_SIZE
; i
++)
847 mg_hist
[i
+ ashift
] +=
848 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
851 for (i
= 0; i
< RANGE_TREE_HISTOGRAM_SIZE
; i
++)
852 VERIFY3U(mg_hist
[i
], ==, mg
->mg_histogram
[i
]);
854 kmem_free(mg_hist
, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE
);
858 metaslab_group_histogram_add(metaslab_group_t
*mg
, metaslab_t
*msp
)
860 metaslab_class_t
*mc
= mg
->mg_class
;
861 uint64_t ashift
= mg
->mg_vd
->vdev_ashift
;
863 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
864 if (msp
->ms_sm
== NULL
)
867 mutex_enter(&mg
->mg_lock
);
868 for (int i
= 0; i
< SPACE_MAP_HISTOGRAM_SIZE
; i
++) {
869 mg
->mg_histogram
[i
+ ashift
] +=
870 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
871 mc
->mc_histogram
[i
+ ashift
] +=
872 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
874 mutex_exit(&mg
->mg_lock
);
878 metaslab_group_histogram_remove(metaslab_group_t
*mg
, metaslab_t
*msp
)
880 metaslab_class_t
*mc
= mg
->mg_class
;
881 uint64_t ashift
= mg
->mg_vd
->vdev_ashift
;
883 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
884 if (msp
->ms_sm
== NULL
)
887 mutex_enter(&mg
->mg_lock
);
888 for (int i
= 0; i
< SPACE_MAP_HISTOGRAM_SIZE
; i
++) {
889 ASSERT3U(mg
->mg_histogram
[i
+ ashift
], >=,
890 msp
->ms_sm
->sm_phys
->smp_histogram
[i
]);
891 ASSERT3U(mc
->mc_histogram
[i
+ ashift
], >=,
892 msp
->ms_sm
->sm_phys
->smp_histogram
[i
]);
894 mg
->mg_histogram
[i
+ ashift
] -=
895 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
896 mc
->mc_histogram
[i
+ ashift
] -=
897 msp
->ms_sm
->sm_phys
->smp_histogram
[i
];
899 mutex_exit(&mg
->mg_lock
);
903 metaslab_group_add(metaslab_group_t
*mg
, metaslab_t
*msp
)
905 ASSERT(msp
->ms_group
== NULL
);
906 mutex_enter(&mg
->mg_lock
);
909 avl_add(&mg
->mg_metaslab_tree
, msp
);
910 mutex_exit(&mg
->mg_lock
);
912 mutex_enter(&msp
->ms_lock
);
913 metaslab_group_histogram_add(mg
, msp
);
914 mutex_exit(&msp
->ms_lock
);
918 metaslab_group_remove(metaslab_group_t
*mg
, metaslab_t
*msp
)
920 mutex_enter(&msp
->ms_lock
);
921 metaslab_group_histogram_remove(mg
, msp
);
922 mutex_exit(&msp
->ms_lock
);
924 mutex_enter(&mg
->mg_lock
);
925 ASSERT(msp
->ms_group
== mg
);
926 avl_remove(&mg
->mg_metaslab_tree
, msp
);
927 msp
->ms_group
= NULL
;
928 mutex_exit(&mg
->mg_lock
);
932 metaslab_group_sort_impl(metaslab_group_t
*mg
, metaslab_t
*msp
, uint64_t weight
)
934 ASSERT(MUTEX_HELD(&mg
->mg_lock
));
935 ASSERT(msp
->ms_group
== mg
);
936 avl_remove(&mg
->mg_metaslab_tree
, msp
);
937 msp
->ms_weight
= weight
;
938 avl_add(&mg
->mg_metaslab_tree
, msp
);
943 metaslab_group_sort(metaslab_group_t
*mg
, metaslab_t
*msp
, uint64_t weight
)
946 * Although in principle the weight can be any value, in
947 * practice we do not use values in the range [1, 511].
949 ASSERT(weight
>= SPA_MINBLOCKSIZE
|| weight
== 0);
950 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
952 mutex_enter(&mg
->mg_lock
);
953 metaslab_group_sort_impl(mg
, msp
, weight
);
954 mutex_exit(&mg
->mg_lock
);
958 * Calculate the fragmentation for a given metaslab group. We can use
959 * a simple average here since all metaslabs within the group must have
960 * the same size. The return value will be a value between 0 and 100
961 * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
962 * group have a fragmentation metric.
965 metaslab_group_fragmentation(metaslab_group_t
*mg
)
967 vdev_t
*vd
= mg
->mg_vd
;
968 uint64_t fragmentation
= 0;
969 uint64_t valid_ms
= 0;
971 for (int m
= 0; m
< vd
->vdev_ms_count
; m
++) {
972 metaslab_t
*msp
= vd
->vdev_ms
[m
];
974 if (msp
->ms_fragmentation
== ZFS_FRAG_INVALID
)
978 fragmentation
+= msp
->ms_fragmentation
;
981 if (valid_ms
<= vd
->vdev_ms_count
/ 2)
982 return (ZFS_FRAG_INVALID
);
984 fragmentation
/= valid_ms
;
985 ASSERT3U(fragmentation
, <=, 100);
986 return (fragmentation
);
990 * Determine if a given metaslab group should skip allocations. A metaslab
991 * group should avoid allocations if its free capacity is less than the
992 * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
993 * zfs_mg_fragmentation_threshold and there is at least one metaslab group
994 * that can still handle allocations. If the allocation throttle is enabled
995 * then we skip allocations to devices that have reached their maximum
996 * allocation queue depth unless the selected metaslab group is the only
997 * eligible group remaining.
1000 metaslab_group_allocatable(metaslab_group_t
*mg
, metaslab_group_t
*rotor
,
1001 uint64_t psize
, int allocator
)
1003 spa_t
*spa
= mg
->mg_vd
->vdev_spa
;
1004 metaslab_class_t
*mc
= mg
->mg_class
;
1007 * We can only consider skipping this metaslab group if it's
1008 * in the normal metaslab class and there are other metaslab
1009 * groups to select from. Otherwise, we always consider it eligible
1012 if (mc
!= spa_normal_class(spa
) || mc
->mc_groups
<= 1)
1016 * If the metaslab group's mg_allocatable flag is set (see comments
1017 * in metaslab_group_alloc_update() for more information) and
1018 * the allocation throttle is disabled then allow allocations to this
1019 * device. However, if the allocation throttle is enabled then
1020 * check if we have reached our allocation limit (mg_alloc_queue_depth)
1021 * to determine if we should allow allocations to this metaslab group.
1022 * If all metaslab groups are no longer considered allocatable
1023 * (mc_alloc_groups == 0) or we're trying to allocate the smallest
1024 * gang block size then we allow allocations on this metaslab group
1025 * regardless of the mg_allocatable or throttle settings.
1027 if (mg
->mg_allocatable
) {
1028 metaslab_group_t
*mgp
;
1030 uint64_t qmax
= mg
->mg_cur_max_alloc_queue_depth
[allocator
];
1032 if (!mc
->mc_alloc_throttle_enabled
)
1036 * If this metaslab group does not have any free space, then
1037 * there is no point in looking further.
1039 if (mg
->mg_no_free_space
)
1042 qdepth
= refcount_count(&mg
->mg_alloc_queue_depth
[allocator
]);
1045 * If this metaslab group is below its qmax or it's
1046 * the only allocatable metasable group, then attempt
1047 * to allocate from it.
1049 if (qdepth
< qmax
|| mc
->mc_alloc_groups
== 1)
1051 ASSERT3U(mc
->mc_alloc_groups
, >, 1);
1054 * Since this metaslab group is at or over its qmax, we
1055 * need to determine if there are metaslab groups after this
1056 * one that might be able to handle this allocation. This is
1057 * racy since we can't hold the locks for all metaslab
1058 * groups at the same time when we make this check.
1060 for (mgp
= mg
->mg_next
; mgp
!= rotor
; mgp
= mgp
->mg_next
) {
1061 qmax
= mgp
->mg_cur_max_alloc_queue_depth
[allocator
];
1063 qdepth
= refcount_count(
1064 &mgp
->mg_alloc_queue_depth
[allocator
]);
1067 * If there is another metaslab group that
1068 * might be able to handle the allocation, then
1069 * we return false so that we skip this group.
1071 if (qdepth
< qmax
&& !mgp
->mg_no_free_space
)
1076 * We didn't find another group to handle the allocation
1077 * so we can't skip this metaslab group even though
1078 * we are at or over our qmax.
1082 } else if (mc
->mc_alloc_groups
== 0 || psize
== SPA_MINBLOCKSIZE
) {
1089 * ==========================================================================
1090 * Range tree callbacks
1091 * ==========================================================================
1095 * Comparison function for the private size-ordered tree. Tree is sorted
1096 * by size, larger sizes at the end of the tree.
1099 metaslab_rangesize_compare(const void *x1
, const void *x2
)
1101 const range_seg_t
*r1
= x1
;
1102 const range_seg_t
*r2
= x2
;
1103 uint64_t rs_size1
= r1
->rs_end
- r1
->rs_start
;
1104 uint64_t rs_size2
= r2
->rs_end
- r2
->rs_start
;
1106 if (rs_size1
< rs_size2
)
1108 if (rs_size1
> rs_size2
)
1111 if (r1
->rs_start
< r2
->rs_start
)
1114 if (r1
->rs_start
> r2
->rs_start
)
1121 * Create any block allocator specific components. The current allocators
1122 * rely on using both a size-ordered range_tree_t and an array of uint64_t's.
1125 metaslab_rt_create(range_tree_t
*rt
, void *arg
)
1127 metaslab_t
*msp
= arg
;
1129 ASSERT3P(rt
->rt_arg
, ==, msp
);
1130 ASSERT(msp
->ms_allocatable
== NULL
);
1132 avl_create(&msp
->ms_allocatable_by_size
, metaslab_rangesize_compare
,
1133 sizeof (range_seg_t
), offsetof(range_seg_t
, rs_pp_node
));
1137 * Destroy the block allocator specific components.
1140 metaslab_rt_destroy(range_tree_t
*rt
, void *arg
)
1142 metaslab_t
*msp
= arg
;
1144 ASSERT3P(rt
->rt_arg
, ==, msp
);
1145 ASSERT3P(msp
->ms_allocatable
, ==, rt
);
1146 ASSERT0(avl_numnodes(&msp
->ms_allocatable_by_size
));
1148 avl_destroy(&msp
->ms_allocatable_by_size
);
1152 metaslab_rt_add(range_tree_t
*rt
, range_seg_t
*rs
, void *arg
)
1154 metaslab_t
*msp
= arg
;
1156 ASSERT3P(rt
->rt_arg
, ==, msp
);
1157 ASSERT3P(msp
->ms_allocatable
, ==, rt
);
1158 VERIFY(!msp
->ms_condensing
);
1159 avl_add(&msp
->ms_allocatable_by_size
, rs
);
1163 metaslab_rt_remove(range_tree_t
*rt
, range_seg_t
*rs
, void *arg
)
1165 metaslab_t
*msp
= arg
;
1167 ASSERT3P(rt
->rt_arg
, ==, msp
);
1168 ASSERT3P(msp
->ms_allocatable
, ==, rt
);
1169 VERIFY(!msp
->ms_condensing
);
1170 avl_remove(&msp
->ms_allocatable_by_size
, rs
);
1174 metaslab_rt_vacate(range_tree_t
*rt
, void *arg
)
1176 metaslab_t
*msp
= arg
;
1178 ASSERT3P(rt
->rt_arg
, ==, msp
);
1179 ASSERT3P(msp
->ms_allocatable
, ==, rt
);
1182 * Normally one would walk the tree freeing nodes along the way.
1183 * Since the nodes are shared with the range trees we can avoid
1184 * walking all nodes and just reinitialize the avl tree. The nodes
1185 * will be freed by the range tree, so we don't want to free them here.
1187 avl_create(&msp
->ms_allocatable_by_size
, metaslab_rangesize_compare
,
1188 sizeof (range_seg_t
), offsetof(range_seg_t
, rs_pp_node
));
1191 static range_tree_ops_t metaslab_rt_ops
= {
1193 metaslab_rt_destroy
,
1200 * ==========================================================================
1201 * Common allocator routines
1202 * ==========================================================================
1206 * Return the maximum contiguous segment within the metaslab.
1209 metaslab_block_maxsize(metaslab_t
*msp
)
1211 avl_tree_t
*t
= &msp
->ms_allocatable_by_size
;
1214 if (t
== NULL
|| (rs
= avl_last(t
)) == NULL
)
1217 return (rs
->rs_end
- rs
->rs_start
);
1220 static range_seg_t
*
1221 metaslab_block_find(avl_tree_t
*t
, uint64_t start
, uint64_t size
)
1223 range_seg_t
*rs
, rsearch
;
1226 rsearch
.rs_start
= start
;
1227 rsearch
.rs_end
= start
+ size
;
1229 rs
= avl_find(t
, &rsearch
, &where
);
1231 rs
= avl_nearest(t
, where
, AVL_AFTER
);
1238 * This is a helper function that can be used by the allocator to find
1239 * a suitable block to allocate. This will search the specified AVL
1240 * tree looking for a block that matches the specified criteria.
1243 metaslab_block_picker(avl_tree_t
*t
, uint64_t *cursor
, uint64_t size
,
1246 range_seg_t
*rs
= metaslab_block_find(t
, *cursor
, size
);
1248 while (rs
!= NULL
) {
1249 uint64_t offset
= P2ROUNDUP(rs
->rs_start
, align
);
1251 if (offset
+ size
<= rs
->rs_end
) {
1252 *cursor
= offset
+ size
;
1255 rs
= AVL_NEXT(t
, rs
);
1259 * If we know we've searched the whole map (*cursor == 0), give up.
1260 * Otherwise, reset the cursor to the beginning and try again.
1266 return (metaslab_block_picker(t
, cursor
, size
, align
));
1270 * ==========================================================================
1271 * The first-fit block allocator
1272 * ==========================================================================
1275 metaslab_ff_alloc(metaslab_t
*msp
, uint64_t size
)
1278 * Find the largest power of 2 block size that evenly divides the
1279 * requested size. This is used to try to allocate blocks with similar
1280 * alignment from the same area of the metaslab (i.e. same cursor
1281 * bucket) but it does not guarantee that other allocations sizes
1282 * may exist in the same region.
1284 uint64_t align
= size
& -size
;
1285 uint64_t *cursor
= &msp
->ms_lbas
[highbit64(align
) - 1];
1286 avl_tree_t
*t
= &msp
->ms_allocatable
->rt_root
;
1288 return (metaslab_block_picker(t
, cursor
, size
, align
));
1291 static metaslab_ops_t metaslab_ff_ops
= {
1296 * ==========================================================================
1297 * Dynamic block allocator -
1298 * Uses the first fit allocation scheme until space get low and then
1299 * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
1300 * and metaslab_df_free_pct to determine when to switch the allocation scheme.
1301 * ==========================================================================
1304 metaslab_df_alloc(metaslab_t
*msp
, uint64_t size
)
1307 * Find the largest power of 2 block size that evenly divides the
1308 * requested size. This is used to try to allocate blocks with similar
1309 * alignment from the same area of the metaslab (i.e. same cursor
1310 * bucket) but it does not guarantee that other allocations sizes
1311 * may exist in the same region.
1313 uint64_t align
= size
& -size
;
1314 uint64_t *cursor
= &msp
->ms_lbas
[highbit64(align
) - 1];
1315 range_tree_t
*rt
= msp
->ms_allocatable
;
1316 avl_tree_t
*t
= &rt
->rt_root
;
1317 uint64_t max_size
= metaslab_block_maxsize(msp
);
1318 int free_pct
= range_tree_space(rt
) * 100 / msp
->ms_size
;
1320 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1321 ASSERT3U(avl_numnodes(t
), ==,
1322 avl_numnodes(&msp
->ms_allocatable_by_size
));
1324 if (max_size
< size
)
1328 * If we're running low on space switch to using the size
1329 * sorted AVL tree (best-fit).
1331 if (max_size
< metaslab_df_alloc_threshold
||
1332 free_pct
< metaslab_df_free_pct
) {
1333 t
= &msp
->ms_allocatable_by_size
;
1337 return (metaslab_block_picker(t
, cursor
, size
, 1ULL));
1340 static metaslab_ops_t metaslab_df_ops
= {
1345 * ==========================================================================
1346 * Cursor fit block allocator -
1347 * Select the largest region in the metaslab, set the cursor to the beginning
1348 * of the range and the cursor_end to the end of the range. As allocations
1349 * are made advance the cursor. Continue allocating from the cursor until
1350 * the range is exhausted and then find a new range.
1351 * ==========================================================================
1354 metaslab_cf_alloc(metaslab_t
*msp
, uint64_t size
)
1356 range_tree_t
*rt
= msp
->ms_allocatable
;
1357 avl_tree_t
*t
= &msp
->ms_allocatable_by_size
;
1358 uint64_t *cursor
= &msp
->ms_lbas
[0];
1359 uint64_t *cursor_end
= &msp
->ms_lbas
[1];
1360 uint64_t offset
= 0;
1362 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1363 ASSERT3U(avl_numnodes(t
), ==, avl_numnodes(&rt
->rt_root
));
1365 ASSERT3U(*cursor_end
, >=, *cursor
);
1367 if ((*cursor
+ size
) > *cursor_end
) {
1370 rs
= avl_last(&msp
->ms_allocatable_by_size
);
1371 if (rs
== NULL
|| (rs
->rs_end
- rs
->rs_start
) < size
)
1374 *cursor
= rs
->rs_start
;
1375 *cursor_end
= rs
->rs_end
;
1384 static metaslab_ops_t metaslab_cf_ops
= {
1389 * ==========================================================================
1390 * New dynamic fit allocator -
1391 * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1392 * contiguous blocks. If no region is found then just use the largest segment
1394 * ==========================================================================
1398 * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1399 * to request from the allocator.
1401 uint64_t metaslab_ndf_clump_shift
= 4;
1404 metaslab_ndf_alloc(metaslab_t
*msp
, uint64_t size
)
1406 avl_tree_t
*t
= &msp
->ms_allocatable
->rt_root
;
1408 range_seg_t
*rs
, rsearch
;
1409 uint64_t hbit
= highbit64(size
);
1410 uint64_t *cursor
= &msp
->ms_lbas
[hbit
- 1];
1411 uint64_t max_size
= metaslab_block_maxsize(msp
);
1413 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1414 ASSERT3U(avl_numnodes(t
), ==,
1415 avl_numnodes(&msp
->ms_allocatable_by_size
));
1417 if (max_size
< size
)
1420 rsearch
.rs_start
= *cursor
;
1421 rsearch
.rs_end
= *cursor
+ size
;
1423 rs
= avl_find(t
, &rsearch
, &where
);
1424 if (rs
== NULL
|| (rs
->rs_end
- rs
->rs_start
) < size
) {
1425 t
= &msp
->ms_allocatable_by_size
;
1427 rsearch
.rs_start
= 0;
1428 rsearch
.rs_end
= MIN(max_size
,
1429 1ULL << (hbit
+ metaslab_ndf_clump_shift
));
1430 rs
= avl_find(t
, &rsearch
, &where
);
1432 rs
= avl_nearest(t
, where
, AVL_AFTER
);
1436 if ((rs
->rs_end
- rs
->rs_start
) >= size
) {
1437 *cursor
= rs
->rs_start
+ size
;
1438 return (rs
->rs_start
);
1443 static metaslab_ops_t metaslab_ndf_ops
= {
1447 metaslab_ops_t
*zfs_metaslab_ops
= &metaslab_df_ops
;
1450 * ==========================================================================
1452 * ==========================================================================
1456 * Wait for any in-progress metaslab loads to complete.
1459 metaslab_load_wait(metaslab_t
*msp
)
1461 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1463 while (msp
->ms_loading
) {
1464 ASSERT(!msp
->ms_loaded
);
1465 cv_wait(&msp
->ms_load_cv
, &msp
->ms_lock
);
1470 metaslab_load(metaslab_t
*msp
)
1473 boolean_t success
= B_FALSE
;
1475 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1476 ASSERT(!msp
->ms_loaded
);
1477 ASSERT(!msp
->ms_loading
);
1479 msp
->ms_loading
= B_TRUE
;
1481 * Nobody else can manipulate a loading metaslab, so it's now safe
1482 * to drop the lock. This way we don't have to hold the lock while
1483 * reading the spacemap from disk.
1485 mutex_exit(&msp
->ms_lock
);
1488 * If the space map has not been allocated yet, then treat
1489 * all the space in the metaslab as free and add it to ms_allocatable.
1491 if (msp
->ms_sm
!= NULL
) {
1492 error
= space_map_load(msp
->ms_sm
, msp
->ms_allocatable
,
1495 range_tree_add(msp
->ms_allocatable
,
1496 msp
->ms_start
, msp
->ms_size
);
1499 success
= (error
== 0);
1501 mutex_enter(&msp
->ms_lock
);
1502 msp
->ms_loading
= B_FALSE
;
1505 ASSERT3P(msp
->ms_group
, !=, NULL
);
1506 msp
->ms_loaded
= B_TRUE
;
1509 * If the metaslab already has a spacemap, then we need to
1510 * remove all segments from the defer tree; otherwise, the
1511 * metaslab is completely empty and we can skip this.
1513 if (msp
->ms_sm
!= NULL
) {
1514 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
1515 range_tree_walk(msp
->ms_defer
[t
],
1516 range_tree_remove
, msp
->ms_allocatable
);
1519 msp
->ms_max_size
= metaslab_block_maxsize(msp
);
1521 cv_broadcast(&msp
->ms_load_cv
);
1526 metaslab_unload(metaslab_t
*msp
)
1528 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1529 range_tree_vacate(msp
->ms_allocatable
, NULL
, NULL
);
1530 msp
->ms_loaded
= B_FALSE
;
1531 msp
->ms_weight
&= ~METASLAB_ACTIVE_MASK
;
1532 msp
->ms_max_size
= 0;
1536 metaslab_init(metaslab_group_t
*mg
, uint64_t id
, uint64_t object
, uint64_t txg
,
1539 vdev_t
*vd
= mg
->mg_vd
;
1540 objset_t
*mos
= vd
->vdev_spa
->spa_meta_objset
;
1544 ms
= kmem_zalloc(sizeof (metaslab_t
), KM_SLEEP
);
1545 mutex_init(&ms
->ms_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
1546 mutex_init(&ms
->ms_sync_lock
, NULL
, MUTEX_DEFAULT
, NULL
);
1547 cv_init(&ms
->ms_load_cv
, NULL
, CV_DEFAULT
, NULL
);
1550 ms
->ms_start
= id
<< vd
->vdev_ms_shift
;
1551 ms
->ms_size
= 1ULL << vd
->vdev_ms_shift
;
1552 ms
->ms_allocator
= -1;
1553 ms
->ms_new
= B_TRUE
;
1556 * We only open space map objects that already exist. All others
1557 * will be opened when we finally allocate an object for it.
1560 error
= space_map_open(&ms
->ms_sm
, mos
, object
, ms
->ms_start
,
1561 ms
->ms_size
, vd
->vdev_ashift
);
1564 kmem_free(ms
, sizeof (metaslab_t
));
1568 ASSERT(ms
->ms_sm
!= NULL
);
1572 * We create the main range tree here, but we don't create the
1573 * other range trees until metaslab_sync_done(). This serves
1574 * two purposes: it allows metaslab_sync_done() to detect the
1575 * addition of new space; and for debugging, it ensures that we'd
1576 * data fault on any attempt to use this metaslab before it's ready.
1578 ms
->ms_allocatable
= range_tree_create(&metaslab_rt_ops
, ms
);
1579 metaslab_group_add(mg
, ms
);
1581 metaslab_set_fragmentation(ms
);
1584 * If we're opening an existing pool (txg == 0) or creating
1585 * a new one (txg == TXG_INITIAL), all space is available now.
1586 * If we're adding space to an existing pool, the new space
1587 * does not become available until after this txg has synced.
1588 * The metaslab's weight will also be initialized when we sync
1589 * out this txg. This ensures that we don't attempt to allocate
1590 * from it before we have initialized it completely.
1592 if (txg
<= TXG_INITIAL
)
1593 metaslab_sync_done(ms
, 0);
1596 * If metaslab_debug_load is set and we're initializing a metaslab
1597 * that has an allocated space map object then load the its space
1598 * map so that can verify frees.
1600 if (metaslab_debug_load
&& ms
->ms_sm
!= NULL
) {
1601 mutex_enter(&ms
->ms_lock
);
1602 VERIFY0(metaslab_load(ms
));
1603 mutex_exit(&ms
->ms_lock
);
1607 vdev_dirty(vd
, 0, NULL
, txg
);
1608 vdev_dirty(vd
, VDD_METASLAB
, ms
, txg
);
1617 metaslab_fini(metaslab_t
*msp
)
1619 metaslab_group_t
*mg
= msp
->ms_group
;
1621 metaslab_group_remove(mg
, msp
);
1623 mutex_enter(&msp
->ms_lock
);
1624 VERIFY(msp
->ms_group
== NULL
);
1625 vdev_space_update(mg
->mg_vd
, -space_map_allocated(msp
->ms_sm
),
1627 space_map_close(msp
->ms_sm
);
1629 metaslab_unload(msp
);
1630 range_tree_destroy(msp
->ms_allocatable
);
1631 range_tree_destroy(msp
->ms_freeing
);
1632 range_tree_destroy(msp
->ms_freed
);
1634 for (int t
= 0; t
< TXG_SIZE
; t
++) {
1635 range_tree_destroy(msp
->ms_allocating
[t
]);
1638 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
1639 range_tree_destroy(msp
->ms_defer
[t
]);
1641 ASSERT0(msp
->ms_deferspace
);
1643 range_tree_destroy(msp
->ms_checkpointing
);
1645 mutex_exit(&msp
->ms_lock
);
1646 cv_destroy(&msp
->ms_load_cv
);
1647 mutex_destroy(&msp
->ms_lock
);
1648 mutex_destroy(&msp
->ms_sync_lock
);
1649 ASSERT3U(msp
->ms_allocator
, ==, -1);
1651 kmem_free(msp
, sizeof (metaslab_t
));
1654 #define FRAGMENTATION_TABLE_SIZE 17
1657 * This table defines a segment size based fragmentation metric that will
1658 * allow each metaslab to derive its own fragmentation value. This is done
1659 * by calculating the space in each bucket of the spacemap histogram and
1660 * multiplying that by the fragmetation metric in this table. Doing
1661 * this for all buckets and dividing it by the total amount of free
1662 * space in this metaslab (i.e. the total free space in all buckets) gives
1663 * us the fragmentation metric. This means that a high fragmentation metric
1664 * equates to most of the free space being comprised of small segments.
1665 * Conversely, if the metric is low, then most of the free space is in
1666 * large segments. A 10% change in fragmentation equates to approximately
1667 * double the number of segments.
1669 * This table defines 0% fragmented space using 16MB segments. Testing has
1670 * shown that segments that are greater than or equal to 16MB do not suffer
1671 * from drastic performance problems. Using this value, we derive the rest
1672 * of the table. Since the fragmentation value is never stored on disk, it
1673 * is possible to change these calculations in the future.
1675 int zfs_frag_table
[FRAGMENTATION_TABLE_SIZE
] = {
1695 * Calclate the metaslab's fragmentation metric. A return value
1696 * of ZFS_FRAG_INVALID means that the metaslab has not been upgraded and does
1697 * not support this metric. Otherwise, the return value should be in the
1701 metaslab_set_fragmentation(metaslab_t
*msp
)
1703 spa_t
*spa
= msp
->ms_group
->mg_vd
->vdev_spa
;
1704 uint64_t fragmentation
= 0;
1706 boolean_t feature_enabled
= spa_feature_is_enabled(spa
,
1707 SPA_FEATURE_SPACEMAP_HISTOGRAM
);
1709 if (!feature_enabled
) {
1710 msp
->ms_fragmentation
= ZFS_FRAG_INVALID
;
1715 * A null space map means that the entire metaslab is free
1716 * and thus is not fragmented.
1718 if (msp
->ms_sm
== NULL
) {
1719 msp
->ms_fragmentation
= 0;
1724 * If this metaslab's space map has not been upgraded, flag it
1725 * so that we upgrade next time we encounter it.
1727 if (msp
->ms_sm
->sm_dbuf
->db_size
!= sizeof (space_map_phys_t
)) {
1728 uint64_t txg
= spa_syncing_txg(spa
);
1729 vdev_t
*vd
= msp
->ms_group
->mg_vd
;
1732 * If we've reached the final dirty txg, then we must
1733 * be shutting down the pool. We don't want to dirty
1734 * any data past this point so skip setting the condense
1735 * flag. We can retry this action the next time the pool
1738 if (spa_writeable(spa
) && txg
< spa_final_dirty_txg(spa
)) {
1739 msp
->ms_condense_wanted
= B_TRUE
;
1740 vdev_dirty(vd
, VDD_METASLAB
, msp
, txg
+ 1);
1741 zfs_dbgmsg("txg %llu, requesting force condense: "
1742 "ms_id %llu, vdev_id %llu", txg
, msp
->ms_id
,
1745 msp
->ms_fragmentation
= ZFS_FRAG_INVALID
;
1749 for (int i
= 0; i
< SPACE_MAP_HISTOGRAM_SIZE
; i
++) {
1751 uint8_t shift
= msp
->ms_sm
->sm_shift
;
1753 int idx
= MIN(shift
- SPA_MINBLOCKSHIFT
+ i
,
1754 FRAGMENTATION_TABLE_SIZE
- 1);
1756 if (msp
->ms_sm
->sm_phys
->smp_histogram
[i
] == 0)
1759 space
= msp
->ms_sm
->sm_phys
->smp_histogram
[i
] << (i
+ shift
);
1762 ASSERT3U(idx
, <, FRAGMENTATION_TABLE_SIZE
);
1763 fragmentation
+= space
* zfs_frag_table
[idx
];
1767 fragmentation
/= total
;
1768 ASSERT3U(fragmentation
, <=, 100);
1770 msp
->ms_fragmentation
= fragmentation
;
1774 * Compute a weight -- a selection preference value -- for the given metaslab.
1775 * This is based on the amount of free space, the level of fragmentation,
1776 * the LBA range, and whether the metaslab is loaded.
1779 metaslab_space_weight(metaslab_t
*msp
)
1781 metaslab_group_t
*mg
= msp
->ms_group
;
1782 vdev_t
*vd
= mg
->mg_vd
;
1783 uint64_t weight
, space
;
1785 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1786 ASSERT(!vd
->vdev_removing
);
1789 * The baseline weight is the metaslab's free space.
1791 space
= msp
->ms_size
- space_map_allocated(msp
->ms_sm
);
1793 if (metaslab_fragmentation_factor_enabled
&&
1794 msp
->ms_fragmentation
!= ZFS_FRAG_INVALID
) {
1796 * Use the fragmentation information to inversely scale
1797 * down the baseline weight. We need to ensure that we
1798 * don't exclude this metaslab completely when it's 100%
1799 * fragmented. To avoid this we reduce the fragmented value
1802 space
= (space
* (100 - (msp
->ms_fragmentation
- 1))) / 100;
1805 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
1806 * this metaslab again. The fragmentation metric may have
1807 * decreased the space to something smaller than
1808 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
1809 * so that we can consume any remaining space.
1811 if (space
> 0 && space
< SPA_MINBLOCKSIZE
)
1812 space
= SPA_MINBLOCKSIZE
;
1817 * Modern disks have uniform bit density and constant angular velocity.
1818 * Therefore, the outer recording zones are faster (higher bandwidth)
1819 * than the inner zones by the ratio of outer to inner track diameter,
1820 * which is typically around 2:1. We account for this by assigning
1821 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
1822 * In effect, this means that we'll select the metaslab with the most
1823 * free bandwidth rather than simply the one with the most free space.
1825 if (metaslab_lba_weighting_enabled
) {
1826 weight
= 2 * weight
- (msp
->ms_id
* weight
) / vd
->vdev_ms_count
;
1827 ASSERT(weight
>= space
&& weight
<= 2 * space
);
1831 * If this metaslab is one we're actively using, adjust its
1832 * weight to make it preferable to any inactive metaslab so
1833 * we'll polish it off. If the fragmentation on this metaslab
1834 * has exceed our threshold, then don't mark it active.
1836 if (msp
->ms_loaded
&& msp
->ms_fragmentation
!= ZFS_FRAG_INVALID
&&
1837 msp
->ms_fragmentation
<= zfs_metaslab_fragmentation_threshold
) {
1838 weight
|= (msp
->ms_weight
& METASLAB_ACTIVE_MASK
);
1841 WEIGHT_SET_SPACEBASED(weight
);
1846 * Return the weight of the specified metaslab, according to the segment-based
1847 * weighting algorithm. The metaslab must be loaded. This function can
1848 * be called within a sync pass since it relies only on the metaslab's
1849 * range tree which is always accurate when the metaslab is loaded.
1852 metaslab_weight_from_range_tree(metaslab_t
*msp
)
1854 uint64_t weight
= 0;
1855 uint32_t segments
= 0;
1857 ASSERT(msp
->ms_loaded
);
1859 for (int i
= RANGE_TREE_HISTOGRAM_SIZE
- 1; i
>= SPA_MINBLOCKSHIFT
;
1861 uint8_t shift
= msp
->ms_group
->mg_vd
->vdev_ashift
;
1862 int max_idx
= SPACE_MAP_HISTOGRAM_SIZE
+ shift
- 1;
1865 segments
+= msp
->ms_allocatable
->rt_histogram
[i
];
1868 * The range tree provides more precision than the space map
1869 * and must be downgraded so that all values fit within the
1870 * space map's histogram. This allows us to compare loaded
1871 * vs. unloaded metaslabs to determine which metaslab is
1872 * considered "best".
1877 if (segments
!= 0) {
1878 WEIGHT_SET_COUNT(weight
, segments
);
1879 WEIGHT_SET_INDEX(weight
, i
);
1880 WEIGHT_SET_ACTIVE(weight
, 0);
1888 * Calculate the weight based on the on-disk histogram. This should only
1889 * be called after a sync pass has completely finished since the on-disk
1890 * information is updated in metaslab_sync().
1893 metaslab_weight_from_spacemap(metaslab_t
*msp
)
1895 uint64_t weight
= 0;
1897 for (int i
= SPACE_MAP_HISTOGRAM_SIZE
- 1; i
>= 0; i
--) {
1898 if (msp
->ms_sm
->sm_phys
->smp_histogram
[i
] != 0) {
1899 WEIGHT_SET_COUNT(weight
,
1900 msp
->ms_sm
->sm_phys
->smp_histogram
[i
]);
1901 WEIGHT_SET_INDEX(weight
, i
+
1902 msp
->ms_sm
->sm_shift
);
1903 WEIGHT_SET_ACTIVE(weight
, 0);
1911 * Compute a segment-based weight for the specified metaslab. The weight
1912 * is determined by highest bucket in the histogram. The information
1913 * for the highest bucket is encoded into the weight value.
1916 metaslab_segment_weight(metaslab_t
*msp
)
1918 metaslab_group_t
*mg
= msp
->ms_group
;
1919 uint64_t weight
= 0;
1920 uint8_t shift
= mg
->mg_vd
->vdev_ashift
;
1922 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
1925 * The metaslab is completely free.
1927 if (space_map_allocated(msp
->ms_sm
) == 0) {
1928 int idx
= highbit64(msp
->ms_size
) - 1;
1929 int max_idx
= SPACE_MAP_HISTOGRAM_SIZE
+ shift
- 1;
1931 if (idx
< max_idx
) {
1932 WEIGHT_SET_COUNT(weight
, 1ULL);
1933 WEIGHT_SET_INDEX(weight
, idx
);
1935 WEIGHT_SET_COUNT(weight
, 1ULL << (idx
- max_idx
));
1936 WEIGHT_SET_INDEX(weight
, max_idx
);
1938 WEIGHT_SET_ACTIVE(weight
, 0);
1939 ASSERT(!WEIGHT_IS_SPACEBASED(weight
));
1944 ASSERT3U(msp
->ms_sm
->sm_dbuf
->db_size
, ==, sizeof (space_map_phys_t
));
1947 * If the metaslab is fully allocated then just make the weight 0.
1949 if (space_map_allocated(msp
->ms_sm
) == msp
->ms_size
)
1952 * If the metaslab is already loaded, then use the range tree to
1953 * determine the weight. Otherwise, we rely on the space map information
1954 * to generate the weight.
1956 if (msp
->ms_loaded
) {
1957 weight
= metaslab_weight_from_range_tree(msp
);
1959 weight
= metaslab_weight_from_spacemap(msp
);
1963 * If the metaslab was active the last time we calculated its weight
1964 * then keep it active. We want to consume the entire region that
1965 * is associated with this weight.
1967 if (msp
->ms_activation_weight
!= 0 && weight
!= 0)
1968 WEIGHT_SET_ACTIVE(weight
, WEIGHT_GET_ACTIVE(msp
->ms_weight
));
1973 * Determine if we should attempt to allocate from this metaslab. If the
1974 * metaslab has a maximum size then we can quickly determine if the desired
1975 * allocation size can be satisfied. Otherwise, if we're using segment-based
1976 * weighting then we can determine the maximum allocation that this metaslab
1977 * can accommodate based on the index encoded in the weight. If we're using
1978 * space-based weights then rely on the entire weight (excluding the weight
1982 metaslab_should_allocate(metaslab_t
*msp
, uint64_t asize
)
1984 boolean_t should_allocate
;
1986 if (msp
->ms_max_size
!= 0)
1987 return (msp
->ms_max_size
>= asize
);
1989 if (!WEIGHT_IS_SPACEBASED(msp
->ms_weight
)) {
1991 * The metaslab segment weight indicates segments in the
1992 * range [2^i, 2^(i+1)), where i is the index in the weight.
1993 * Since the asize might be in the middle of the range, we
1994 * should attempt the allocation if asize < 2^(i+1).
1996 should_allocate
= (asize
<
1997 1ULL << (WEIGHT_GET_INDEX(msp
->ms_weight
) + 1));
1999 should_allocate
= (asize
<=
2000 (msp
->ms_weight
& ~METASLAB_WEIGHT_TYPE
));
2002 return (should_allocate
);
2006 metaslab_weight(metaslab_t
*msp
)
2008 vdev_t
*vd
= msp
->ms_group
->mg_vd
;
2009 spa_t
*spa
= vd
->vdev_spa
;
2012 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2015 * If this vdev is in the process of being removed, there is nothing
2016 * for us to do here.
2018 if (vd
->vdev_removing
)
2021 metaslab_set_fragmentation(msp
);
2024 * Update the maximum size if the metaslab is loaded. This will
2025 * ensure that we get an accurate maximum size if newly freed space
2026 * has been added back into the free tree.
2029 msp
->ms_max_size
= metaslab_block_maxsize(msp
);
2032 * Segment-based weighting requires space map histogram support.
2034 if (zfs_metaslab_segment_weight_enabled
&&
2035 spa_feature_is_enabled(spa
, SPA_FEATURE_SPACEMAP_HISTOGRAM
) &&
2036 (msp
->ms_sm
== NULL
|| msp
->ms_sm
->sm_dbuf
->db_size
==
2037 sizeof (space_map_phys_t
))) {
2038 weight
= metaslab_segment_weight(msp
);
2040 weight
= metaslab_space_weight(msp
);
2046 metaslab_activate_allocator(metaslab_group_t
*mg
, metaslab_t
*msp
,
2047 int allocator
, uint64_t activation_weight
)
2050 * If we're activating for the claim code, we don't want to actually
2051 * set the metaslab up for a specific allocator.
2053 if (activation_weight
== METASLAB_WEIGHT_CLAIM
)
2055 metaslab_t
**arr
= (activation_weight
== METASLAB_WEIGHT_PRIMARY
?
2056 mg
->mg_primaries
: mg
->mg_secondaries
);
2058 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2059 mutex_enter(&mg
->mg_lock
);
2060 if (arr
[allocator
] != NULL
) {
2061 mutex_exit(&mg
->mg_lock
);
2065 arr
[allocator
] = msp
;
2066 ASSERT3S(msp
->ms_allocator
, ==, -1);
2067 msp
->ms_allocator
= allocator
;
2068 msp
->ms_primary
= (activation_weight
== METASLAB_WEIGHT_PRIMARY
);
2069 mutex_exit(&mg
->mg_lock
);
2075 metaslab_activate(metaslab_t
*msp
, int allocator
, uint64_t activation_weight
)
2077 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2079 if ((msp
->ms_weight
& METASLAB_ACTIVE_MASK
) == 0) {
2081 metaslab_load_wait(msp
);
2082 if (!msp
->ms_loaded
) {
2083 if ((error
= metaslab_load(msp
)) != 0) {
2084 metaslab_group_sort(msp
->ms_group
, msp
, 0);
2088 if ((msp
->ms_weight
& METASLAB_ACTIVE_MASK
) != 0) {
2090 * The metaslab was activated for another allocator
2091 * while we were waiting, we should reselect.
2095 if ((error
= metaslab_activate_allocator(msp
->ms_group
, msp
,
2096 allocator
, activation_weight
)) != 0) {
2100 msp
->ms_activation_weight
= msp
->ms_weight
;
2101 metaslab_group_sort(msp
->ms_group
, msp
,
2102 msp
->ms_weight
| activation_weight
);
2104 ASSERT(msp
->ms_loaded
);
2105 ASSERT(msp
->ms_weight
& METASLAB_ACTIVE_MASK
);
2111 metaslab_passivate_allocator(metaslab_group_t
*mg
, metaslab_t
*msp
,
2114 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2115 if (msp
->ms_weight
& METASLAB_WEIGHT_CLAIM
) {
2116 metaslab_group_sort(mg
, msp
, weight
);
2120 mutex_enter(&mg
->mg_lock
);
2121 ASSERT3P(msp
->ms_group
, ==, mg
);
2122 if (msp
->ms_primary
) {
2123 ASSERT3U(0, <=, msp
->ms_allocator
);
2124 ASSERT3U(msp
->ms_allocator
, <, mg
->mg_allocators
);
2125 ASSERT3P(mg
->mg_primaries
[msp
->ms_allocator
], ==, msp
);
2126 ASSERT(msp
->ms_weight
& METASLAB_WEIGHT_PRIMARY
);
2127 mg
->mg_primaries
[msp
->ms_allocator
] = NULL
;
2129 ASSERT(msp
->ms_weight
& METASLAB_WEIGHT_SECONDARY
);
2130 ASSERT3P(mg
->mg_secondaries
[msp
->ms_allocator
], ==, msp
);
2131 mg
->mg_secondaries
[msp
->ms_allocator
] = NULL
;
2133 msp
->ms_allocator
= -1;
2134 metaslab_group_sort_impl(mg
, msp
, weight
);
2135 mutex_exit(&mg
->mg_lock
);
2139 metaslab_passivate(metaslab_t
*msp
, uint64_t weight
)
2141 uint64_t size
= weight
& ~METASLAB_WEIGHT_TYPE
;
2144 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
2145 * this metaslab again. In that case, it had better be empty,
2146 * or we would be leaving space on the table.
2148 ASSERT(size
>= SPA_MINBLOCKSIZE
||
2149 range_tree_is_empty(msp
->ms_allocatable
));
2150 ASSERT0(weight
& METASLAB_ACTIVE_MASK
);
2152 msp
->ms_activation_weight
= 0;
2153 metaslab_passivate_allocator(msp
->ms_group
, msp
, weight
);
2154 ASSERT((msp
->ms_weight
& METASLAB_ACTIVE_MASK
) == 0);
2158 * Segment-based metaslabs are activated once and remain active until
2159 * we either fail an allocation attempt (similar to space-based metaslabs)
2160 * or have exhausted the free space in zfs_metaslab_switch_threshold
2161 * buckets since the metaslab was activated. This function checks to see
2162 * if we've exhaused the zfs_metaslab_switch_threshold buckets in the
2163 * metaslab and passivates it proactively. This will allow us to select a
2164 * metaslabs with larger contiguous region if any remaining within this
2165 * metaslab group. If we're in sync pass > 1, then we continue using this
2166 * metaslab so that we don't dirty more block and cause more sync passes.
2169 metaslab_segment_may_passivate(metaslab_t
*msp
)
2171 spa_t
*spa
= msp
->ms_group
->mg_vd
->vdev_spa
;
2173 if (WEIGHT_IS_SPACEBASED(msp
->ms_weight
) || spa_sync_pass(spa
) > 1)
2177 * Since we are in the middle of a sync pass, the most accurate
2178 * information that is accessible to us is the in-core range tree
2179 * histogram; calculate the new weight based on that information.
2181 uint64_t weight
= metaslab_weight_from_range_tree(msp
);
2182 int activation_idx
= WEIGHT_GET_INDEX(msp
->ms_activation_weight
);
2183 int current_idx
= WEIGHT_GET_INDEX(weight
);
2185 if (current_idx
<= activation_idx
- zfs_metaslab_switch_threshold
)
2186 metaslab_passivate(msp
, weight
);
2190 metaslab_preload(void *arg
)
2192 metaslab_t
*msp
= arg
;
2193 spa_t
*spa
= msp
->ms_group
->mg_vd
->vdev_spa
;
2195 ASSERT(!MUTEX_HELD(&msp
->ms_group
->mg_lock
));
2197 mutex_enter(&msp
->ms_lock
);
2198 metaslab_load_wait(msp
);
2199 if (!msp
->ms_loaded
)
2200 (void) metaslab_load(msp
);
2201 msp
->ms_selected_txg
= spa_syncing_txg(spa
);
2202 mutex_exit(&msp
->ms_lock
);
2206 metaslab_group_preload(metaslab_group_t
*mg
)
2208 spa_t
*spa
= mg
->mg_vd
->vdev_spa
;
2210 avl_tree_t
*t
= &mg
->mg_metaslab_tree
;
2213 if (spa_shutting_down(spa
) || !metaslab_preload_enabled
) {
2214 taskq_wait(mg
->mg_taskq
);
2218 mutex_enter(&mg
->mg_lock
);
2221 * Load the next potential metaslabs
2223 for (msp
= avl_first(t
); msp
!= NULL
; msp
= AVL_NEXT(t
, msp
)) {
2224 ASSERT3P(msp
->ms_group
, ==, mg
);
2227 * We preload only the maximum number of metaslabs specified
2228 * by metaslab_preload_limit. If a metaslab is being forced
2229 * to condense then we preload it too. This will ensure
2230 * that force condensing happens in the next txg.
2232 if (++m
> metaslab_preload_limit
&& !msp
->ms_condense_wanted
) {
2236 VERIFY(taskq_dispatch(mg
->mg_taskq
, metaslab_preload
,
2237 msp
, TQ_SLEEP
) != (uintptr_t)NULL
);
2239 mutex_exit(&mg
->mg_lock
);
2243 * Determine if the space map's on-disk footprint is past our tolerance
2244 * for inefficiency. We would like to use the following criteria to make
2247 * 1. The size of the space map object should not dramatically increase as a
2248 * result of writing out the free space range tree.
2250 * 2. The minimal on-disk space map representation is zfs_condense_pct/100
2251 * times the size than the free space range tree representation
2252 * (i.e. zfs_condense_pct = 110 and in-core = 1MB, minimal = 1.1MB).
2254 * 3. The on-disk size of the space map should actually decrease.
2256 * Unfortunately, we cannot compute the on-disk size of the space map in this
2257 * context because we cannot accurately compute the effects of compression, etc.
2258 * Instead, we apply the heuristic described in the block comment for
2259 * zfs_metaslab_condense_block_threshold - we only condense if the space used
2260 * is greater than a threshold number of blocks.
2263 metaslab_should_condense(metaslab_t
*msp
)
2265 space_map_t
*sm
= msp
->ms_sm
;
2266 vdev_t
*vd
= msp
->ms_group
->mg_vd
;
2267 uint64_t vdev_blocksize
= 1 << vd
->vdev_ashift
;
2268 uint64_t current_txg
= spa_syncing_txg(vd
->vdev_spa
);
2270 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2271 ASSERT(msp
->ms_loaded
);
2274 * Allocations and frees in early passes are generally more space
2275 * efficient (in terms of blocks described in space map entries)
2276 * than the ones in later passes (e.g. we don't compress after
2277 * sync pass 5) and condensing a metaslab multiple times in a txg
2278 * could degrade performance.
2280 * Thus we prefer condensing each metaslab at most once every txg at
2281 * the earliest sync pass possible. If a metaslab is eligible for
2282 * condensing again after being considered for condensing within the
2283 * same txg, it will hopefully be dirty in the next txg where it will
2284 * be condensed at an earlier pass.
2286 if (msp
->ms_condense_checked_txg
== current_txg
)
2288 msp
->ms_condense_checked_txg
= current_txg
;
2291 * We always condense metaslabs that are empty and metaslabs for
2292 * which a condense request has been made.
2294 if (avl_is_empty(&msp
->ms_allocatable_by_size
) ||
2295 msp
->ms_condense_wanted
)
2298 uint64_t object_size
= space_map_length(msp
->ms_sm
);
2299 uint64_t optimal_size
= space_map_estimate_optimal_size(sm
,
2300 msp
->ms_allocatable
, SM_NO_VDEVID
);
2302 dmu_object_info_t doi
;
2303 dmu_object_info_from_db(sm
->sm_dbuf
, &doi
);
2304 uint64_t record_size
= MAX(doi
.doi_data_block_size
, vdev_blocksize
);
2306 return (object_size
>= (optimal_size
* zfs_condense_pct
/ 100) &&
2307 object_size
> zfs_metaslab_condense_block_threshold
* record_size
);
2311 * Condense the on-disk space map representation to its minimized form.
2312 * The minimized form consists of a small number of allocations followed by
2313 * the entries of the free range tree.
2316 metaslab_condense(metaslab_t
*msp
, uint64_t txg
, dmu_tx_t
*tx
)
2318 range_tree_t
*condense_tree
;
2319 space_map_t
*sm
= msp
->ms_sm
;
2321 ASSERT(MUTEX_HELD(&msp
->ms_lock
));
2322 ASSERT(msp
->ms_loaded
);
2324 zfs_dbgmsg("condensing: txg %llu, msp[%llu] %p, vdev id %llu, "
2325 "spa %s, smp size %llu, segments %lu, forcing condense=%s", txg
,
2326 msp
->ms_id
, msp
, msp
->ms_group
->mg_vd
->vdev_id
,
2327 msp
->ms_group
->mg_vd
->vdev_spa
->spa_name
,
2328 space_map_length(msp
->ms_sm
),
2329 avl_numnodes(&msp
->ms_allocatable
->rt_root
),
2330 msp
->ms_condense_wanted
? "TRUE" : "FALSE");
2332 msp
->ms_condense_wanted
= B_FALSE
;
2335 * Create an range tree that is 100% allocated. We remove segments
2336 * that have been freed in this txg, any deferred frees that exist,
2337 * and any allocation in the future. Removing segments should be
2338 * a relatively inexpensive operation since we expect these trees to
2339 * have a small number of nodes.
2341 condense_tree
= range_tree_create(NULL
, NULL
);
2342 range_tree_add(condense_tree
, msp
->ms_start
, msp
->ms_size
);
2344 range_tree_walk(msp
->ms_freeing
, range_tree_remove
, condense_tree
);
2345 range_tree_walk(msp
->ms_freed
, range_tree_remove
, condense_tree
);
2347 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
2348 range_tree_walk(msp
->ms_defer
[t
],
2349 range_tree_remove
, condense_tree
);
2352 for (int t
= 1; t
< TXG_CONCURRENT_STATES
; t
++) {
2353 range_tree_walk(msp
->ms_allocating
[(txg
+ t
) & TXG_MASK
],
2354 range_tree_remove
, condense_tree
);
2358 * We're about to drop the metaslab's lock thus allowing
2359 * other consumers to change it's content. Set the
2360 * metaslab's ms_condensing flag to ensure that
2361 * allocations on this metaslab do not occur while we're
2362 * in the middle of committing it to disk. This is only critical
2363 * for ms_allocatable as all other range trees use per txg
2364 * views of their content.
2366 msp
->ms_condensing
= B_TRUE
;
2368 mutex_exit(&msp
->ms_lock
);
2369 space_map_truncate(sm
, zfs_metaslab_sm_blksz
, tx
);
2372 * While we would ideally like to create a space map representation
2373 * that consists only of allocation records, doing so can be
2374 * prohibitively expensive because the in-core free tree can be
2375 * large, and therefore computationally expensive to subtract
2376 * from the condense_tree. Instead we sync out two trees, a cheap
2377 * allocation only tree followed by the in-core free tree. While not
2378 * optimal, this is typically close to optimal, and much cheaper to
2381 space_map_write(sm
, condense_tree
, SM_ALLOC
, SM_NO_VDEVID
, tx
);
2382 range_tree_vacate(condense_tree
, NULL
, NULL
);
2383 range_tree_destroy(condense_tree
);
2385 space_map_write(sm
, msp
->ms_allocatable
, SM_FREE
, SM_NO_VDEVID
, tx
);
2386 mutex_enter(&msp
->ms_lock
);
2387 msp
->ms_condensing
= B_FALSE
;
2391 * Write a metaslab to disk in the context of the specified transaction group.
2394 metaslab_sync(metaslab_t
*msp
, uint64_t txg
)
2396 metaslab_group_t
*mg
= msp
->ms_group
;
2397 vdev_t
*vd
= mg
->mg_vd
;
2398 spa_t
*spa
= vd
->vdev_spa
;
2399 objset_t
*mos
= spa_meta_objset(spa
);
2400 range_tree_t
*alloctree
= msp
->ms_allocating
[txg
& TXG_MASK
];
2402 uint64_t object
= space_map_object(msp
->ms_sm
);
2404 ASSERT(!vd
->vdev_ishole
);
2407 * This metaslab has just been added so there's no work to do now.
2409 if (msp
->ms_freeing
== NULL
) {
2410 ASSERT3P(alloctree
, ==, NULL
);
2414 ASSERT3P(alloctree
, !=, NULL
);
2415 ASSERT3P(msp
->ms_freeing
, !=, NULL
);
2416 ASSERT3P(msp
->ms_freed
, !=, NULL
);
2417 ASSERT3P(msp
->ms_checkpointing
, !=, NULL
);
2420 * Normally, we don't want to process a metaslab if there are no
2421 * allocations or frees to perform. However, if the metaslab is being
2422 * forced to condense and it's loaded, we need to let it through.
2424 if (range_tree_is_empty(alloctree
) &&
2425 range_tree_is_empty(msp
->ms_freeing
) &&
2426 range_tree_is_empty(msp
->ms_checkpointing
) &&
2427 !(msp
->ms_loaded
&& msp
->ms_condense_wanted
))
2431 VERIFY(txg
<= spa_final_dirty_txg(spa
));
2434 * The only state that can actually be changing concurrently with
2435 * metaslab_sync() is the metaslab's ms_allocatable. No other
2436 * thread can be modifying this txg's alloc, freeing,
2437 * freed, or space_map_phys_t. We drop ms_lock whenever we
2438 * could call into the DMU, because the DMU can call down to us
2439 * (e.g. via zio_free()) at any time.
2441 * The spa_vdev_remove_thread() can be reading metaslab state
2442 * concurrently, and it is locked out by the ms_sync_lock. Note
2443 * that the ms_lock is insufficient for this, because it is dropped
2444 * by space_map_write().
2446 tx
= dmu_tx_create_assigned(spa_get_dsl(spa
), txg
);
2448 if (msp
->ms_sm
== NULL
) {
2449 uint64_t new_object
;
2451 new_object
= space_map_alloc(mos
, zfs_metaslab_sm_blksz
, tx
);
2452 VERIFY3U(new_object
, !=, 0);
2454 VERIFY0(space_map_open(&msp
->ms_sm
, mos
, new_object
,
2455 msp
->ms_start
, msp
->ms_size
, vd
->vdev_ashift
));
2456 ASSERT(msp
->ms_sm
!= NULL
);
2459 if (!range_tree_is_empty(msp
->ms_checkpointing
) &&
2460 vd
->vdev_checkpoint_sm
== NULL
) {
2461 ASSERT(spa_has_checkpoint(spa
));
2463 uint64_t new_object
= space_map_alloc(mos
,
2464 vdev_standard_sm_blksz
, tx
);
2465 VERIFY3U(new_object
, !=, 0);
2467 VERIFY0(space_map_open(&vd
->vdev_checkpoint_sm
,
2468 mos
, new_object
, 0, vd
->vdev_asize
, vd
->vdev_ashift
));
2469 ASSERT3P(vd
->vdev_checkpoint_sm
, !=, NULL
);
2472 * We save the space map object as an entry in vdev_top_zap
2473 * so it can be retrieved when the pool is reopened after an
2474 * export or through zdb.
2476 VERIFY0(zap_add(vd
->vdev_spa
->spa_meta_objset
,
2477 vd
->vdev_top_zap
, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM
,
2478 sizeof (new_object
), 1, &new_object
, tx
));
2481 mutex_enter(&msp
->ms_sync_lock
);
2482 mutex_enter(&msp
->ms_lock
);
2485 * Note: metaslab_condense() clears the space map's histogram.
2486 * Therefore we must verify and remove this histogram before
2489 metaslab_group_histogram_verify(mg
);
2490 metaslab_class_histogram_verify(mg
->mg_class
);
2491 metaslab_group_histogram_remove(mg
, msp
);
2493 if (msp
->ms_loaded
&& metaslab_should_condense(msp
)) {
2494 metaslab_condense(msp
, txg
, tx
);
2496 mutex_exit(&msp
->ms_lock
);
2497 space_map_write(msp
->ms_sm
, alloctree
, SM_ALLOC
,
2499 space_map_write(msp
->ms_sm
, msp
->ms_freeing
, SM_FREE
,
2501 mutex_enter(&msp
->ms_lock
);
2504 if (!range_tree_is_empty(msp
->ms_checkpointing
)) {
2505 ASSERT(spa_has_checkpoint(spa
));
2506 ASSERT3P(vd
->vdev_checkpoint_sm
, !=, NULL
);
2509 * Since we are doing writes to disk and the ms_checkpointing
2510 * tree won't be changing during that time, we drop the
2511 * ms_lock while writing to the checkpoint space map.
2513 mutex_exit(&msp
->ms_lock
);
2514 space_map_write(vd
->vdev_checkpoint_sm
,
2515 msp
->ms_checkpointing
, SM_FREE
, SM_NO_VDEVID
, tx
);
2516 mutex_enter(&msp
->ms_lock
);
2517 space_map_update(vd
->vdev_checkpoint_sm
);
2519 spa
->spa_checkpoint_info
.sci_dspace
+=
2520 range_tree_space(msp
->ms_checkpointing
);
2521 vd
->vdev_stat
.vs_checkpoint_space
+=
2522 range_tree_space(msp
->ms_checkpointing
);
2523 ASSERT3U(vd
->vdev_stat
.vs_checkpoint_space
, ==,
2524 -vd
->vdev_checkpoint_sm
->sm_alloc
);
2526 range_tree_vacate(msp
->ms_checkpointing
, NULL
, NULL
);
2529 if (msp
->ms_loaded
) {
2531 * When the space map is loaded, we have an accurate
2532 * histogram in the range tree. This gives us an opportunity
2533 * to bring the space map's histogram up-to-date so we clear
2534 * it first before updating it.
2536 space_map_histogram_clear(msp
->ms_sm
);
2537 space_map_histogram_add(msp
->ms_sm
, msp
->ms_allocatable
, tx
);
2540 * Since we've cleared the histogram we need to add back
2541 * any free space that has already been processed, plus
2542 * any deferred space. This allows the on-disk histogram
2543 * to accurately reflect all free space even if some space
2544 * is not yet available for allocation (i.e. deferred).
2546 space_map_histogram_add(msp
->ms_sm
, msp
->ms_freed
, tx
);
2549 * Add back any deferred free space that has not been
2550 * added back into the in-core free tree yet. This will
2551 * ensure that we don't end up with a space map histogram
2552 * that is completely empty unless the metaslab is fully
2555 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
2556 space_map_histogram_add(msp
->ms_sm
,
2557 msp
->ms_defer
[t
], tx
);
2562 * Always add the free space from this sync pass to the space
2563 * map histogram. We want to make sure that the on-disk histogram
2564 * accounts for all free space. If the space map is not loaded,
2565 * then we will lose some accuracy but will correct it the next
2566 * time we load the space map.
2568 space_map_histogram_add(msp
->ms_sm
, msp
->ms_freeing
, tx
);
2570 metaslab_group_histogram_add(mg
, msp
);
2571 metaslab_group_histogram_verify(mg
);
2572 metaslab_class_histogram_verify(mg
->mg_class
);
2575 * For sync pass 1, we avoid traversing this txg's free range tree
2576 * and instead will just swap the pointers for freeing and
2577 * freed. We can safely do this since the freed_tree is
2578 * guaranteed to be empty on the initial pass.
2580 if (spa_sync_pass(spa
) == 1) {
2581 range_tree_swap(&msp
->ms_freeing
, &msp
->ms_freed
);
2583 range_tree_vacate(msp
->ms_freeing
,
2584 range_tree_add
, msp
->ms_freed
);
2586 range_tree_vacate(alloctree
, NULL
, NULL
);
2588 ASSERT0(range_tree_space(msp
->ms_allocating
[txg
& TXG_MASK
]));
2589 ASSERT0(range_tree_space(msp
->ms_allocating
[TXG_CLEAN(txg
)
2591 ASSERT0(range_tree_space(msp
->ms_freeing
));
2592 ASSERT0(range_tree_space(msp
->ms_checkpointing
));
2594 mutex_exit(&msp
->ms_lock
);
2596 if (object
!= space_map_object(msp
->ms_sm
)) {
2597 object
= space_map_object(msp
->ms_sm
);
2598 dmu_write(mos
, vd
->vdev_ms_array
, sizeof (uint64_t) *
2599 msp
->ms_id
, sizeof (uint64_t), &object
, tx
);
2601 mutex_exit(&msp
->ms_sync_lock
);
2606 * Called after a transaction group has completely synced to mark
2607 * all of the metaslab's free space as usable.
2610 metaslab_sync_done(metaslab_t
*msp
, uint64_t txg
)
2612 metaslab_group_t
*mg
= msp
->ms_group
;
2613 vdev_t
*vd
= mg
->mg_vd
;
2614 spa_t
*spa
= vd
->vdev_spa
;
2615 range_tree_t
**defer_tree
;
2616 int64_t alloc_delta
, defer_delta
;
2617 boolean_t defer_allowed
= B_TRUE
;
2619 ASSERT(!vd
->vdev_ishole
);
2621 mutex_enter(&msp
->ms_lock
);
2624 * If this metaslab is just becoming available, initialize its
2625 * range trees and add its capacity to the vdev.
2627 if (msp
->ms_freed
== NULL
) {
2628 for (int t
= 0; t
< TXG_SIZE
; t
++) {
2629 ASSERT(msp
->ms_allocating
[t
] == NULL
);
2631 msp
->ms_allocating
[t
] = range_tree_create(NULL
, NULL
);
2634 ASSERT3P(msp
->ms_freeing
, ==, NULL
);
2635 msp
->ms_freeing
= range_tree_create(NULL
, NULL
);
2637 ASSERT3P(msp
->ms_freed
, ==, NULL
);
2638 msp
->ms_freed
= range_tree_create(NULL
, NULL
);
2640 for (int t
= 0; t
< TXG_DEFER_SIZE
; t
++) {
2641 ASSERT(msp
->ms_defer
[t
] == NULL
);
2643 msp
->ms_defer
[t
] = range_tree_create(NULL
, NULL
);
2646 ASSERT3P(msp
->ms_checkpointing
, ==, NULL
);
2647 msp
->ms_checkpointing
= range_tree_create(NULL
, NULL
);
2649 vdev_space_update(vd
, 0, 0, msp
->ms_size
);
2651 ASSERT0(range_tree_space(msp
->ms_freeing
));
2652 ASSERT0(range_tree_space(msp
->ms_checkpointing
));
2654 defer_tree
= &msp
->ms_defer
[txg
% TXG_DEFER_SIZE
];
2656 uint64_t free_space
= metaslab_class_get_space(spa_normal_class(spa
)) -
2657 metaslab_class_get_alloc(spa_normal_class(spa
));
2658 if (free_space
<= spa_get_slop_space(spa
) || vd
->vdev_removing
) {
2659 defer_allowed
= B_FALSE
;
2663 alloc_delta
= space_map_alloc_delta(msp
->ms_sm
);
2664 if (defer_allowed
) {
2665 defer_delta
= range_tree_space(msp
->ms_freed
) -
2666 range_tree_space(*defer_tree
);
2668 defer_delta
-= range_tree_space(*defer_tree
);
2671 vdev_space_update(vd
, alloc_delta
+ defer_delta
, defer_delta
, 0);
2674 * If there's a metaslab_load() in progress, wait for it to complete
2675 * so that we have a consistent view of the in-core space map.
2677 metaslab_load_wait(msp
);
2680 * Move the frees from the defer_tree back to the free
2681 * range tree (if it's loaded). Swap the freed_tree and
2682 * the defer_tree -- this is safe to do because we've
2683 * just emptied out the defer_tree.
2685 range_tree_vacate(*defer_tree
,
2686 msp
->ms_loaded
? range_tree_add
: NULL
, msp
->ms_allocatable
);
2687 if (defer_allowed
) {
2688 range_tree_swap(&msp
->ms_freed
, defer_tree
);
2690 range_tree_vacate(msp
->ms_freed
,
2691 msp
->ms_loaded
? range_tree_add
: NULL
,
2692 msp
->ms_allocatable
);
2694 space_map_update(msp
->ms_sm
);
2696 msp
->ms_deferspace
+= defer_delta
;
2697 ASSERT3S(msp
->ms_deferspace
, >=, 0);
2698 ASSERT3S(msp
->ms_deferspace
, <=, msp
->ms_size
);
2699 if (msp
->ms_deferspace
!= 0) {
2701 * Keep syncing this metaslab until all deferred frees
2702 * are back in circulation.
2704 vdev_dirty(vd
, VDD_METASLAB
, msp
, txg
+ 1);
2708 msp
->ms_new
= B_FALSE
;
2709 mutex_enter(&mg
->mg_lock
);
2711 mutex_exit(&mg
->mg_lock
);
2714 * Calculate the new weights before unloading any metaslabs.
2715 * This will give us the most accurate weighting.
2717 metaslab_group_sort(mg
, msp
, metaslab_weight(msp
) |
2718 (msp
->ms_weight
& METASLAB_ACTIVE_MASK
));
2721 * If the metaslab is loaded and we've not tried to load or allocate
2722 * from it in 'metaslab_unload_delay' txgs, then unload it.
2724 if (msp
->ms_loaded
&&
2725 msp
->ms_initializing
== 0 &&
2726 msp
->ms_selected_txg
+ metaslab_unload_delay
< txg
) {
2727 for (int t
= 1; t
< TXG_CONCURRENT_STATES
; t
++) {
2728 VERIFY0(range_tree_space(
2729 msp
->ms_allocating
[(txg
+ t
) & TXG_MASK
]));
2731 if (msp
->ms_allocator
!= -1) {
2732 metaslab_passivate(msp
, msp
->ms_weight
&
2733 ~METASLAB_ACTIVE_MASK
);
2736 if (!metaslab_debug_unload
)
2737 metaslab_unload(msp
);
2740 ASSERT0(range_tree_space(msp
->ms_allocating
[txg
& TXG_MASK
]));
2741 ASSERT0(range_tree_space(msp
->ms_freeing
));
2742 ASSERT0(range_tree_space(msp
->ms_freed
));
2743 ASSERT0(range_tree_space(msp
->ms_checkpointing
));
2745 mutex_exit(&msp
->ms_lock
);
2749 metaslab_sync_reassess(metaslab_group_t
*mg
)
2751 spa_t
*spa
= mg
->mg_class
->mc_spa
;
2753 spa_config_enter(spa
, SCL_ALLOC
, FTAG
, RW_READER
);
2754 metaslab_group_alloc_update(mg
);
2755 mg
->mg_fragmentation
= metaslab_group_fragmentation(mg
);
2758 * Preload the next potential metaslabs but only on active
2759 * metaslab groups. We can get into a state where the metaslab
2760 * is no longer active since we dirty metaslabs as we remove a
2761 * a device, thus potentially making the metaslab group eligible
2764 if (mg
->mg_activation_count
> 0) {
2765 metaslab_group_preload(mg
);
2767 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
2771 metaslab_distance(metaslab_t
*msp
, dva_t
*dva
)
2773 uint64_t ms_shift
= msp
->ms_group
->mg_vd
->vdev_ms_shift
;
2774 uint64_t offset
= DVA_GET_OFFSET(dva
) >> ms_shift
;
2775 uint64_t start
= msp
->ms_id
;
2777 if (msp
->ms_group
->mg_vd
->vdev_id
!= DVA_GET_VDEV(dva
))
2778 return (1ULL << 63);
2781 return ((start
- offset
) << ms_shift
);
2783 return ((offset
- start
) << ms_shift
);
2788 * ==========================================================================
2789 * Metaslab allocation tracing facility
2790 * ==========================================================================
2792 kstat_t
*metaslab_trace_ksp
;
2793 kstat_named_t metaslab_trace_over_limit
;
2796 metaslab_alloc_trace_init(void)
2798 ASSERT(metaslab_alloc_trace_cache
== NULL
);
2799 metaslab_alloc_trace_cache
= kmem_cache_create(
2800 "metaslab_alloc_trace_cache", sizeof (metaslab_alloc_trace_t
),
2801 0, NULL
, NULL
, NULL
, NULL
, NULL
, 0);
2802 metaslab_trace_ksp
= kstat_create("zfs", 0, "metaslab_trace_stats",
2803 "misc", KSTAT_TYPE_NAMED
, 1, KSTAT_FLAG_VIRTUAL
);
2804 if (metaslab_trace_ksp
!= NULL
) {
2805 metaslab_trace_ksp
->ks_data
= &metaslab_trace_over_limit
;
2806 kstat_named_init(&metaslab_trace_over_limit
,
2807 "metaslab_trace_over_limit", KSTAT_DATA_UINT64
);
2808 kstat_install(metaslab_trace_ksp
);
2813 metaslab_alloc_trace_fini(void)
2815 if (metaslab_trace_ksp
!= NULL
) {
2816 kstat_delete(metaslab_trace_ksp
);
2817 metaslab_trace_ksp
= NULL
;
2819 kmem_cache_destroy(metaslab_alloc_trace_cache
);
2820 metaslab_alloc_trace_cache
= NULL
;
2824 * Add an allocation trace element to the allocation tracing list.
2827 metaslab_trace_add(zio_alloc_list_t
*zal
, metaslab_group_t
*mg
,
2828 metaslab_t
*msp
, uint64_t psize
, uint32_t dva_id
, uint64_t offset
,
2831 if (!metaslab_trace_enabled
)
2835 * When the tracing list reaches its maximum we remove
2836 * the second element in the list before adding a new one.
2837 * By removing the second element we preserve the original
2838 * entry as a clue to what allocations steps have already been
2841 if (zal
->zal_size
== metaslab_trace_max_entries
) {
2842 metaslab_alloc_trace_t
*mat_next
;
2844 panic("too many entries in allocation list");
2846 atomic_inc_64(&metaslab_trace_over_limit
.value
.ui64
);
2848 mat_next
= list_next(&zal
->zal_list
, list_head(&zal
->zal_list
));
2849 list_remove(&zal
->zal_list
, mat_next
);
2850 kmem_cache_free(metaslab_alloc_trace_cache
, mat_next
);
2853 metaslab_alloc_trace_t
*mat
=
2854 kmem_cache_alloc(metaslab_alloc_trace_cache
, KM_SLEEP
);
2855 list_link_init(&mat
->mat_list_node
);
2858 mat
->mat_size
= psize
;
2859 mat
->mat_dva_id
= dva_id
;
2860 mat
->mat_offset
= offset
;
2861 mat
->mat_weight
= 0;
2862 mat
->mat_allocator
= allocator
;
2865 mat
->mat_weight
= msp
->ms_weight
;
2868 * The list is part of the zio so locking is not required. Only
2869 * a single thread will perform allocations for a given zio.
2871 list_insert_tail(&zal
->zal_list
, mat
);
2874 ASSERT3U(zal
->zal_size
, <=, metaslab_trace_max_entries
);
2878 metaslab_trace_init(zio_alloc_list_t
*zal
)
2880 list_create(&zal
->zal_list
, sizeof (metaslab_alloc_trace_t
),
2881 offsetof(metaslab_alloc_trace_t
, mat_list_node
));
2886 metaslab_trace_fini(zio_alloc_list_t
*zal
)
2888 metaslab_alloc_trace_t
*mat
;
2890 while ((mat
= list_remove_head(&zal
->zal_list
)) != NULL
)
2891 kmem_cache_free(metaslab_alloc_trace_cache
, mat
);
2892 list_destroy(&zal
->zal_list
);
2897 * ==========================================================================
2898 * Metaslab block operations
2899 * ==========================================================================
2903 metaslab_group_alloc_increment(spa_t
*spa
, uint64_t vdev
, void *tag
, int flags
,
2906 if (!(flags
& METASLAB_ASYNC_ALLOC
) ||
2907 (flags
& METASLAB_DONT_THROTTLE
))
2910 metaslab_group_t
*mg
= vdev_lookup_top(spa
, vdev
)->vdev_mg
;
2911 if (!mg
->mg_class
->mc_alloc_throttle_enabled
)
2914 (void) refcount_add(&mg
->mg_alloc_queue_depth
[allocator
], tag
);
2918 metaslab_group_increment_qdepth(metaslab_group_t
*mg
, int allocator
)
2920 uint64_t max
= mg
->mg_max_alloc_queue_depth
;
2921 uint64_t cur
= mg
->mg_cur_max_alloc_queue_depth
[allocator
];
2923 if (atomic_cas_64(&mg
->mg_cur_max_alloc_queue_depth
[allocator
],
2924 cur
, cur
+ 1) == cur
) {
2926 &mg
->mg_class
->mc_alloc_max_slots
[allocator
]);
2929 cur
= mg
->mg_cur_max_alloc_queue_depth
[allocator
];
2934 metaslab_group_alloc_decrement(spa_t
*spa
, uint64_t vdev
, void *tag
, int flags
,
2935 int allocator
, boolean_t io_complete
)
2937 if (!(flags
& METASLAB_ASYNC_ALLOC
) ||
2938 (flags
& METASLAB_DONT_THROTTLE
))
2941 metaslab_group_t
*mg
= vdev_lookup_top(spa
, vdev
)->vdev_mg
;
2942 if (!mg
->mg_class
->mc_alloc_throttle_enabled
)
2945 (void) refcount_remove(&mg
->mg_alloc_queue_depth
[allocator
], tag
);
2947 metaslab_group_increment_qdepth(mg
, allocator
);
2951 metaslab_group_alloc_verify(spa_t
*spa
, const blkptr_t
*bp
, void *tag
,
2955 const dva_t
*dva
= bp
->blk_dva
;
2956 int ndvas
= BP_GET_NDVAS(bp
);
2958 for (int d
= 0; d
< ndvas
; d
++) {
2959 uint64_t vdev
= DVA_GET_VDEV(&dva
[d
]);
2960 metaslab_group_t
*mg
= vdev_lookup_top(spa
, vdev
)->vdev_mg
;
2961 VERIFY(refcount_not_held(&mg
->mg_alloc_queue_depth
[allocator
],
2968 metaslab_block_alloc(metaslab_t
*msp
, uint64_t size
, uint64_t txg
)
2971 range_tree_t
*rt
= msp
->ms_allocatable
;
2972 metaslab_class_t
*mc
= msp
->ms_group
->mg_class
;
2974 VERIFY(!msp
->ms_condensing
);
2975 VERIFY0(msp
->ms_initializing
);
2977 start
= mc
->mc_ops
->msop_alloc(msp
, size
);
2978 if (start
!= -1ULL) {
2979 metaslab_group_t
*mg
= msp
->ms_group
;
2980 vdev_t
*vd
= mg
->mg_vd
;
2982 VERIFY0(P2PHASE(start
, 1ULL << vd
->vdev_ashift
));
2983 VERIFY0(P2PHASE(size
, 1ULL << vd
->vdev_ashift
));
2984 VERIFY3U(range_tree_space(rt
) - size
, <=, msp
->ms_size
);
2985 range_tree_remove(rt
, start
, size
);
2987 if (range_tree_is_empty(msp
->ms_allocating
[txg
& TXG_MASK
]))
2988 vdev_dirty(mg
->mg_vd
, VDD_METASLAB
, msp
, txg
);
2990 range_tree_add(msp
->ms_allocating
[txg
& TXG_MASK
], start
, size
);
2992 /* Track the last successful allocation */
2993 msp
->ms_alloc_txg
= txg
;
2994 metaslab_verify_space(msp
, txg
);
2998 * Now that we've attempted the allocation we need to update the
2999 * metaslab's maximum block size since it may have changed.
3001 msp
->ms_max_size
= metaslab_block_maxsize(msp
);
3006 * Find the metaslab with the highest weight that is less than what we've
3007 * already tried. In the common case, this means that we will examine each
3008 * metaslab at most once. Note that concurrent callers could reorder metaslabs
3009 * by activation/passivation once we have dropped the mg_lock. If a metaslab is
3010 * activated by another thread, and we fail to allocate from the metaslab we
3011 * have selected, we may not try the newly-activated metaslab, and instead
3012 * activate another metaslab. This is not optimal, but generally does not cause
3013 * any problems (a possible exception being if every metaslab is completely full
3014 * except for the the newly-activated metaslab which we fail to examine).
3017 find_valid_metaslab(metaslab_group_t
*mg
, uint64_t activation_weight
,
3018 dva_t
*dva
, int d
, uint64_t min_distance
, uint64_t asize
, int allocator
,
3019 zio_alloc_list_t
*zal
, metaslab_t
*search
, boolean_t
*was_active
)
3022 avl_tree_t
*t
= &mg
->mg_metaslab_tree
;
3023 metaslab_t
*msp
= avl_find(t
, search
, &idx
);
3025 msp
= avl_nearest(t
, idx
, AVL_AFTER
);
3027 for (; msp
!= NULL
; msp
= AVL_NEXT(t
, msp
)) {
3029 if (!metaslab_should_allocate(msp
, asize
)) {
3030 metaslab_trace_add(zal
, mg
, msp
, asize
, d
,
3031 TRACE_TOO_SMALL
, allocator
);
3036 * If the selected metaslab is condensing or being
3037 * initialized, skip it.
3039 if (msp
->ms_condensing
|| msp
->ms_initializing
> 0)
3042 *was_active
= msp
->ms_allocator
!= -1;
3044 * If we're activating as primary, this is our first allocation
3045 * from this disk, so we don't need to check how close we are.
3046 * If the metaslab under consideration was already active,
3047 * we're getting desperate enough to steal another allocator's
3048 * metaslab, so we still don't care about distances.
3050 if (activation_weight
== METASLAB_WEIGHT_PRIMARY
|| *was_active
)
3053 uint64_t target_distance
= min_distance
3054 + (space_map_allocated(msp
->ms_sm
) != 0 ? 0 :
3057 for (i
= 0; i
< d
; i
++) {
3058 if (metaslab_distance(msp
, &dva
[i
]) < target_distance
)
3066 search
->ms_weight
= msp
->ms_weight
;
3067 search
->ms_start
= msp
->ms_start
+ 1;
3068 search
->ms_allocator
= msp
->ms_allocator
;
3069 search
->ms_primary
= msp
->ms_primary
;
3076 metaslab_group_alloc_normal(metaslab_group_t
*mg
, zio_alloc_list_t
*zal
,
3077 uint64_t asize
, uint64_t txg
, uint64_t min_distance
, dva_t
*dva
, int d
,
3080 metaslab_t
*msp
= NULL
;
3081 uint64_t offset
= -1ULL;
3082 uint64_t activation_weight
;
3084 activation_weight
= METASLAB_WEIGHT_PRIMARY
;
3085 for (int i
= 0; i
< d
; i
++) {
3086 if (activation_weight
== METASLAB_WEIGHT_PRIMARY
&&
3087 DVA_GET_VDEV(&dva
[i
]) == mg
->mg_vd
->vdev_id
) {
3088 activation_weight
= METASLAB_WEIGHT_SECONDARY
;
3089 } else if (activation_weight
== METASLAB_WEIGHT_SECONDARY
&&
3090 DVA_GET_VDEV(&dva
[i
]) == mg
->mg_vd
->vdev_id
) {
3091 activation_weight
= METASLAB_WEIGHT_CLAIM
;
3097 * If we don't have enough metaslabs active to fill the entire array, we
3098 * just use the 0th slot.
3100 if (mg
->mg_ms_ready
< mg
->mg_allocators
* 3)
3103 ASSERT3U(mg
->mg_vd
->vdev_ms_count
, >=, 2);
3105 metaslab_t
*search
= kmem_alloc(sizeof (*search
), KM_SLEEP
);
3106 search
->ms_weight
= UINT64_MAX
;
3107 search
->ms_start
= 0;
3109 * At the end of the metaslab tree are the already-active metaslabs,
3110 * first the primaries, then the secondaries. When we resume searching
3111 * through the tree, we need to consider ms_allocator and ms_primary so
3112 * we start in the location right after where we left off, and don't
3113 * accidentally loop forever considering the same metaslabs.
3115 search
->ms_allocator
= -1;
3116 search
->ms_primary
= B_TRUE
;
3118 boolean_t was_active
= B_FALSE
;
3120 mutex_enter(&mg
->mg_lock
);
3122 if (activation_weight
== METASLAB_WEIGHT_PRIMARY
&&
3123 mg
->mg_primaries
[allocator
] != NULL
) {
3124 msp
= mg
->mg_primaries
[allocator
];
3125 was_active
= B_TRUE
;
3126 } else if (activation_weight
== METASLAB_WEIGHT_SECONDARY
&&
3127 mg
->mg_secondaries
[allocator
] != NULL
) {
3128 msp
= mg
->mg_secondaries
[allocator
];
3129 was_active
= B_TRUE
;
3131 msp
= find_valid_metaslab(mg
, activation_weight
, dva
, d
,
3132 min_distance
, asize
, allocator
, zal
, search
,
3136 mutex_exit(&mg
->mg_lock
);
3138 kmem_free(search
, sizeof (*search
));
3142 mutex_enter(&msp
->ms_lock
);
3144 * Ensure that the metaslab we have selected is still
3145 * capable of handling our request. It's possible that
3146 * another thread may have changed the weight while we
3147 * were blocked on the metaslab lock. We check the
3148 * active status first to see if we need to reselect
3151 if (was_active
&& !(msp
->ms_weight
& METASLAB_ACTIVE_MASK
)) {
3152 mutex_exit(&msp
->ms_lock
);
3157 * If the metaslab is freshly activated for an allocator that
3158 * isn't the one we're allocating from, or if it's a primary and
3159 * we're seeking a secondary (or vice versa), we go back and
3160 * select a new metaslab.
3162 if (!was_active
&& (msp
->ms_weight
& METASLAB_ACTIVE_MASK
) &&
3163 (msp
->ms_allocator
!= -1) &&
3164 (msp
->ms_allocator
!= allocator
|| ((activation_weight
==
3165 METASLAB_WEIGHT_PRIMARY
) != msp
->ms_primary
))) {
3166 mutex_exit(&msp
->ms_lock
);
3170 if (msp
->ms_weight
& METASLAB_WEIGHT_CLAIM
&&
3171 activation_weight
!= METASLAB_WEIGHT_CLAIM
) {
3172 metaslab_passivate(msp
, msp
->ms_weight
&
3173 ~METASLAB_WEIGHT_CLAIM
);
3174 mutex_exit(&msp
->ms_lock
);
3178 if (metaslab_activate(msp
, allocator
, activation_weight
) != 0) {
3179 mutex_exit(&msp
->ms_lock
);
3183 msp
->ms_selected_txg
= txg
;
3186 * Now that we have the lock, recheck to see if we should
3187 * continue to use this metaslab for this allocation. The
3188 * the metaslab is now loaded so metaslab_should_allocate() can
3189 * accurately determine if the allocation attempt should
3192 if (!metaslab_should_allocate(msp
, asize
)) {
3193 /* Passivate this metaslab and select a new one. */
3194 metaslab_trace_add(zal
, mg
, msp
, asize
, d
,
3195 TRACE_TOO_SMALL
, allocator
);
3200 * If this metaslab is currently condensing then pick again as
3201 * we can't manipulate this metaslab until it's committed
3202 * to disk. If this metaslab is being initialized, we shouldn't
3203 * allocate from it since the allocated region might be
3204 * overwritten after allocation.
3206 if (msp
->ms_condensing
) {
3207 metaslab_trace_add(zal
, mg
, msp
, asize
, d
,
3208 TRACE_CONDENSING
, allocator
);
3209 metaslab_passivate(msp
, msp
->ms_weight
&
3210 ~METASLAB_ACTIVE_MASK
);
3211 mutex_exit(&msp
->ms_lock
);
3213 } else if (msp
->ms_initializing
> 0) {
3214 metaslab_trace_add(zal
, mg
, msp
, asize
, d
,
3215 TRACE_INITIALIZING
, allocator
);
3216 metaslab_passivate(msp
, msp
->ms_weight
&
3217 ~METASLAB_ACTIVE_MASK
);
3218 mutex_exit(&msp
->ms_lock
);
3222 offset
= metaslab_block_alloc(msp
, asize
, txg
);
3223 metaslab_trace_add(zal
, mg
, msp
, asize
, d
, offset
, allocator
);
3225 if (offset
!= -1ULL) {
3226 /* Proactively passivate the metaslab, if needed */
3227 metaslab_segment_may_passivate(msp
);
3231 ASSERT(msp
->ms_loaded
);
3234 * We were unable to allocate from this metaslab so determine
3235 * a new weight for this metaslab. Now that we have loaded
3236 * the metaslab we can provide a better hint to the metaslab
3239 * For space-based metaslabs, we use the maximum block size.
3240 * This information is only available when the metaslab
3241 * is loaded and is more accurate than the generic free
3242 * space weight that was calculated by metaslab_weight().
3243 * This information allows us to quickly compare the maximum
3244 * available allocation in the metaslab to the allocation
3245 * size being requested.
3247 * For segment-based metaslabs, determine the new weight
3248 * based on the highest bucket in the range tree. We
3249 * explicitly use the loaded segment weight (i.e. the range
3250 * tree histogram) since it contains the space that is
3251 * currently available for allocation and is accurate
3252 * even within a sync pass.
3254 if (WEIGHT_IS_SPACEBASED(msp
->ms_weight
)) {
3255 uint64_t weight
= metaslab_block_maxsize(msp
);
3256 WEIGHT_SET_SPACEBASED(weight
);
3257 metaslab_passivate(msp
, weight
);
3259 metaslab_passivate(msp
,
3260 metaslab_weight_from_range_tree(msp
));
3264 * We have just failed an allocation attempt, check
3265 * that metaslab_should_allocate() agrees. Otherwise,
3266 * we may end up in an infinite loop retrying the same
3269 ASSERT(!metaslab_should_allocate(msp
, asize
));
3270 mutex_exit(&msp
->ms_lock
);
3272 mutex_exit(&msp
->ms_lock
);
3273 kmem_free(search
, sizeof (*search
));
3278 metaslab_group_alloc(metaslab_group_t
*mg
, zio_alloc_list_t
*zal
,
3279 uint64_t asize
, uint64_t txg
, uint64_t min_distance
, dva_t
*dva
, int d
,
3283 ASSERT(mg
->mg_initialized
);
3285 offset
= metaslab_group_alloc_normal(mg
, zal
, asize
, txg
,
3286 min_distance
, dva
, d
, allocator
);
3288 mutex_enter(&mg
->mg_lock
);
3289 if (offset
== -1ULL) {
3290 mg
->mg_failed_allocations
++;
3291 metaslab_trace_add(zal
, mg
, NULL
, asize
, d
,
3292 TRACE_GROUP_FAILURE
, allocator
);
3293 if (asize
== SPA_GANGBLOCKSIZE
) {
3295 * This metaslab group was unable to allocate
3296 * the minimum gang block size so it must be out of
3297 * space. We must notify the allocation throttle
3298 * to start skipping allocation attempts to this
3299 * metaslab group until more space becomes available.
3300 * Note: this failure cannot be caused by the
3301 * allocation throttle since the allocation throttle
3302 * is only responsible for skipping devices and
3303 * not failing block allocations.
3305 mg
->mg_no_free_space
= B_TRUE
;
3308 mg
->mg_allocations
++;
3309 mutex_exit(&mg
->mg_lock
);
3314 * If we have to write a ditto block (i.e. more than one DVA for a given BP)
3315 * on the same vdev as an existing DVA of this BP, then try to allocate it
3316 * at least (vdev_asize / (2 ^ ditto_same_vdev_distance_shift)) away from the
3319 int ditto_same_vdev_distance_shift
= 3;
3322 * Allocate a block for the specified i/o.
3325 metaslab_alloc_dva(spa_t
*spa
, metaslab_class_t
*mc
, uint64_t psize
,
3326 dva_t
*dva
, int d
, dva_t
*hintdva
, uint64_t txg
, int flags
,
3327 zio_alloc_list_t
*zal
, int allocator
)
3329 metaslab_group_t
*mg
, *rotor
;
3331 boolean_t try_hard
= B_FALSE
;
3333 ASSERT(!DVA_IS_VALID(&dva
[d
]));
3336 * For testing, make some blocks above a certain size be gang blocks.
3338 if (psize
>= metaslab_force_ganging
&& (ddi_get_lbolt() & 3) == 0) {
3339 metaslab_trace_add(zal
, NULL
, NULL
, psize
, d
, TRACE_FORCE_GANG
,
3341 return (SET_ERROR(ENOSPC
));
3345 * Start at the rotor and loop through all mgs until we find something.
3346 * Note that there's no locking on mc_rotor or mc_aliquot because
3347 * nothing actually breaks if we miss a few updates -- we just won't
3348 * allocate quite as evenly. It all balances out over time.
3350 * If we are doing ditto or log blocks, try to spread them across
3351 * consecutive vdevs. If we're forced to reuse a vdev before we've
3352 * allocated all of our ditto blocks, then try and spread them out on
3353 * that vdev as much as possible. If it turns out to not be possible,
3354 * gradually lower our standards until anything becomes acceptable.
3355 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
3356 * gives us hope of containing our fault domains to something we're
3357 * able to reason about. Otherwise, any two top-level vdev failures
3358 * will guarantee the loss of data. With consecutive allocation,
3359 * only two adjacent top-level vdev failures will result in data loss.
3361 * If we are doing gang blocks (hintdva is non-NULL), try to keep
3362 * ourselves on the same vdev as our gang block header. That
3363 * way, we can hope for locality in vdev_cache, plus it makes our
3364 * fault domains something tractable.
3367 vd
= vdev_lookup_top(spa
, DVA_GET_VDEV(&hintdva
[d
]));
3370 * It's possible the vdev we're using as the hint no
3371 * longer exists or its mg has been closed (e.g. by
3372 * device removal). Consult the rotor when
3375 if (vd
!= NULL
&& vd
->vdev_mg
!= NULL
) {
3378 if (flags
& METASLAB_HINTBP_AVOID
&&
3379 mg
->mg_next
!= NULL
)
3384 } else if (d
!= 0) {
3385 vd
= vdev_lookup_top(spa
, DVA_GET_VDEV(&dva
[d
- 1]));
3386 mg
= vd
->vdev_mg
->mg_next
;
3392 * If the hint put us into the wrong metaslab class, or into a
3393 * metaslab group that has been passivated, just follow the rotor.
3395 if (mg
->mg_class
!= mc
|| mg
->mg_activation_count
<= 0)
3401 boolean_t allocatable
;
3403 ASSERT(mg
->mg_activation_count
== 1);
3407 * Don't allocate from faulted devices.
3410 spa_config_enter(spa
, SCL_ZIO
, FTAG
, RW_READER
);
3411 allocatable
= vdev_allocatable(vd
);
3412 spa_config_exit(spa
, SCL_ZIO
, FTAG
);
3414 allocatable
= vdev_allocatable(vd
);
3418 * Determine if the selected metaslab group is eligible
3419 * for allocations. If we're ganging then don't allow
3420 * this metaslab group to skip allocations since that would
3421 * inadvertently return ENOSPC and suspend the pool
3422 * even though space is still available.
3424 if (allocatable
&& !GANG_ALLOCATION(flags
) && !try_hard
) {
3425 allocatable
= metaslab_group_allocatable(mg
, rotor
,
3430 metaslab_trace_add(zal
, mg
, NULL
, psize
, d
,
3431 TRACE_NOT_ALLOCATABLE
, allocator
);
3435 ASSERT(mg
->mg_initialized
);
3438 * Avoid writing single-copy data to a failing,
3439 * non-redundant vdev, unless we've already tried all
3442 if ((vd
->vdev_stat
.vs_write_errors
> 0 ||
3443 vd
->vdev_state
< VDEV_STATE_HEALTHY
) &&
3444 d
== 0 && !try_hard
&& vd
->vdev_children
== 0) {
3445 metaslab_trace_add(zal
, mg
, NULL
, psize
, d
,
3446 TRACE_VDEV_ERROR
, allocator
);
3450 ASSERT(mg
->mg_class
== mc
);
3453 * If we don't need to try hard, then require that the
3454 * block be 1/8th of the device away from any other DVAs
3455 * in this BP. If we are trying hard, allow any offset
3456 * to be used (distance=0).
3458 uint64_t distance
= 0;
3460 distance
= vd
->vdev_asize
>>
3461 ditto_same_vdev_distance_shift
;
3462 if (distance
<= (1ULL << vd
->vdev_ms_shift
))
3466 uint64_t asize
= vdev_psize_to_asize(vd
, psize
);
3467 ASSERT(P2PHASE(asize
, 1ULL << vd
->vdev_ashift
) == 0);
3469 uint64_t offset
= metaslab_group_alloc(mg
, zal
, asize
, txg
,
3470 distance
, dva
, d
, allocator
);
3472 if (offset
!= -1ULL) {
3474 * If we've just selected this metaslab group,
3475 * figure out whether the corresponding vdev is
3476 * over- or under-used relative to the pool,
3477 * and set an allocation bias to even it out.
3479 if (mc
->mc_aliquot
== 0 && metaslab_bias_enabled
) {
3480 vdev_stat_t
*vs
= &vd
->vdev_stat
;
3483 vu
= (vs
->vs_alloc
* 100) / (vs
->vs_space
+ 1);
3484 cu
= (mc
->mc_alloc
* 100) / (mc
->mc_space
+ 1);
3487 * Calculate how much more or less we should
3488 * try to allocate from this device during
3489 * this iteration around the rotor.
3490 * For example, if a device is 80% full
3491 * and the pool is 20% full then we should
3492 * reduce allocations by 60% on this device.
3494 * mg_bias = (20 - 80) * 512K / 100 = -307K
3496 * This reduces allocations by 307K for this
3499 mg
->mg_bias
= ((cu
- vu
) *
3500 (int64_t)mg
->mg_aliquot
) / 100;
3501 } else if (!metaslab_bias_enabled
) {
3505 if (atomic_add_64_nv(&mc
->mc_aliquot
, asize
) >=
3506 mg
->mg_aliquot
+ mg
->mg_bias
) {
3507 mc
->mc_rotor
= mg
->mg_next
;
3511 DVA_SET_VDEV(&dva
[d
], vd
->vdev_id
);
3512 DVA_SET_OFFSET(&dva
[d
], offset
);
3513 DVA_SET_GANG(&dva
[d
], !!(flags
& METASLAB_GANG_HEADER
));
3514 DVA_SET_ASIZE(&dva
[d
], asize
);
3519 mc
->mc_rotor
= mg
->mg_next
;
3521 } while ((mg
= mg
->mg_next
) != rotor
);
3524 * If we haven't tried hard, do so now.
3531 bzero(&dva
[d
], sizeof (dva_t
));
3533 metaslab_trace_add(zal
, rotor
, NULL
, psize
, d
, TRACE_ENOSPC
, allocator
);
3534 return (SET_ERROR(ENOSPC
));
3538 metaslab_free_concrete(vdev_t
*vd
, uint64_t offset
, uint64_t asize
,
3539 boolean_t checkpoint
)
3542 spa_t
*spa
= vd
->vdev_spa
;
3544 ASSERT(vdev_is_concrete(vd
));
3545 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
3546 ASSERT3U(offset
>> vd
->vdev_ms_shift
, <, vd
->vdev_ms_count
);
3548 msp
= vd
->vdev_ms
[offset
>> vd
->vdev_ms_shift
];
3550 VERIFY(!msp
->ms_condensing
);
3551 VERIFY3U(offset
, >=, msp
->ms_start
);
3552 VERIFY3U(offset
+ asize
, <=, msp
->ms_start
+ msp
->ms_size
);
3553 VERIFY0(P2PHASE(offset
, 1ULL << vd
->vdev_ashift
));
3554 VERIFY0(P2PHASE(asize
, 1ULL << vd
->vdev_ashift
));
3556 metaslab_check_free_impl(vd
, offset
, asize
);
3558 mutex_enter(&msp
->ms_lock
);
3559 if (range_tree_is_empty(msp
->ms_freeing
) &&
3560 range_tree_is_empty(msp
->ms_checkpointing
)) {
3561 vdev_dirty(vd
, VDD_METASLAB
, msp
, spa_syncing_txg(spa
));
3565 ASSERT(spa_has_checkpoint(spa
));
3566 range_tree_add(msp
->ms_checkpointing
, offset
, asize
);
3568 range_tree_add(msp
->ms_freeing
, offset
, asize
);
3570 mutex_exit(&msp
->ms_lock
);
3575 metaslab_free_impl_cb(uint64_t inner_offset
, vdev_t
*vd
, uint64_t offset
,
3576 uint64_t size
, void *arg
)
3578 boolean_t
*checkpoint
= arg
;
3580 ASSERT3P(checkpoint
, !=, NULL
);
3582 if (vd
->vdev_ops
->vdev_op_remap
!= NULL
)
3583 vdev_indirect_mark_obsolete(vd
, offset
, size
);
3585 metaslab_free_impl(vd
, offset
, size
, *checkpoint
);
3589 metaslab_free_impl(vdev_t
*vd
, uint64_t offset
, uint64_t size
,
3590 boolean_t checkpoint
)
3592 spa_t
*spa
= vd
->vdev_spa
;
3594 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
3596 if (spa_syncing_txg(spa
) > spa_freeze_txg(spa
))
3599 if (spa
->spa_vdev_removal
!= NULL
&&
3600 spa
->spa_vdev_removal
->svr_vdev_id
== vd
->vdev_id
&&
3601 vdev_is_concrete(vd
)) {
3603 * Note: we check if the vdev is concrete because when
3604 * we complete the removal, we first change the vdev to be
3605 * an indirect vdev (in open context), and then (in syncing
3606 * context) clear spa_vdev_removal.
3608 free_from_removing_vdev(vd
, offset
, size
);
3609 } else if (vd
->vdev_ops
->vdev_op_remap
!= NULL
) {
3610 vdev_indirect_mark_obsolete(vd
, offset
, size
);
3611 vd
->vdev_ops
->vdev_op_remap(vd
, offset
, size
,
3612 metaslab_free_impl_cb
, &checkpoint
);
3614 metaslab_free_concrete(vd
, offset
, size
, checkpoint
);
3618 typedef struct remap_blkptr_cb_arg
{
3620 spa_remap_cb_t rbca_cb
;
3621 vdev_t
*rbca_remap_vd
;
3622 uint64_t rbca_remap_offset
;
3624 } remap_blkptr_cb_arg_t
;
3627 remap_blkptr_cb(uint64_t inner_offset
, vdev_t
*vd
, uint64_t offset
,
3628 uint64_t size
, void *arg
)
3630 remap_blkptr_cb_arg_t
*rbca
= arg
;
3631 blkptr_t
*bp
= rbca
->rbca_bp
;
3633 /* We can not remap split blocks. */
3634 if (size
!= DVA_GET_ASIZE(&bp
->blk_dva
[0]))
3636 ASSERT0(inner_offset
);
3638 if (rbca
->rbca_cb
!= NULL
) {
3640 * At this point we know that we are not handling split
3641 * blocks and we invoke the callback on the previous
3642 * vdev which must be indirect.
3644 ASSERT3P(rbca
->rbca_remap_vd
->vdev_ops
, ==, &vdev_indirect_ops
);
3646 rbca
->rbca_cb(rbca
->rbca_remap_vd
->vdev_id
,
3647 rbca
->rbca_remap_offset
, size
, rbca
->rbca_cb_arg
);
3649 /* set up remap_blkptr_cb_arg for the next call */
3650 rbca
->rbca_remap_vd
= vd
;
3651 rbca
->rbca_remap_offset
= offset
;
3655 * The phys birth time is that of dva[0]. This ensures that we know
3656 * when each dva was written, so that resilver can determine which
3657 * blocks need to be scrubbed (i.e. those written during the time
3658 * the vdev was offline). It also ensures that the key used in
3659 * the ARC hash table is unique (i.e. dva[0] + phys_birth). If
3660 * we didn't change the phys_birth, a lookup in the ARC for a
3661 * remapped BP could find the data that was previously stored at
3662 * this vdev + offset.
3664 vdev_t
*oldvd
= vdev_lookup_top(vd
->vdev_spa
,
3665 DVA_GET_VDEV(&bp
->blk_dva
[0]));
3666 vdev_indirect_births_t
*vib
= oldvd
->vdev_indirect_births
;
3667 bp
->blk_phys_birth
= vdev_indirect_births_physbirth(vib
,
3668 DVA_GET_OFFSET(&bp
->blk_dva
[0]), DVA_GET_ASIZE(&bp
->blk_dva
[0]));
3670 DVA_SET_VDEV(&bp
->blk_dva
[0], vd
->vdev_id
);
3671 DVA_SET_OFFSET(&bp
->blk_dva
[0], offset
);
3675 * If the block pointer contains any indirect DVAs, modify them to refer to
3676 * concrete DVAs. Note that this will sometimes not be possible, leaving
3677 * the indirect DVA in place. This happens if the indirect DVA spans multiple
3678 * segments in the mapping (i.e. it is a "split block").
3680 * If the BP was remapped, calls the callback on the original dva (note the
3681 * callback can be called multiple times if the original indirect DVA refers
3682 * to another indirect DVA, etc).
3684 * Returns TRUE if the BP was remapped.
3687 spa_remap_blkptr(spa_t
*spa
, blkptr_t
*bp
, spa_remap_cb_t callback
, void *arg
)
3689 remap_blkptr_cb_arg_t rbca
;
3691 if (!zfs_remap_blkptr_enable
)
3694 if (!spa_feature_is_enabled(spa
, SPA_FEATURE_OBSOLETE_COUNTS
))
3698 * Dedup BP's can not be remapped, because ddt_phys_select() depends
3699 * on DVA[0] being the same in the BP as in the DDT (dedup table).
3701 if (BP_GET_DEDUP(bp
))
3705 * Gang blocks can not be remapped, because
3706 * zio_checksum_gang_verifier() depends on the DVA[0] that's in
3707 * the BP used to read the gang block header (GBH) being the same
3708 * as the DVA[0] that we allocated for the GBH.
3714 * Embedded BP's have no DVA to remap.
3716 if (BP_GET_NDVAS(bp
) < 1)
3720 * Note: we only remap dva[0]. If we remapped other dvas, we
3721 * would no longer know what their phys birth txg is.
3723 dva_t
*dva
= &bp
->blk_dva
[0];
3725 uint64_t offset
= DVA_GET_OFFSET(dva
);
3726 uint64_t size
= DVA_GET_ASIZE(dva
);
3727 vdev_t
*vd
= vdev_lookup_top(spa
, DVA_GET_VDEV(dva
));
3729 if (vd
->vdev_ops
->vdev_op_remap
== NULL
)
3733 rbca
.rbca_cb
= callback
;
3734 rbca
.rbca_remap_vd
= vd
;
3735 rbca
.rbca_remap_offset
= offset
;
3736 rbca
.rbca_cb_arg
= arg
;
3739 * remap_blkptr_cb() will be called in order for each level of
3740 * indirection, until a concrete vdev is reached or a split block is
3741 * encountered. old_vd and old_offset are updated within the callback
3742 * as we go from the one indirect vdev to the next one (either concrete
3743 * or indirect again) in that order.
3745 vd
->vdev_ops
->vdev_op_remap(vd
, offset
, size
, remap_blkptr_cb
, &rbca
);
3747 /* Check if the DVA wasn't remapped because it is a split block */
3748 if (DVA_GET_VDEV(&rbca
.rbca_bp
->blk_dva
[0]) == vd
->vdev_id
)
3755 * Undo the allocation of a DVA which happened in the given transaction group.
3758 metaslab_unalloc_dva(spa_t
*spa
, const dva_t
*dva
, uint64_t txg
)
3762 uint64_t vdev
= DVA_GET_VDEV(dva
);
3763 uint64_t offset
= DVA_GET_OFFSET(dva
);
3764 uint64_t size
= DVA_GET_ASIZE(dva
);
3766 ASSERT(DVA_IS_VALID(dva
));
3767 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
3769 if (txg
> spa_freeze_txg(spa
))
3772 if ((vd
= vdev_lookup_top(spa
, vdev
)) == NULL
||
3773 (offset
>> vd
->vdev_ms_shift
) >= vd
->vdev_ms_count
) {
3774 cmn_err(CE_WARN
, "metaslab_free_dva(): bad DVA %llu:%llu",
3775 (u_longlong_t
)vdev
, (u_longlong_t
)offset
);
3780 ASSERT(!vd
->vdev_removing
);
3781 ASSERT(vdev_is_concrete(vd
));
3782 ASSERT0(vd
->vdev_indirect_config
.vic_mapping_object
);
3783 ASSERT3P(vd
->vdev_indirect_mapping
, ==, NULL
);
3785 if (DVA_GET_GANG(dva
))
3786 size
= vdev_psize_to_asize(vd
, SPA_GANGBLOCKSIZE
);
3788 msp
= vd
->vdev_ms
[offset
>> vd
->vdev_ms_shift
];
3790 mutex_enter(&msp
->ms_lock
);
3791 range_tree_remove(msp
->ms_allocating
[txg
& TXG_MASK
],
3794 VERIFY(!msp
->ms_condensing
);
3795 VERIFY3U(offset
, >=, msp
->ms_start
);
3796 VERIFY3U(offset
+ size
, <=, msp
->ms_start
+ msp
->ms_size
);
3797 VERIFY3U(range_tree_space(msp
->ms_allocatable
) + size
, <=,
3799 VERIFY0(P2PHASE(offset
, 1ULL << vd
->vdev_ashift
));
3800 VERIFY0(P2PHASE(size
, 1ULL << vd
->vdev_ashift
));
3801 range_tree_add(msp
->ms_allocatable
, offset
, size
);
3802 mutex_exit(&msp
->ms_lock
);
3806 * Free the block represented by the given DVA.
3809 metaslab_free_dva(spa_t
*spa
, const dva_t
*dva
, boolean_t checkpoint
)
3811 uint64_t vdev
= DVA_GET_VDEV(dva
);
3812 uint64_t offset
= DVA_GET_OFFSET(dva
);
3813 uint64_t size
= DVA_GET_ASIZE(dva
);
3814 vdev_t
*vd
= vdev_lookup_top(spa
, vdev
);
3816 ASSERT(DVA_IS_VALID(dva
));
3817 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
3819 if (DVA_GET_GANG(dva
)) {
3820 size
= vdev_psize_to_asize(vd
, SPA_GANGBLOCKSIZE
);
3823 metaslab_free_impl(vd
, offset
, size
, checkpoint
);
3827 * Reserve some allocation slots. The reservation system must be called
3828 * before we call into the allocator. If there aren't any available slots
3829 * then the I/O will be throttled until an I/O completes and its slots are
3830 * freed up. The function returns true if it was successful in placing
3834 metaslab_class_throttle_reserve(metaslab_class_t
*mc
, int slots
, int allocator
,
3835 zio_t
*zio
, int flags
)
3837 uint64_t available_slots
= 0;
3838 boolean_t slot_reserved
= B_FALSE
;
3839 uint64_t max
= mc
->mc_alloc_max_slots
[allocator
];
3841 ASSERT(mc
->mc_alloc_throttle_enabled
);
3842 mutex_enter(&mc
->mc_lock
);
3844 uint64_t reserved_slots
=
3845 refcount_count(&mc
->mc_alloc_slots
[allocator
]);
3846 if (reserved_slots
< max
)
3847 available_slots
= max
- reserved_slots
;
3849 if (slots
<= available_slots
|| GANG_ALLOCATION(flags
)) {
3851 * We reserve the slots individually so that we can unreserve
3852 * them individually when an I/O completes.
3854 for (int d
= 0; d
< slots
; d
++) {
3856 refcount_add(&mc
->mc_alloc_slots
[allocator
],
3859 zio
->io_flags
|= ZIO_FLAG_IO_ALLOCATING
;
3860 slot_reserved
= B_TRUE
;
3863 mutex_exit(&mc
->mc_lock
);
3864 return (slot_reserved
);
3868 metaslab_class_throttle_unreserve(metaslab_class_t
*mc
, int slots
,
3869 int allocator
, zio_t
*zio
)
3871 ASSERT(mc
->mc_alloc_throttle_enabled
);
3872 mutex_enter(&mc
->mc_lock
);
3873 for (int d
= 0; d
< slots
; d
++) {
3874 (void) refcount_remove(&mc
->mc_alloc_slots
[allocator
],
3877 mutex_exit(&mc
->mc_lock
);
3881 metaslab_claim_concrete(vdev_t
*vd
, uint64_t offset
, uint64_t size
,
3885 spa_t
*spa
= vd
->vdev_spa
;
3888 if (offset
>> vd
->vdev_ms_shift
>= vd
->vdev_ms_count
)
3891 ASSERT3P(vd
->vdev_ms
, !=, NULL
);
3892 msp
= vd
->vdev_ms
[offset
>> vd
->vdev_ms_shift
];
3894 mutex_enter(&msp
->ms_lock
);
3896 if ((txg
!= 0 && spa_writeable(spa
)) || !msp
->ms_loaded
)
3897 error
= metaslab_activate(msp
, 0, METASLAB_WEIGHT_CLAIM
);
3899 * No need to fail in that case; someone else has activated the
3900 * metaslab, but that doesn't preclude us from using it.
3906 !range_tree_contains(msp
->ms_allocatable
, offset
, size
))
3907 error
= SET_ERROR(ENOENT
);
3909 if (error
|| txg
== 0) { /* txg == 0 indicates dry run */
3910 mutex_exit(&msp
->ms_lock
);
3914 VERIFY(!msp
->ms_condensing
);
3915 VERIFY0(P2PHASE(offset
, 1ULL << vd
->vdev_ashift
));
3916 VERIFY0(P2PHASE(size
, 1ULL << vd
->vdev_ashift
));
3917 VERIFY3U(range_tree_space(msp
->ms_allocatable
) - size
, <=,
3919 range_tree_remove(msp
->ms_allocatable
, offset
, size
);
3921 if (spa_writeable(spa
)) { /* don't dirty if we're zdb(8) */
3922 if (range_tree_is_empty(msp
->ms_allocating
[txg
& TXG_MASK
]))
3923 vdev_dirty(vd
, VDD_METASLAB
, msp
, txg
);
3924 range_tree_add(msp
->ms_allocating
[txg
& TXG_MASK
],
3928 mutex_exit(&msp
->ms_lock
);
3933 typedef struct metaslab_claim_cb_arg_t
{
3936 } metaslab_claim_cb_arg_t
;
3940 metaslab_claim_impl_cb(uint64_t inner_offset
, vdev_t
*vd
, uint64_t offset
,
3941 uint64_t size
, void *arg
)
3943 metaslab_claim_cb_arg_t
*mcca_arg
= arg
;
3945 if (mcca_arg
->mcca_error
== 0) {
3946 mcca_arg
->mcca_error
= metaslab_claim_concrete(vd
, offset
,
3947 size
, mcca_arg
->mcca_txg
);
3952 metaslab_claim_impl(vdev_t
*vd
, uint64_t offset
, uint64_t size
, uint64_t txg
)
3954 if (vd
->vdev_ops
->vdev_op_remap
!= NULL
) {
3955 metaslab_claim_cb_arg_t arg
;
3958 * Only zdb(8) can claim on indirect vdevs. This is used
3959 * to detect leaks of mapped space (that are not accounted
3960 * for in the obsolete counts, spacemap, or bpobj).
3962 ASSERT(!spa_writeable(vd
->vdev_spa
));
3966 vd
->vdev_ops
->vdev_op_remap(vd
, offset
, size
,
3967 metaslab_claim_impl_cb
, &arg
);
3969 if (arg
.mcca_error
== 0) {
3970 arg
.mcca_error
= metaslab_claim_concrete(vd
,
3973 return (arg
.mcca_error
);
3975 return (metaslab_claim_concrete(vd
, offset
, size
, txg
));
3980 * Intent log support: upon opening the pool after a crash, notify the SPA
3981 * of blocks that the intent log has allocated for immediate write, but
3982 * which are still considered free by the SPA because the last transaction
3983 * group didn't commit yet.
3986 metaslab_claim_dva(spa_t
*spa
, const dva_t
*dva
, uint64_t txg
)
3988 uint64_t vdev
= DVA_GET_VDEV(dva
);
3989 uint64_t offset
= DVA_GET_OFFSET(dva
);
3990 uint64_t size
= DVA_GET_ASIZE(dva
);
3993 if ((vd
= vdev_lookup_top(spa
, vdev
)) == NULL
) {
3994 return (SET_ERROR(ENXIO
));
3997 ASSERT(DVA_IS_VALID(dva
));
3999 if (DVA_GET_GANG(dva
))
4000 size
= vdev_psize_to_asize(vd
, SPA_GANGBLOCKSIZE
);
4002 return (metaslab_claim_impl(vd
, offset
, size
, txg
));
4006 metaslab_alloc(spa_t
*spa
, metaslab_class_t
*mc
, uint64_t psize
, blkptr_t
*bp
,
4007 int ndvas
, uint64_t txg
, blkptr_t
*hintbp
, int flags
,
4008 zio_alloc_list_t
*zal
, zio_t
*zio
, int allocator
)
4010 dva_t
*dva
= bp
->blk_dva
;
4011 dva_t
*hintdva
= hintbp
->blk_dva
;
4014 ASSERT(bp
->blk_birth
== 0);
4015 ASSERT(BP_PHYSICAL_BIRTH(bp
) == 0);
4017 spa_config_enter(spa
, SCL_ALLOC
, FTAG
, RW_READER
);
4019 if (mc
->mc_rotor
== NULL
) { /* no vdevs in this class */
4020 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
4021 return (SET_ERROR(ENOSPC
));
4024 ASSERT(ndvas
> 0 && ndvas
<= spa_max_replication(spa
));
4025 ASSERT(BP_GET_NDVAS(bp
) == 0);
4026 ASSERT(hintbp
== NULL
|| ndvas
<= BP_GET_NDVAS(hintbp
));
4027 ASSERT3P(zal
, !=, NULL
);
4029 for (int d
= 0; d
< ndvas
; d
++) {
4030 error
= metaslab_alloc_dva(spa
, mc
, psize
, dva
, d
, hintdva
,
4031 txg
, flags
, zal
, allocator
);
4033 for (d
--; d
>= 0; d
--) {
4034 metaslab_unalloc_dva(spa
, &dva
[d
], txg
);
4035 metaslab_group_alloc_decrement(spa
,
4036 DVA_GET_VDEV(&dva
[d
]), zio
, flags
,
4037 allocator
, B_FALSE
);
4038 bzero(&dva
[d
], sizeof (dva_t
));
4040 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
4044 * Update the metaslab group's queue depth
4045 * based on the newly allocated dva.
4047 metaslab_group_alloc_increment(spa
,
4048 DVA_GET_VDEV(&dva
[d
]), zio
, flags
, allocator
);
4053 ASSERT(BP_GET_NDVAS(bp
) == ndvas
);
4055 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
4057 BP_SET_BIRTH(bp
, txg
, txg
);
4063 metaslab_free(spa_t
*spa
, const blkptr_t
*bp
, uint64_t txg
, boolean_t now
)
4065 const dva_t
*dva
= bp
->blk_dva
;
4066 int ndvas
= BP_GET_NDVAS(bp
);
4068 ASSERT(!BP_IS_HOLE(bp
));
4069 ASSERT(!now
|| bp
->blk_birth
>= spa_syncing_txg(spa
));
4072 * If we have a checkpoint for the pool we need to make sure that
4073 * the blocks that we free that are part of the checkpoint won't be
4074 * reused until the checkpoint is discarded or we revert to it.
4076 * The checkpoint flag is passed down the metaslab_free code path
4077 * and is set whenever we want to add a block to the checkpoint's
4078 * accounting. That is, we "checkpoint" blocks that existed at the
4079 * time the checkpoint was created and are therefore referenced by
4080 * the checkpointed uberblock.
4082 * Note that, we don't checkpoint any blocks if the current
4083 * syncing txg <= spa_checkpoint_txg. We want these frees to sync
4084 * normally as they will be referenced by the checkpointed uberblock.
4086 boolean_t checkpoint
= B_FALSE
;
4087 if (bp
->blk_birth
<= spa
->spa_checkpoint_txg
&&
4088 spa_syncing_txg(spa
) > spa
->spa_checkpoint_txg
) {
4090 * At this point, if the block is part of the checkpoint
4091 * there is no way it was created in the current txg.
4094 ASSERT3U(spa_syncing_txg(spa
), ==, txg
);
4095 checkpoint
= B_TRUE
;
4098 spa_config_enter(spa
, SCL_FREE
, FTAG
, RW_READER
);
4100 for (int d
= 0; d
< ndvas
; d
++) {
4102 metaslab_unalloc_dva(spa
, &dva
[d
], txg
);
4104 ASSERT3U(txg
, ==, spa_syncing_txg(spa
));
4105 metaslab_free_dva(spa
, &dva
[d
], checkpoint
);
4109 spa_config_exit(spa
, SCL_FREE
, FTAG
);
4113 metaslab_claim(spa_t
*spa
, const blkptr_t
*bp
, uint64_t txg
)
4115 const dva_t
*dva
= bp
->blk_dva
;
4116 int ndvas
= BP_GET_NDVAS(bp
);
4119 ASSERT(!BP_IS_HOLE(bp
));
4123 * First do a dry run to make sure all DVAs are claimable,
4124 * so we don't have to unwind from partial failures below.
4126 if ((error
= metaslab_claim(spa
, bp
, 0)) != 0)
4130 spa_config_enter(spa
, SCL_ALLOC
, FTAG
, RW_READER
);
4132 for (int d
= 0; d
< ndvas
; d
++)
4133 if ((error
= metaslab_claim_dva(spa
, &dva
[d
], txg
)) != 0)
4136 spa_config_exit(spa
, SCL_ALLOC
, FTAG
);
4138 ASSERT(error
== 0 || txg
== 0);
4145 metaslab_check_free_impl_cb(uint64_t inner
, vdev_t
*vd
, uint64_t offset
,
4146 uint64_t size
, void *arg
)
4148 if (vd
->vdev_ops
== &vdev_indirect_ops
)
4151 metaslab_check_free_impl(vd
, offset
, size
);
4155 metaslab_check_free_impl(vdev_t
*vd
, uint64_t offset
, uint64_t size
)
4158 spa_t
*spa
= vd
->vdev_spa
;
4160 if ((zfs_flags
& ZFS_DEBUG_ZIO_FREE
) == 0)
4163 if (vd
->vdev_ops
->vdev_op_remap
!= NULL
) {
4164 vd
->vdev_ops
->vdev_op_remap(vd
, offset
, size
,
4165 metaslab_check_free_impl_cb
, NULL
);
4169 ASSERT(vdev_is_concrete(vd
));
4170 ASSERT3U(offset
>> vd
->vdev_ms_shift
, <, vd
->vdev_ms_count
);
4171 ASSERT3U(spa_config_held(spa
, SCL_ALL
, RW_READER
), !=, 0);
4173 msp
= vd
->vdev_ms
[offset
>> vd
->vdev_ms_shift
];
4175 mutex_enter(&msp
->ms_lock
);
4177 range_tree_verify(msp
->ms_allocatable
, offset
, size
);
4179 range_tree_verify(msp
->ms_freeing
, offset
, size
);
4180 range_tree_verify(msp
->ms_checkpointing
, offset
, size
);
4181 range_tree_verify(msp
->ms_freed
, offset
, size
);
4182 for (int j
= 0; j
< TXG_DEFER_SIZE
; j
++)
4183 range_tree_verify(msp
->ms_defer
[j
], offset
, size
);
4184 mutex_exit(&msp
->ms_lock
);
4188 metaslab_check_free(spa_t
*spa
, const blkptr_t
*bp
)
4190 if ((zfs_flags
& ZFS_DEBUG_ZIO_FREE
) == 0)
4193 spa_config_enter(spa
, SCL_VDEV
, FTAG
, RW_READER
);
4194 for (int i
= 0; i
< BP_GET_NDVAS(bp
); i
++) {
4195 uint64_t vdev
= DVA_GET_VDEV(&bp
->blk_dva
[i
]);
4196 vdev_t
*vd
= vdev_lookup_top(spa
, vdev
);
4197 uint64_t offset
= DVA_GET_OFFSET(&bp
->blk_dva
[i
]);
4198 uint64_t size
= DVA_GET_ASIZE(&bp
->blk_dva
[i
]);
4200 if (DVA_GET_GANG(&bp
->blk_dva
[i
]))
4201 size
= vdev_psize_to_asize(vd
, SPA_GANGBLOCKSIZE
);
4203 ASSERT3P(vd
, !=, NULL
);
4205 metaslab_check_free_impl(vd
, offset
, size
);
4207 spa_config_exit(spa
, SCL_VDEV
, FTAG
);