]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/metaslab.c
vdev_disk: don't touch vbio after its handed off to the kernel
[mirror_zfs.git] / module / zfs / metaslab.c
CommitLineData
34dc7c2f
BB
1/*
2 * CDDL HEADER START
3 *
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.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
1d3ba0bf 9 * or https://opensource.org/licenses/CDDL-1.0.
34dc7c2f
BB
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
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]
18 *
19 * CDDL HEADER END
20 */
21/*
428870ff 22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
893a6d62 23 * Copyright (c) 2011, 2019 by Delphix. All rights reserved.
2e528b49 24 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
dce63135 25 * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
cc99f275 26 * Copyright (c) 2017, Intel Corporation.
34dc7c2f
BB
27 */
28
34dc7c2f 29#include <sys/zfs_context.h>
34dc7c2f
BB
30#include <sys/dmu.h>
31#include <sys/dmu_tx.h>
32#include <sys/space_map.h>
33#include <sys/metaslab_impl.h>
34#include <sys/vdev_impl.h>
b2255edc 35#include <sys/vdev_draid.h>
34dc7c2f 36#include <sys/zio.h>
93cf2076 37#include <sys/spa_impl.h>
f3a7f661 38#include <sys/zfeature.h>
a1d477c2 39#include <sys/vdev_indirect_mapping.h>
d2734cce 40#include <sys/zap.h>
ca577779 41#include <sys/btree.h>
34dc7c2f 42
3dfb57a3
DB
43#define GANG_ALLOCATION(flags) \
44 ((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER))
22c81dd8 45
e8fe6684
ED
46/*
47 * Metaslab granularity, in bytes. This is roughly similar to what would be
48 * referred to as the "stripe size" in traditional RAID arrays. In normal
c55b2932
AM
49 * operation, we will try to write this amount of data to each disk before
50 * moving on to the next top-level vdev.
e8fe6684 51 */
ab8d9c17 52static uint64_t metaslab_aliquot = 1024 * 1024;
e8fe6684 53
d830d479
MA
54/*
55 * For testing, make some blocks above a certain size be gang blocks.
56 */
ab8d9c17 57uint64_t metaslab_force_ganging = SPA_MAXBLOCKSIZE + 1;
34dc7c2f 58
46adb282
RN
59/*
60 * Of blocks of size >= metaslab_force_ganging, actually gang them this often.
61 */
62uint_t metaslab_force_ganging_pct = 3;
63
d2734cce 64/*
93e28d66
SD
65 * In pools where the log space map feature is not enabled we touch
66 * multiple metaslabs (and their respective space maps) with each
67 * transaction group. Thus, we benefit from having a small space map
d2734cce 68 * block size since it allows us to issue more I/O operations scattered
93e28d66
SD
69 * around the disk. So a sane default for the space map block size
70 * is 8~16K.
d2734cce 71 */
93e28d66
SD
72int zfs_metaslab_sm_blksz_no_log = (1 << 14);
73
74/*
75 * When the log space map feature is enabled, we accumulate a lot of
76 * changes per metaslab that are flushed once in a while so we benefit
77 * from a bigger block size like 128K for the metaslab space maps.
78 */
79int zfs_metaslab_sm_blksz_with_log = (1 << 17);
d2734cce 80
e51be066
GW
81/*
82 * The in-core space map representation is more compact than its on-disk form.
83 * The zfs_condense_pct determines how much more compact the in-core
4e21fd06 84 * space map representation must be before we compact it on-disk.
e51be066
GW
85 * Values should be greater than or equal to 100.
86 */
fdc2d303 87uint_t zfs_condense_pct = 200;
e51be066 88
b02fe35d
AR
89/*
90 * Condensing a metaslab is not guaranteed to actually reduce the amount of
91 * space used on disk. In particular, a space map uses data in increments of
96358617 92 * MAX(1 << ashift, space_map_blksz), so a metaslab might use the
b02fe35d
AR
93 * same number of blocks after condensing. Since the goal of condensing is to
94 * reduce the number of IOPs required to read the space map, we only want to
95 * condense when we can be sure we will reduce the number of blocks used by the
96 * space map. Unfortunately, we cannot precisely compute whether or not this is
97 * the case in metaslab_should_condense since we are holding ms_lock. Instead,
98 * we apply the following heuristic: do not condense a spacemap unless the
99 * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
100 * blocks.
101 */
18168da7 102static const int zfs_metaslab_condense_block_threshold = 4;
b02fe35d 103
ac72fac3
GW
104/*
105 * The zfs_mg_noalloc_threshold defines which metaslab groups should
106 * be eligible for allocation. The value is defined as a percentage of
f3a7f661 107 * free space. Metaslab groups that have more free space than
ac72fac3
GW
108 * zfs_mg_noalloc_threshold are always eligible for allocations. Once
109 * a metaslab group's free space is less than or equal to the
110 * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
111 * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
112 * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
113 * groups are allowed to accept allocations. Gang blocks are always
114 * eligible to allocate on any metaslab group. The default value of 0 means
115 * no metaslab group will be excluded based on this criterion.
116 */
fdc2d303 117static uint_t zfs_mg_noalloc_threshold = 0;
6d974228 118
f3a7f661
GW
119/*
120 * Metaslab groups are considered eligible for allocations if their
e1cfd73f 121 * fragmentation metric (measured as a percentage) is less than or
cb020f0d
SD
122 * equal to zfs_mg_fragmentation_threshold. If a metaslab group
123 * exceeds this threshold then it will be skipped unless all metaslab
124 * groups within the metaslab class have also crossed this threshold.
125 *
126 * This tunable was introduced to avoid edge cases where we continue
127 * allocating from very fragmented disks in our pool while other, less
128 * fragmented disks, exists. On the other hand, if all disks in the
129 * pool are uniformly approaching the threshold, the threshold can
130 * be a speed bump in performance, where we keep switching the disks
131 * that we allocate from (e.g. we allocate some segments from disk A
132 * making it bypassing the threshold while freeing segments from disk
133 * B getting its fragmentation below the threshold).
134 *
135 * Empirically, we've seen that our vdev selection for allocations is
136 * good enough that fragmentation increases uniformly across all vdevs
137 * the majority of the time. Thus we set the threshold percentage high
138 * enough to avoid hitting the speed bump on pools that are being pushed
139 * to the edge.
f3a7f661 140 */
fdc2d303 141static uint_t zfs_mg_fragmentation_threshold = 95;
f3a7f661
GW
142
143/*
144 * Allow metaslabs to keep their active state as long as their fragmentation
145 * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
146 * active metaslab that exceeds this threshold will no longer keep its active
147 * status allowing better metaslabs to be selected.
148 */
fdc2d303 149static uint_t zfs_metaslab_fragmentation_threshold = 70;
f3a7f661 150
428870ff 151/*
aa7d06a9 152 * When set will load all metaslabs when pool is first opened.
428870ff 153 */
18168da7 154int metaslab_debug_load = B_FALSE;
aa7d06a9
GW
155
156/*
157 * When set will prevent metaslabs from being unloaded.
158 */
18168da7 159static int metaslab_debug_unload = B_FALSE;
428870ff 160
9babb374
BB
161/*
162 * Minimum size which forces the dynamic allocator to change
428870ff 163 * it's allocation strategy. Once the space map cannot satisfy
9babb374
BB
164 * an allocation of this size then it switches to using more
165 * aggressive strategy (i.e search by size rather than offset).
166 */
4e21fd06 167uint64_t metaslab_df_alloc_threshold = SPA_OLD_MAXBLOCKSIZE;
9babb374
BB
168
169/*
170 * The minimum free space, in percent, which must be available
171 * in a space map to continue allocations in a first-fit fashion.
4e21fd06 172 * Once the space map's free space drops below this level we dynamically
9babb374
BB
173 * switch to using best-fit allocations.
174 */
fdc2d303 175uint_t metaslab_df_free_pct = 4;
428870ff 176
d3230d76
MA
177/*
178 * Maximum distance to search forward from the last offset. Without this
179 * limit, fragmented pools can see >100,000 iterations and
180 * metaslab_block_picker() becomes the performance limiting factor on
181 * high-performance storage.
182 *
183 * With the default setting of 16MB, we typically see less than 500
184 * iterations, even with very fragmented, ashift=9 pools. The maximum number
185 * of iterations possible is:
186 * metaslab_df_max_search / (2 * (1<<ashift))
187 * With the default setting of 16MB this is 16*1024 (with ashift=9) or
188 * 2048 (with ashift=12).
189 */
fdc2d303 190static uint_t metaslab_df_max_search = 16 * 1024 * 1024;
d3230d76 191
ca577779
PD
192/*
193 * Forces the metaslab_block_picker function to search for at least this many
194 * segments forwards until giving up on finding a segment that the allocation
195 * will fit into.
196 */
18168da7 197static const uint32_t metaslab_min_search_count = 100;
ca577779 198
d3230d76
MA
199/*
200 * If we are not searching forward (due to metaslab_df_max_search,
201 * metaslab_df_free_pct, or metaslab_df_alloc_threshold), this tunable
202 * controls what segment is used. If it is set, we will use the largest free
203 * segment. If it is not set, we will use a segment of exactly the requested
204 * size (or larger).
205 */
18168da7 206static int metaslab_df_use_largest_segment = B_FALSE;
d3230d76 207
428870ff 208/*
eef0f4d8
PD
209 * These tunables control how long a metaslab will remain loaded after the
210 * last allocation from it. A metaslab can't be unloaded until at least
211 * metaslab_unload_delay TXG's and metaslab_unload_delay_ms milliseconds
212 * have elapsed. However, zfs_metaslab_mem_limit may cause it to be
213 * unloaded sooner. These settings are intended to be generous -- to keep
214 * metaslabs loaded for a long time, reducing the rate of metaslab loading.
428870ff 215 */
fdc2d303
RY
216static uint_t metaslab_unload_delay = 32;
217static uint_t metaslab_unload_delay_ms = 10 * 60 * 1000; /* ten minutes */
9babb374 218
93cf2076
GW
219/*
220 * Max number of metaslabs per group to preload.
221 */
fdc2d303 222uint_t metaslab_preload_limit = 10;
93cf2076
GW
223
224/*
225 * Enable/disable preloading of metaslab.
226 */
18168da7 227static int metaslab_preload_enabled = B_TRUE;
93cf2076
GW
228
229/*
f3a7f661 230 * Enable/disable fragmentation weighting on metaslabs.
93cf2076 231 */
18168da7 232static int metaslab_fragmentation_factor_enabled = B_TRUE;
93cf2076 233
f3a7f661
GW
234/*
235 * Enable/disable lba weighting (i.e. outer tracks are given preference).
236 */
18168da7 237static int metaslab_lba_weighting_enabled = B_TRUE;
f3a7f661
GW
238
239/*
240 * Enable/disable metaslab group biasing.
241 */
18168da7 242static int metaslab_bias_enabled = B_TRUE;
f3a7f661 243
a1d477c2
MA
244/*
245 * Enable/disable remapping of indirect DVAs to their concrete vdevs.
246 */
18168da7 247static const boolean_t zfs_remap_blkptr_enable = B_TRUE;
a1d477c2 248
4e21fd06
DB
249/*
250 * Enable/disable segment-based metaslab selection.
251 */
18168da7 252static int zfs_metaslab_segment_weight_enabled = B_TRUE;
4e21fd06
DB
253
254/*
255 * When using segment-based metaslab selection, we will continue
256 * allocating from the active metaslab until we have exhausted
257 * zfs_metaslab_switch_threshold of its buckets.
258 */
18168da7 259static int zfs_metaslab_switch_threshold = 2;
4e21fd06
DB
260
261/*
262 * Internal switch to enable/disable the metaslab allocation tracing
263 * facility.
264 */
18168da7 265static const boolean_t metaslab_trace_enabled = B_FALSE;
4e21fd06
DB
266
267/*
268 * Maximum entries that the metaslab allocation tracing facility will keep
269 * in a given list when running in non-debug mode. We limit the number
270 * of entries in non-debug mode to prevent us from using up too much memory.
271 * The limit should be sufficiently large that we don't expect any allocation
272 * to every exceed this value. In debug mode, the system will panic if this
273 * limit is ever reached allowing for further investigation.
274 */
18168da7 275static const uint64_t metaslab_trace_max_entries = 5000;
4e21fd06 276
1b939560
BB
277/*
278 * Maximum number of metaslabs per group that can be disabled
279 * simultaneously.
280 */
18168da7 281static const int max_disabled_ms = 3;
1b939560 282
ca577779
PD
283/*
284 * Time (in seconds) to respect ms_max_size when the metaslab is not loaded.
285 * To avoid 64-bit overflow, don't set above UINT32_MAX.
286 */
ab8d9c17 287static uint64_t zfs_metaslab_max_size_cache_sec = 1 * 60 * 60; /* 1 hour */
ca577779 288
f09fda50
PD
289/*
290 * Maximum percentage of memory to use on storing loaded metaslabs. If loading
291 * a metaslab would take it over this percentage, the oldest selected metaslab
292 * is automatically unloaded.
293 */
fdc2d303 294static uint_t zfs_metaslab_mem_limit = 25;
eef0f4d8
PD
295
296/*
ca577779
PD
297 * Force the per-metaslab range trees to use 64-bit integers to store
298 * segments. Used for debugging purposes.
eef0f4d8 299 */
18168da7 300static const boolean_t zfs_metaslab_force_large_segs = B_FALSE;
ca577779
PD
301
302/*
303 * By default we only store segments over a certain size in the size-sorted
304 * metaslab trees (ms_allocatable_by_size and
305 * ms_unflushed_frees_by_size). This dramatically reduces memory usage and
306 * improves load and unload times at the cost of causing us to use slightly
307 * larger segments than we would otherwise in some cases.
308 */
18168da7 309static const uint32_t metaslab_by_size_min_shift = 14;
f09fda50 310
be5c6d96
MA
311/*
312 * If not set, we will first try normal allocation. If that fails then
313 * we will do a gang allocation. If that fails then we will do a "try hard"
314 * gang allocation. If that fails then we will have a multi-layer gang
315 * block.
316 *
317 * If set, we will first try normal allocation. If that fails then
318 * we will do a "try hard" allocation. If that fails we will do a gang
319 * allocation. If that fails we will do a "try hard" gang allocation. If
320 * that fails then we will have a multi-layer gang block.
321 */
18168da7 322static int zfs_metaslab_try_hard_before_gang = B_FALSE;
be5c6d96
MA
323
324/*
325 * When not trying hard, we only consider the best zfs_metaslab_find_max_tries
326 * metaslabs. This improves performance, especially when there are many
327 * metaslabs per vdev and the allocation can't actually be satisfied (so we
328 * would otherwise iterate all the metaslabs). If there is a metaslab with a
329 * worse weight but it can actually satisfy the allocation, we won't find it
330 * until trying hard. This may happen if the worse metaslab is not loaded
331 * (and the true weight is better than we have calculated), or due to weight
332 * bucketization. E.g. we are looking for a 60K segment, and the best
333 * metaslabs all have free segments in the 32-63K bucket, but the best
334 * zfs_metaslab_find_max_tries metaslabs have ms_max_size <60KB, and a
335 * subsequent metaslab has ms_max_size >60KB (but fewer segments in this
336 * bucket, and therefore a lower weight).
337 */
fdc2d303 338static uint_t zfs_metaslab_find_max_tries = 100;
be5c6d96 339
65a91b16
SD
340static uint64_t metaslab_weight(metaslab_t *, boolean_t);
341static void metaslab_set_fragmentation(metaslab_t *, boolean_t);
d2734cce 342static void metaslab_free_impl(vdev_t *, uint64_t, uint64_t, boolean_t);
a1d477c2 343static void metaslab_check_free_impl(vdev_t *, uint64_t, uint64_t);
4e21fd06 344
492f64e9
PD
345static void metaslab_passivate(metaslab_t *msp, uint64_t weight);
346static uint64_t metaslab_weight_from_range_tree(metaslab_t *msp);
93e28d66 347static void metaslab_flush_update(metaslab_t *, dmu_tx_t *);
f09fda50
PD
348static unsigned int metaslab_idx_func(multilist_t *, void *);
349static void metaslab_evict(metaslab_t *, uint64_t);
ca577779 350static void metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg);
4e21fd06 351kmem_cache_t *metaslab_alloc_trace_cache;
ca577779
PD
352
353typedef struct metaslab_stats {
354 kstat_named_t metaslabstat_trace_over_limit;
ca577779 355 kstat_named_t metaslabstat_reload_tree;
be5c6d96
MA
356 kstat_named_t metaslabstat_too_many_tries;
357 kstat_named_t metaslabstat_try_hard;
ca577779
PD
358} metaslab_stats_t;
359
360static metaslab_stats_t metaslab_stats = {
361 { "trace_over_limit", KSTAT_DATA_UINT64 },
ca577779 362 { "reload_tree", KSTAT_DATA_UINT64 },
be5c6d96
MA
363 { "too_many_tries", KSTAT_DATA_UINT64 },
364 { "try_hard", KSTAT_DATA_UINT64 },
ca577779
PD
365};
366
367#define METASLABSTAT_BUMP(stat) \
368 atomic_inc_64(&metaslab_stats.stat.value.ui64);
369
370
18168da7 371static kstat_t *metaslab_ksp;
ca577779
PD
372
373void
374metaslab_stat_init(void)
375{
376 ASSERT(metaslab_alloc_trace_cache == NULL);
377 metaslab_alloc_trace_cache = kmem_cache_create(
378 "metaslab_alloc_trace_cache", sizeof (metaslab_alloc_trace_t),
379 0, NULL, NULL, NULL, NULL, NULL, 0);
380 metaslab_ksp = kstat_create("zfs", 0, "metaslab_stats",
381 "misc", KSTAT_TYPE_NAMED, sizeof (metaslab_stats) /
382 sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
383 if (metaslab_ksp != NULL) {
384 metaslab_ksp->ks_data = &metaslab_stats;
385 kstat_install(metaslab_ksp);
386 }
387}
388
389void
390metaslab_stat_fini(void)
391{
392 if (metaslab_ksp != NULL) {
393 kstat_delete(metaslab_ksp);
394 metaslab_ksp = NULL;
395 }
396
397 kmem_cache_destroy(metaslab_alloc_trace_cache);
398 metaslab_alloc_trace_cache = NULL;
399}
93cf2076 400
34dc7c2f
BB
401/*
402 * ==========================================================================
403 * Metaslab classes
404 * ==========================================================================
405 */
406metaslab_class_t *
18168da7 407metaslab_class_create(spa_t *spa, const metaslab_ops_t *ops)
34dc7c2f
BB
408{
409 metaslab_class_t *mc;
410
f8020c93
AM
411 mc = kmem_zalloc(offsetof(metaslab_class_t,
412 mc_allocator[spa->spa_alloc_count]), KM_SLEEP);
34dc7c2f 413
428870ff 414 mc->mc_spa = spa;
9babb374 415 mc->mc_ops = ops;
3dfb57a3 416 mutex_init(&mc->mc_lock, NULL, MUTEX_DEFAULT, NULL);
ffdf019c 417 multilist_create(&mc->mc_metaslab_txg_list, sizeof (metaslab_t),
f09fda50 418 offsetof(metaslab_t, ms_class_txg_node), metaslab_idx_func);
f8020c93
AM
419 for (int i = 0; i < spa->spa_alloc_count; i++) {
420 metaslab_class_allocator_t *mca = &mc->mc_allocator[i];
421 mca->mca_rotor = NULL;
422 zfs_refcount_create_tracked(&mca->mca_alloc_slots);
423 }
34dc7c2f
BB
424
425 return (mc);
426}
427
428void
429metaslab_class_destroy(metaslab_class_t *mc)
430{
f8020c93
AM
431 spa_t *spa = mc->mc_spa;
432
428870ff
BB
433 ASSERT(mc->mc_alloc == 0);
434 ASSERT(mc->mc_deferred == 0);
435 ASSERT(mc->mc_space == 0);
436 ASSERT(mc->mc_dspace == 0);
34dc7c2f 437
f8020c93
AM
438 for (int i = 0; i < spa->spa_alloc_count; i++) {
439 metaslab_class_allocator_t *mca = &mc->mc_allocator[i];
440 ASSERT(mca->mca_rotor == NULL);
441 zfs_refcount_destroy(&mca->mca_alloc_slots);
442 }
3dfb57a3 443 mutex_destroy(&mc->mc_lock);
ffdf019c 444 multilist_destroy(&mc->mc_metaslab_txg_list);
f8020c93
AM
445 kmem_free(mc, offsetof(metaslab_class_t,
446 mc_allocator[spa->spa_alloc_count]));
34dc7c2f
BB
447}
448
428870ff
BB
449int
450metaslab_class_validate(metaslab_class_t *mc)
34dc7c2f 451{
428870ff
BB
452 metaslab_group_t *mg;
453 vdev_t *vd;
34dc7c2f 454
428870ff
BB
455 /*
456 * Must hold one of the spa_config locks.
457 */
458 ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
459 spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
34dc7c2f 460
f8020c93 461 if ((mg = mc->mc_allocator[0].mca_rotor) == NULL)
428870ff
BB
462 return (0);
463
464 do {
465 vd = mg->mg_vd;
466 ASSERT(vd->vdev_mg != NULL);
467 ASSERT3P(vd->vdev_top, ==, vd);
468 ASSERT3P(mg->mg_class, ==, mc);
469 ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
f8020c93 470 } while ((mg = mg->mg_next) != mc->mc_allocator[0].mca_rotor);
428870ff
BB
471
472 return (0);
34dc7c2f
BB
473}
474
cc99f275 475static void
428870ff
BB
476metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
477 int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
34dc7c2f 478{
428870ff
BB
479 atomic_add_64(&mc->mc_alloc, alloc_delta);
480 atomic_add_64(&mc->mc_deferred, defer_delta);
481 atomic_add_64(&mc->mc_space, space_delta);
482 atomic_add_64(&mc->mc_dspace, dspace_delta);
483}
34dc7c2f 484
428870ff
BB
485uint64_t
486metaslab_class_get_alloc(metaslab_class_t *mc)
487{
488 return (mc->mc_alloc);
489}
34dc7c2f 490
428870ff
BB
491uint64_t
492metaslab_class_get_deferred(metaslab_class_t *mc)
493{
494 return (mc->mc_deferred);
495}
34dc7c2f 496
428870ff
BB
497uint64_t
498metaslab_class_get_space(metaslab_class_t *mc)
499{
500 return (mc->mc_space);
501}
34dc7c2f 502
428870ff
BB
503uint64_t
504metaslab_class_get_dspace(metaslab_class_t *mc)
505{
506 return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
34dc7c2f
BB
507}
508
f3a7f661
GW
509void
510metaslab_class_histogram_verify(metaslab_class_t *mc)
511{
cc99f275
DB
512 spa_t *spa = mc->mc_spa;
513 vdev_t *rvd = spa->spa_root_vdev;
f3a7f661 514 uint64_t *mc_hist;
1c27024e 515 int i;
f3a7f661
GW
516
517 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
518 return;
519
520 mc_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
79c76d5b 521 KM_SLEEP);
f3a7f661 522
a0e01997 523 mutex_enter(&mc->mc_lock);
1c27024e 524 for (int c = 0; c < rvd->vdev_children; c++) {
f3a7f661 525 vdev_t *tvd = rvd->vdev_child[c];
aa755b35 526 metaslab_group_t *mg = vdev_get_mg(tvd, mc);
f3a7f661
GW
527
528 /*
529 * Skip any holes, uninitialized top-levels, or
530 * vdevs that are not in this metalab class.
531 */
a1d477c2 532 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
f3a7f661
GW
533 mg->mg_class != mc) {
534 continue;
535 }
536
aa755b35
MA
537 IMPLY(mg == mg->mg_vd->vdev_log_mg,
538 mc == spa_embedded_log_class(mg->mg_vd->vdev_spa));
539
f3a7f661
GW
540 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
541 mc_hist[i] += mg->mg_histogram[i];
542 }
543
aa755b35 544 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
f3a7f661 545 VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
aa755b35 546 }
f3a7f661 547
a0e01997 548 mutex_exit(&mc->mc_lock);
f3a7f661
GW
549 kmem_free(mc_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
550}
551
552/*
553 * Calculate the metaslab class's fragmentation metric. The metric
554 * is weighted based on the space contribution of each metaslab group.
555 * The return value will be a number between 0 and 100 (inclusive), or
556 * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
557 * zfs_frag_table for more information about the metric.
558 */
559uint64_t
560metaslab_class_fragmentation(metaslab_class_t *mc)
561{
562 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
563 uint64_t fragmentation = 0;
f3a7f661
GW
564
565 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
566
1c27024e 567 for (int c = 0; c < rvd->vdev_children; c++) {
f3a7f661
GW
568 vdev_t *tvd = rvd->vdev_child[c];
569 metaslab_group_t *mg = tvd->vdev_mg;
570
571 /*
a1d477c2
MA
572 * Skip any holes, uninitialized top-levels,
573 * or vdevs that are not in this metalab class.
f3a7f661 574 */
a1d477c2 575 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
f3a7f661
GW
576 mg->mg_class != mc) {
577 continue;
578 }
579
580 /*
581 * If a metaslab group does not contain a fragmentation
582 * metric then just bail out.
583 */
584 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
585 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
586 return (ZFS_FRAG_INVALID);
587 }
588
589 /*
590 * Determine how much this metaslab_group is contributing
591 * to the overall pool fragmentation metric.
592 */
593 fragmentation += mg->mg_fragmentation *
594 metaslab_group_get_space(mg);
595 }
596 fragmentation /= metaslab_class_get_space(mc);
597
598 ASSERT3U(fragmentation, <=, 100);
599 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
600 return (fragmentation);
601}
602
603/*
604 * Calculate the amount of expandable space that is available in
605 * this metaslab class. If a device is expanded then its expandable
606 * space will be the amount of allocatable space that is currently not
607 * part of this metaslab class.
608 */
609uint64_t
610metaslab_class_expandable_space(metaslab_class_t *mc)
611{
612 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
613 uint64_t space = 0;
f3a7f661
GW
614
615 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
1c27024e 616 for (int c = 0; c < rvd->vdev_children; c++) {
f3a7f661
GW
617 vdev_t *tvd = rvd->vdev_child[c];
618 metaslab_group_t *mg = tvd->vdev_mg;
619
a1d477c2 620 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
f3a7f661
GW
621 mg->mg_class != mc) {
622 continue;
623 }
624
0f676dc2
GM
625 /*
626 * Calculate if we have enough space to add additional
627 * metaslabs. We report the expandable space in terms
628 * of the metaslab size since that's the unit of expansion.
629 */
630 space += P2ALIGN(tvd->vdev_max_asize - tvd->vdev_asize,
631 1ULL << tvd->vdev_ms_shift);
f3a7f661
GW
632 }
633 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
634 return (space);
635}
636
f09fda50
PD
637void
638metaslab_class_evict_old(metaslab_class_t *mc, uint64_t txg)
639{
ffdf019c 640 multilist_t *ml = &mc->mc_metaslab_txg_list;
f09fda50
PD
641 for (int i = 0; i < multilist_get_num_sublists(ml); i++) {
642 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
643 metaslab_t *msp = multilist_sublist_head(mls);
644 multilist_sublist_unlock(mls);
645 while (msp != NULL) {
646 mutex_enter(&msp->ms_lock);
f09fda50
PD
647
648 /*
649 * If the metaslab has been removed from the list
650 * (which could happen if we were at the memory limit
651 * and it was evicted during this loop), then we can't
652 * proceed and we should restart the sublist.
653 */
654 if (!multilist_link_active(&msp->ms_class_txg_node)) {
655 mutex_exit(&msp->ms_lock);
656 i--;
657 break;
658 }
659 mls = multilist_sublist_lock(ml, i);
660 metaslab_t *next_msp = multilist_sublist_next(mls, msp);
661 multilist_sublist_unlock(mls);
eef0f4d8
PD
662 if (txg >
663 msp->ms_selected_txg + metaslab_unload_delay &&
664 gethrtime() > msp->ms_selected_time +
665 (uint64_t)MSEC2NSEC(metaslab_unload_delay_ms)) {
666 metaslab_evict(msp, txg);
667 } else {
668 /*
669 * Once we've hit a metaslab selected too
670 * recently to evict, we're done evicting for
671 * now.
672 */
673 mutex_exit(&msp->ms_lock);
674 break;
675 }
f09fda50
PD
676 mutex_exit(&msp->ms_lock);
677 msp = next_msp;
678 }
679 }
680}
681
34dc7c2f
BB
682static int
683metaslab_compare(const void *x1, const void *x2)
684{
ee36c709
GN
685 const metaslab_t *m1 = (const metaslab_t *)x1;
686 const metaslab_t *m2 = (const metaslab_t *)x2;
34dc7c2f 687
492f64e9
PD
688 int sort1 = 0;
689 int sort2 = 0;
690 if (m1->ms_allocator != -1 && m1->ms_primary)
691 sort1 = 1;
692 else if (m1->ms_allocator != -1 && !m1->ms_primary)
693 sort1 = 2;
694 if (m2->ms_allocator != -1 && m2->ms_primary)
695 sort2 = 1;
696 else if (m2->ms_allocator != -1 && !m2->ms_primary)
697 sort2 = 2;
698
699 /*
700 * Sort inactive metaslabs first, then primaries, then secondaries. When
701 * selecting a metaslab to allocate from, an allocator first tries its
702 * primary, then secondary active metaslab. If it doesn't have active
703 * metaslabs, or can't allocate from them, it searches for an inactive
704 * metaslab to activate. If it can't find a suitable one, it will steal
705 * a primary or secondary metaslab from another allocator.
706 */
707 if (sort1 < sort2)
708 return (-1);
709 if (sort1 > sort2)
710 return (1);
711
ca577779 712 int cmp = TREE_CMP(m2->ms_weight, m1->ms_weight);
ee36c709
GN
713 if (likely(cmp))
714 return (cmp);
34dc7c2f 715
ca577779 716 IMPLY(TREE_CMP(m1->ms_start, m2->ms_start) == 0, m1 == m2);
34dc7c2f 717
ca577779 718 return (TREE_CMP(m1->ms_start, m2->ms_start));
34dc7c2f
BB
719}
720
4e21fd06
DB
721/*
722 * ==========================================================================
723 * Metaslab groups
724 * ==========================================================================
725 */
ac72fac3
GW
726/*
727 * Update the allocatable flag and the metaslab group's capacity.
728 * The allocatable flag is set to true if the capacity is below
3dfb57a3
DB
729 * the zfs_mg_noalloc_threshold or has a fragmentation value that is
730 * greater than zfs_mg_fragmentation_threshold. If a metaslab group
731 * transitions from allocatable to non-allocatable or vice versa then the
732 * metaslab group's class is updated to reflect the transition.
ac72fac3
GW
733 */
734static void
735metaslab_group_alloc_update(metaslab_group_t *mg)
736{
737 vdev_t *vd = mg->mg_vd;
738 metaslab_class_t *mc = mg->mg_class;
739 vdev_stat_t *vs = &vd->vdev_stat;
740 boolean_t was_allocatable;
3dfb57a3 741 boolean_t was_initialized;
ac72fac3
GW
742
743 ASSERT(vd == vd->vdev_top);
a1d477c2
MA
744 ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_READER), ==,
745 SCL_ALLOC);
ac72fac3
GW
746
747 mutex_enter(&mg->mg_lock);
748 was_allocatable = mg->mg_allocatable;
3dfb57a3 749 was_initialized = mg->mg_initialized;
ac72fac3
GW
750
751 mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
752 (vs->vs_space + 1);
753
3dfb57a3
DB
754 mutex_enter(&mc->mc_lock);
755
756 /*
757 * If the metaslab group was just added then it won't
758 * have any space until we finish syncing out this txg.
759 * At that point we will consider it initialized and available
760 * for allocations. We also don't consider non-activated
761 * metaslab groups (e.g. vdevs that are in the middle of being removed)
762 * to be initialized, because they can't be used for allocation.
763 */
764 mg->mg_initialized = metaslab_group_initialized(mg);
765 if (!was_initialized && mg->mg_initialized) {
766 mc->mc_groups++;
767 } else if (was_initialized && !mg->mg_initialized) {
768 ASSERT3U(mc->mc_groups, >, 0);
769 mc->mc_groups--;
770 }
771 if (mg->mg_initialized)
772 mg->mg_no_free_space = B_FALSE;
773
f3a7f661
GW
774 /*
775 * A metaslab group is considered allocatable if it has plenty
776 * of free space or is not heavily fragmented. We only take
777 * fragmentation into account if the metaslab group has a valid
778 * fragmentation metric (i.e. a value between 0 and 100).
779 */
3dfb57a3
DB
780 mg->mg_allocatable = (mg->mg_activation_count > 0 &&
781 mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
f3a7f661
GW
782 (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
783 mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
ac72fac3
GW
784
785 /*
786 * The mc_alloc_groups maintains a count of the number of
787 * groups in this metaslab class that are still above the
788 * zfs_mg_noalloc_threshold. This is used by the allocating
789 * threads to determine if they should avoid allocations to
790 * a given group. The allocator will avoid allocations to a group
791 * if that group has reached or is below the zfs_mg_noalloc_threshold
792 * and there are still other groups that are above the threshold.
793 * When a group transitions from allocatable to non-allocatable or
794 * vice versa we update the metaslab class to reflect that change.
795 * When the mc_alloc_groups value drops to 0 that means that all
796 * groups have reached the zfs_mg_noalloc_threshold making all groups
797 * eligible for allocations. This effectively means that all devices
798 * are balanced again.
799 */
800 if (was_allocatable && !mg->mg_allocatable)
801 mc->mc_alloc_groups--;
802 else if (!was_allocatable && mg->mg_allocatable)
803 mc->mc_alloc_groups++;
3dfb57a3 804 mutex_exit(&mc->mc_lock);
f3a7f661 805
ac72fac3
GW
806 mutex_exit(&mg->mg_lock);
807}
808
93e28d66
SD
809int
810metaslab_sort_by_flushed(const void *va, const void *vb)
811{
812 const metaslab_t *a = va;
813 const metaslab_t *b = vb;
814
ca577779 815 int cmp = TREE_CMP(a->ms_unflushed_txg, b->ms_unflushed_txg);
93e28d66
SD
816 if (likely(cmp))
817 return (cmp);
818
819 uint64_t a_vdev_id = a->ms_group->mg_vd->vdev_id;
820 uint64_t b_vdev_id = b->ms_group->mg_vd->vdev_id;
ca577779 821 cmp = TREE_CMP(a_vdev_id, b_vdev_id);
93e28d66
SD
822 if (cmp)
823 return (cmp);
824
ca577779 825 return (TREE_CMP(a->ms_id, b->ms_id));
93e28d66
SD
826}
827
34dc7c2f 828metaslab_group_t *
492f64e9 829metaslab_group_create(metaslab_class_t *mc, vdev_t *vd, int allocators)
34dc7c2f
BB
830{
831 metaslab_group_t *mg;
832
f8020c93
AM
833 mg = kmem_zalloc(offsetof(metaslab_group_t,
834 mg_allocator[allocators]), KM_SLEEP);
34dc7c2f 835 mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
1b939560
BB
836 mutex_init(&mg->mg_ms_disabled_lock, NULL, MUTEX_DEFAULT, NULL);
837 cv_init(&mg->mg_ms_disabled_cv, NULL, CV_DEFAULT, NULL);
34dc7c2f 838 avl_create(&mg->mg_metaslab_tree, metaslab_compare,
93e28d66 839 sizeof (metaslab_t), offsetof(metaslab_t, ms_group_node));
34dc7c2f 840 mg->mg_vd = vd;
428870ff
BB
841 mg->mg_class = mc;
842 mg->mg_activation_count = 0;
3dfb57a3
DB
843 mg->mg_initialized = B_FALSE;
844 mg->mg_no_free_space = B_TRUE;
492f64e9
PD
845 mg->mg_allocators = allocators;
846
492f64e9 847 for (int i = 0; i < allocators; i++) {
32d805c3
MA
848 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
849 zfs_refcount_create_tracked(&mga->mga_alloc_queue_depth);
492f64e9 850 }
34dc7c2f
BB
851
852 return (mg);
853}
854
855void
856metaslab_group_destroy(metaslab_group_t *mg)
857{
428870ff
BB
858 ASSERT(mg->mg_prev == NULL);
859 ASSERT(mg->mg_next == NULL);
860 /*
861 * We may have gone below zero with the activation count
862 * either because we never activated in the first place or
863 * because we're done, and possibly removing the vdev.
864 */
865 ASSERT(mg->mg_activation_count <= 0);
866
34dc7c2f
BB
867 avl_destroy(&mg->mg_metaslab_tree);
868 mutex_destroy(&mg->mg_lock);
1b939560
BB
869 mutex_destroy(&mg->mg_ms_disabled_lock);
870 cv_destroy(&mg->mg_ms_disabled_cv);
492f64e9
PD
871
872 for (int i = 0; i < mg->mg_allocators; i++) {
32d805c3
MA
873 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
874 zfs_refcount_destroy(&mga->mga_alloc_queue_depth);
492f64e9 875 }
f8020c93
AM
876 kmem_free(mg, offsetof(metaslab_group_t,
877 mg_allocator[mg->mg_allocators]));
34dc7c2f
BB
878}
879
428870ff
BB
880void
881metaslab_group_activate(metaslab_group_t *mg)
882{
883 metaslab_class_t *mc = mg->mg_class;
f8020c93 884 spa_t *spa = mc->mc_spa;
428870ff
BB
885 metaslab_group_t *mgprev, *mgnext;
886
f8020c93 887 ASSERT3U(spa_config_held(spa, SCL_ALLOC, RW_WRITER), !=, 0);
428870ff 888
428870ff
BB
889 ASSERT(mg->mg_prev == NULL);
890 ASSERT(mg->mg_next == NULL);
891 ASSERT(mg->mg_activation_count <= 0);
892
893 if (++mg->mg_activation_count <= 0)
894 return;
895
c55b2932
AM
896 mg->mg_aliquot = metaslab_aliquot * MAX(1,
897 vdev_get_ndisks(mg->mg_vd) - vdev_get_nparity(mg->mg_vd));
ac72fac3 898 metaslab_group_alloc_update(mg);
428870ff 899
f8020c93 900 if ((mgprev = mc->mc_allocator[0].mca_rotor) == NULL) {
428870ff
BB
901 mg->mg_prev = mg;
902 mg->mg_next = mg;
903 } else {
904 mgnext = mgprev->mg_next;
905 mg->mg_prev = mgprev;
906 mg->mg_next = mgnext;
907 mgprev->mg_next = mg;
908 mgnext->mg_prev = mg;
909 }
f8020c93
AM
910 for (int i = 0; i < spa->spa_alloc_count; i++) {
911 mc->mc_allocator[i].mca_rotor = mg;
912 mg = mg->mg_next;
913 }
428870ff
BB
914}
915
a1d477c2
MA
916/*
917 * Passivate a metaslab group and remove it from the allocation rotor.
918 * Callers must hold both the SCL_ALLOC and SCL_ZIO lock prior to passivating
919 * a metaslab group. This function will momentarily drop spa_config_locks
920 * that are lower than the SCL_ALLOC lock (see comment below).
921 */
428870ff
BB
922void
923metaslab_group_passivate(metaslab_group_t *mg)
924{
925 metaslab_class_t *mc = mg->mg_class;
a1d477c2 926 spa_t *spa = mc->mc_spa;
428870ff 927 metaslab_group_t *mgprev, *mgnext;
a1d477c2 928 int locks = spa_config_held(spa, SCL_ALL, RW_WRITER);
428870ff 929
a1d477c2
MA
930 ASSERT3U(spa_config_held(spa, SCL_ALLOC | SCL_ZIO, RW_WRITER), ==,
931 (SCL_ALLOC | SCL_ZIO));
428870ff
BB
932
933 if (--mg->mg_activation_count != 0) {
f8020c93
AM
934 for (int i = 0; i < spa->spa_alloc_count; i++)
935 ASSERT(mc->mc_allocator[i].mca_rotor != mg);
428870ff
BB
936 ASSERT(mg->mg_prev == NULL);
937 ASSERT(mg->mg_next == NULL);
938 ASSERT(mg->mg_activation_count < 0);
939 return;
940 }
941
a1d477c2
MA
942 /*
943 * The spa_config_lock is an array of rwlocks, ordered as
944 * follows (from highest to lowest):
945 * SCL_CONFIG > SCL_STATE > SCL_L2ARC > SCL_ALLOC >
946 * SCL_ZIO > SCL_FREE > SCL_VDEV
947 * (For more information about the spa_config_lock see spa_misc.c)
948 * The higher the lock, the broader its coverage. When we passivate
949 * a metaslab group, we must hold both the SCL_ALLOC and the SCL_ZIO
950 * config locks. However, the metaslab group's taskq might be trying
951 * to preload metaslabs so we must drop the SCL_ZIO lock and any
952 * lower locks to allow the I/O to complete. At a minimum,
953 * we continue to hold the SCL_ALLOC lock, which prevents any future
954 * allocations from taking place and any changes to the vdev tree.
955 */
956 spa_config_exit(spa, locks & ~(SCL_ZIO - 1), spa);
342357cd 957 taskq_wait_outstanding(spa->spa_metaslab_taskq, 0);
a1d477c2 958 spa_config_enter(spa, locks & ~(SCL_ZIO - 1), spa, RW_WRITER);
f3a7f661 959 metaslab_group_alloc_update(mg);
492f64e9 960 for (int i = 0; i < mg->mg_allocators; i++) {
32d805c3
MA
961 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
962 metaslab_t *msp = mga->mga_primary;
492f64e9
PD
963 if (msp != NULL) {
964 mutex_enter(&msp->ms_lock);
965 metaslab_passivate(msp,
966 metaslab_weight_from_range_tree(msp));
967 mutex_exit(&msp->ms_lock);
968 }
32d805c3 969 msp = mga->mga_secondary;
492f64e9
PD
970 if (msp != NULL) {
971 mutex_enter(&msp->ms_lock);
972 metaslab_passivate(msp,
973 metaslab_weight_from_range_tree(msp));
974 mutex_exit(&msp->ms_lock);
975 }
976 }
93cf2076 977
428870ff
BB
978 mgprev = mg->mg_prev;
979 mgnext = mg->mg_next;
980
981 if (mg == mgnext) {
f8020c93 982 mgnext = NULL;
428870ff 983 } else {
428870ff
BB
984 mgprev->mg_next = mgnext;
985 mgnext->mg_prev = mgprev;
986 }
f8020c93
AM
987 for (int i = 0; i < spa->spa_alloc_count; i++) {
988 if (mc->mc_allocator[i].mca_rotor == mg)
989 mc->mc_allocator[i].mca_rotor = mgnext;
990 }
428870ff
BB
991
992 mg->mg_prev = NULL;
993 mg->mg_next = NULL;
994}
995
3dfb57a3
DB
996boolean_t
997metaslab_group_initialized(metaslab_group_t *mg)
998{
999 vdev_t *vd = mg->mg_vd;
1000 vdev_stat_t *vs = &vd->vdev_stat;
1001
1002 return (vs->vs_space != 0 && mg->mg_activation_count > 0);
1003}
1004
f3a7f661
GW
1005uint64_t
1006metaslab_group_get_space(metaslab_group_t *mg)
1007{
aa755b35
MA
1008 /*
1009 * Note that the number of nodes in mg_metaslab_tree may be one less
1010 * than vdev_ms_count, due to the embedded log metaslab.
1011 */
1012 mutex_enter(&mg->mg_lock);
1013 uint64_t ms_count = avl_numnodes(&mg->mg_metaslab_tree);
1014 mutex_exit(&mg->mg_lock);
1015 return ((1ULL << mg->mg_vd->vdev_ms_shift) * ms_count);
f3a7f661
GW
1016}
1017
1018void
1019metaslab_group_histogram_verify(metaslab_group_t *mg)
1020{
1021 uint64_t *mg_hist;
aa755b35
MA
1022 avl_tree_t *t = &mg->mg_metaslab_tree;
1023 uint64_t ashift = mg->mg_vd->vdev_ashift;
f3a7f661
GW
1024
1025 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
1026 return;
1027
1028 mg_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
79c76d5b 1029 KM_SLEEP);
f3a7f661
GW
1030
1031 ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE, >=,
1032 SPACE_MAP_HISTOGRAM_SIZE + ashift);
1033
aa755b35
MA
1034 mutex_enter(&mg->mg_lock);
1035 for (metaslab_t *msp = avl_first(t);
1036 msp != NULL; msp = AVL_NEXT(t, msp)) {
1037 VERIFY3P(msp->ms_group, ==, mg);
1038 /* skip if not active */
1039 if (msp->ms_sm == NULL)
f3a7f661
GW
1040 continue;
1041
aa755b35 1042 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
f3a7f661
GW
1043 mg_hist[i + ashift] +=
1044 msp->ms_sm->sm_phys->smp_histogram[i];
aa755b35 1045 }
f3a7f661
GW
1046 }
1047
aa755b35 1048 for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i ++)
f3a7f661
GW
1049 VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
1050
aa755b35
MA
1051 mutex_exit(&mg->mg_lock);
1052
f3a7f661
GW
1053 kmem_free(mg_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
1054}
1055
34dc7c2f 1056static void
f3a7f661 1057metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
34dc7c2f 1058{
f3a7f661
GW
1059 metaslab_class_t *mc = mg->mg_class;
1060 uint64_t ashift = mg->mg_vd->vdev_ashift;
f3a7f661
GW
1061
1062 ASSERT(MUTEX_HELD(&msp->ms_lock));
1063 if (msp->ms_sm == NULL)
1064 return;
1065
34dc7c2f 1066 mutex_enter(&mg->mg_lock);
a0e01997 1067 mutex_enter(&mc->mc_lock);
1c27024e 1068 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
aa755b35
MA
1069 IMPLY(mg == mg->mg_vd->vdev_log_mg,
1070 mc == spa_embedded_log_class(mg->mg_vd->vdev_spa));
f3a7f661
GW
1071 mg->mg_histogram[i + ashift] +=
1072 msp->ms_sm->sm_phys->smp_histogram[i];
1073 mc->mc_histogram[i + ashift] +=
1074 msp->ms_sm->sm_phys->smp_histogram[i];
1075 }
a0e01997 1076 mutex_exit(&mc->mc_lock);
f3a7f661
GW
1077 mutex_exit(&mg->mg_lock);
1078}
1079
1080void
1081metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
1082{
1083 metaslab_class_t *mc = mg->mg_class;
1084 uint64_t ashift = mg->mg_vd->vdev_ashift;
f3a7f661
GW
1085
1086 ASSERT(MUTEX_HELD(&msp->ms_lock));
1087 if (msp->ms_sm == NULL)
1088 return;
1089
1090 mutex_enter(&mg->mg_lock);
a0e01997 1091 mutex_enter(&mc->mc_lock);
1c27024e 1092 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
f3a7f661
GW
1093 ASSERT3U(mg->mg_histogram[i + ashift], >=,
1094 msp->ms_sm->sm_phys->smp_histogram[i]);
1095 ASSERT3U(mc->mc_histogram[i + ashift], >=,
1096 msp->ms_sm->sm_phys->smp_histogram[i]);
aa755b35
MA
1097 IMPLY(mg == mg->mg_vd->vdev_log_mg,
1098 mc == spa_embedded_log_class(mg->mg_vd->vdev_spa));
f3a7f661
GW
1099
1100 mg->mg_histogram[i + ashift] -=
1101 msp->ms_sm->sm_phys->smp_histogram[i];
1102 mc->mc_histogram[i + ashift] -=
1103 msp->ms_sm->sm_phys->smp_histogram[i];
1104 }
a0e01997 1105 mutex_exit(&mc->mc_lock);
f3a7f661
GW
1106 mutex_exit(&mg->mg_lock);
1107}
1108
1109static void
1110metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
1111{
34dc7c2f 1112 ASSERT(msp->ms_group == NULL);
f3a7f661 1113 mutex_enter(&mg->mg_lock);
34dc7c2f
BB
1114 msp->ms_group = mg;
1115 msp->ms_weight = 0;
1116 avl_add(&mg->mg_metaslab_tree, msp);
1117 mutex_exit(&mg->mg_lock);
f3a7f661
GW
1118
1119 mutex_enter(&msp->ms_lock);
1120 metaslab_group_histogram_add(mg, msp);
1121 mutex_exit(&msp->ms_lock);
34dc7c2f
BB
1122}
1123
1124static void
1125metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
1126{
f3a7f661
GW
1127 mutex_enter(&msp->ms_lock);
1128 metaslab_group_histogram_remove(mg, msp);
1129 mutex_exit(&msp->ms_lock);
1130
34dc7c2f
BB
1131 mutex_enter(&mg->mg_lock);
1132 ASSERT(msp->ms_group == mg);
1133 avl_remove(&mg->mg_metaslab_tree, msp);
f09fda50
PD
1134
1135 metaslab_class_t *mc = msp->ms_group->mg_class;
1136 multilist_sublist_t *mls =
ffdf019c 1137 multilist_sublist_lock_obj(&mc->mc_metaslab_txg_list, msp);
f09fda50
PD
1138 if (multilist_link_active(&msp->ms_class_txg_node))
1139 multilist_sublist_remove(mls, msp);
1140 multilist_sublist_unlock(mls);
1141
34dc7c2f
BB
1142 msp->ms_group = NULL;
1143 mutex_exit(&mg->mg_lock);
1144}
1145
492f64e9
PD
1146static void
1147metaslab_group_sort_impl(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1148{
679b0f2a 1149 ASSERT(MUTEX_HELD(&msp->ms_lock));
492f64e9
PD
1150 ASSERT(MUTEX_HELD(&mg->mg_lock));
1151 ASSERT(msp->ms_group == mg);
679b0f2a 1152
492f64e9
PD
1153 avl_remove(&mg->mg_metaslab_tree, msp);
1154 msp->ms_weight = weight;
1155 avl_add(&mg->mg_metaslab_tree, msp);
1156
1157}
1158
34dc7c2f
BB
1159static void
1160metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1161{
1162 /*
1163 * Although in principle the weight can be any value, in
f3a7f661 1164 * practice we do not use values in the range [1, 511].
34dc7c2f 1165 */
f3a7f661 1166 ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
34dc7c2f
BB
1167 ASSERT(MUTEX_HELD(&msp->ms_lock));
1168
1169 mutex_enter(&mg->mg_lock);
492f64e9 1170 metaslab_group_sort_impl(mg, msp, weight);
34dc7c2f
BB
1171 mutex_exit(&mg->mg_lock);
1172}
1173
f3a7f661
GW
1174/*
1175 * Calculate the fragmentation for a given metaslab group. We can use
1176 * a simple average here since all metaslabs within the group must have
1177 * the same size. The return value will be a value between 0 and 100
1178 * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
1179 * group have a fragmentation metric.
1180 */
1181uint64_t
1182metaslab_group_fragmentation(metaslab_group_t *mg)
1183{
1184 vdev_t *vd = mg->mg_vd;
1185 uint64_t fragmentation = 0;
1186 uint64_t valid_ms = 0;
f3a7f661 1187
1c27024e 1188 for (int m = 0; m < vd->vdev_ms_count; m++) {
f3a7f661
GW
1189 metaslab_t *msp = vd->vdev_ms[m];
1190
1191 if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
1192 continue;
cc99f275
DB
1193 if (msp->ms_group != mg)
1194 continue;
f3a7f661
GW
1195
1196 valid_ms++;
1197 fragmentation += msp->ms_fragmentation;
1198 }
1199
cc99f275 1200 if (valid_ms <= mg->mg_vd->vdev_ms_count / 2)
f3a7f661
GW
1201 return (ZFS_FRAG_INVALID);
1202
1203 fragmentation /= valid_ms;
1204 ASSERT3U(fragmentation, <=, 100);
1205 return (fragmentation);
1206}
1207
ac72fac3
GW
1208/*
1209 * Determine if a given metaslab group should skip allocations. A metaslab
f3a7f661
GW
1210 * group should avoid allocations if its free capacity is less than the
1211 * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
1212 * zfs_mg_fragmentation_threshold and there is at least one metaslab group
3dfb57a3
DB
1213 * that can still handle allocations. If the allocation throttle is enabled
1214 * then we skip allocations to devices that have reached their maximum
1215 * allocation queue depth unless the selected metaslab group is the only
1216 * eligible group remaining.
ac72fac3
GW
1217 */
1218static boolean_t
3dfb57a3 1219metaslab_group_allocatable(metaslab_group_t *mg, metaslab_group_t *rotor,
7bf4c97a 1220 int flags, uint64_t psize, int allocator, int d)
ac72fac3 1221{
3dfb57a3 1222 spa_t *spa = mg->mg_vd->vdev_spa;
ac72fac3
GW
1223 metaslab_class_t *mc = mg->mg_class;
1224
1225 /*
3dfb57a3
DB
1226 * We can only consider skipping this metaslab group if it's
1227 * in the normal metaslab class and there are other metaslab
1228 * groups to select from. Otherwise, we always consider it eligible
f3a7f661 1229 * for allocations.
ac72fac3 1230 */
cc99f275
DB
1231 if ((mc != spa_normal_class(spa) &&
1232 mc != spa_special_class(spa) &&
1233 mc != spa_dedup_class(spa)) ||
1234 mc->mc_groups <= 1)
3dfb57a3
DB
1235 return (B_TRUE);
1236
1237 /*
1238 * If the metaslab group's mg_allocatable flag is set (see comments
1239 * in metaslab_group_alloc_update() for more information) and
1240 * the allocation throttle is disabled then allow allocations to this
1241 * device. However, if the allocation throttle is enabled then
f8020c93 1242 * check if we have reached our allocation limit (mga_alloc_queue_depth)
3dfb57a3
DB
1243 * to determine if we should allow allocations to this metaslab group.
1244 * If all metaslab groups are no longer considered allocatable
1245 * (mc_alloc_groups == 0) or we're trying to allocate the smallest
1246 * gang block size then we allow allocations on this metaslab group
1247 * regardless of the mg_allocatable or throttle settings.
1248 */
1249 if (mg->mg_allocatable) {
32d805c3 1250 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
3dfb57a3 1251 int64_t qdepth;
32d805c3 1252 uint64_t qmax = mga->mga_cur_max_alloc_queue_depth;
3dfb57a3
DB
1253
1254 if (!mc->mc_alloc_throttle_enabled)
1255 return (B_TRUE);
1256
1257 /*
1258 * If this metaslab group does not have any free space, then
1259 * there is no point in looking further.
1260 */
1261 if (mg->mg_no_free_space)
1262 return (B_FALSE);
1263
7bf4c97a
SD
1264 /*
1265 * Some allocations (e.g., those coming from device removal
1266 * where the * allocations are not even counted in the
1267 * metaslab * allocation queues) are allowed to bypass
1268 * the throttle.
1269 */
1270 if (flags & METASLAB_DONT_THROTTLE)
1271 return (B_TRUE);
1272
c197a77c 1273 /*
1274 * Relax allocation throttling for ditto blocks. Due to
1275 * random imbalances in allocation it tends to push copies
1276 * to one vdev, that looks a bit better at the moment.
1277 */
1278 qmax = qmax * (4 + d) / 4;
1279
32d805c3 1280 qdepth = zfs_refcount_count(&mga->mga_alloc_queue_depth);
3dfb57a3
DB
1281
1282 /*
1283 * If this metaslab group is below its qmax or it's
a97b8fc2 1284 * the only allocatable metaslab group, then attempt
3dfb57a3
DB
1285 * to allocate from it.
1286 */
1287 if (qdepth < qmax || mc->mc_alloc_groups == 1)
1288 return (B_TRUE);
1289 ASSERT3U(mc->mc_alloc_groups, >, 1);
1290
1291 /*
1292 * Since this metaslab group is at or over its qmax, we
1293 * need to determine if there are metaslab groups after this
1294 * one that might be able to handle this allocation. This is
1295 * racy since we can't hold the locks for all metaslab
1296 * groups at the same time when we make this check.
1297 */
32d805c3
MA
1298 for (metaslab_group_t *mgp = mg->mg_next;
1299 mgp != rotor; mgp = mgp->mg_next) {
1300 metaslab_group_allocator_t *mgap =
1301 &mgp->mg_allocator[allocator];
1302 qmax = mgap->mga_cur_max_alloc_queue_depth;
c197a77c 1303 qmax = qmax * (4 + d) / 4;
32d805c3
MA
1304 qdepth =
1305 zfs_refcount_count(&mgap->mga_alloc_queue_depth);
3dfb57a3
DB
1306
1307 /*
1308 * If there is another metaslab group that
1309 * might be able to handle the allocation, then
1310 * we return false so that we skip this group.
1311 */
1312 if (qdepth < qmax && !mgp->mg_no_free_space)
1313 return (B_FALSE);
1314 }
1315
1316 /*
1317 * We didn't find another group to handle the allocation
1318 * so we can't skip this metaslab group even though
1319 * we are at or over our qmax.
1320 */
1321 return (B_TRUE);
1322
1323 } else if (mc->mc_alloc_groups == 0 || psize == SPA_MINBLOCKSIZE) {
1324 return (B_TRUE);
1325 }
1326 return (B_FALSE);
ac72fac3
GW
1327}
1328
428870ff
BB
1329/*
1330 * ==========================================================================
93cf2076 1331 * Range tree callbacks
428870ff
BB
1332 * ==========================================================================
1333 */
93cf2076
GW
1334
1335/*
ca577779
PD
1336 * Comparison function for the private size-ordered tree using 32-bit
1337 * ranges. Tree is sorted by size, larger sizes at the end of the tree.
93cf2076 1338 */
677c6f84 1339__attribute__((always_inline)) inline
428870ff 1340static int
ca577779 1341metaslab_rangesize32_compare(const void *x1, const void *x2)
428870ff 1342{
ca577779
PD
1343 const range_seg32_t *r1 = x1;
1344 const range_seg32_t *r2 = x2;
1345
93cf2076
GW
1346 uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1347 uint64_t rs_size2 = r2->rs_end - r2->rs_start;
428870ff 1348
ca577779 1349 int cmp = TREE_CMP(rs_size1, rs_size2);
428870ff 1350
677c6f84 1351 return (cmp + !cmp * TREE_CMP(r1->rs_start, r2->rs_start));
428870ff
BB
1352}
1353
ca577779
PD
1354/*
1355 * Comparison function for the private size-ordered tree using 64-bit
1356 * ranges. Tree is sorted by size, larger sizes at the end of the tree.
1357 */
677c6f84 1358__attribute__((always_inline)) inline
ca577779
PD
1359static int
1360metaslab_rangesize64_compare(const void *x1, const void *x2)
1361{
1362 const range_seg64_t *r1 = x1;
1363 const range_seg64_t *r2 = x2;
1364
1365 uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1366 uint64_t rs_size2 = r2->rs_end - r2->rs_start;
1367
1368 int cmp = TREE_CMP(rs_size1, rs_size2);
ca577779 1369
677c6f84 1370 return (cmp + !cmp * TREE_CMP(r1->rs_start, r2->rs_start));
ca577779 1371}
677c6f84 1372
ca577779
PD
1373typedef struct metaslab_rt_arg {
1374 zfs_btree_t *mra_bt;
1375 uint32_t mra_floor_shift;
1376} metaslab_rt_arg_t;
1377
1378struct mssa_arg {
1379 range_tree_t *rt;
1380 metaslab_rt_arg_t *mra;
1381};
1382
1383static void
1384metaslab_size_sorted_add(void *arg, uint64_t start, uint64_t size)
1385{
1386 struct mssa_arg *mssap = arg;
1387 range_tree_t *rt = mssap->rt;
1388 metaslab_rt_arg_t *mrap = mssap->mra;
1389 range_seg_max_t seg = {0};
1390 rs_set_start(&seg, rt, start);
1391 rs_set_end(&seg, rt, start + size);
1392 metaslab_rt_add(rt, &seg, mrap);
1393}
1394
1395static void
1396metaslab_size_tree_full_load(range_tree_t *rt)
1397{
1398 metaslab_rt_arg_t *mrap = rt->rt_arg;
ca577779 1399 METASLABSTAT_BUMP(metaslabstat_reload_tree);
ca577779
PD
1400 ASSERT0(zfs_btree_numnodes(mrap->mra_bt));
1401 mrap->mra_floor_shift = 0;
1402 struct mssa_arg arg = {0};
1403 arg.rt = rt;
1404 arg.mra = mrap;
1405 range_tree_walk(rt, metaslab_size_sorted_add, &arg);
1406}
1407
677c6f84
RY
1408
1409ZFS_BTREE_FIND_IN_BUF_FUNC(metaslab_rt_find_rangesize32_in_buf,
1410 range_seg32_t, metaslab_rangesize32_compare)
1411
1412ZFS_BTREE_FIND_IN_BUF_FUNC(metaslab_rt_find_rangesize64_in_buf,
1413 range_seg64_t, metaslab_rangesize64_compare)
1414
ca577779
PD
1415/*
1416 * Create any block allocator specific components. The current allocators
1417 * rely on using both a size-ordered range_tree_t and an array of uint64_t's.
1418 */
ca577779
PD
1419static void
1420metaslab_rt_create(range_tree_t *rt, void *arg)
1421{
1422 metaslab_rt_arg_t *mrap = arg;
1423 zfs_btree_t *size_tree = mrap->mra_bt;
1424
1425 size_t size;
1426 int (*compare) (const void *, const void *);
677c6f84 1427 bt_find_in_buf_f bt_find;
ca577779
PD
1428 switch (rt->rt_type) {
1429 case RANGE_SEG32:
1430 size = sizeof (range_seg32_t);
1431 compare = metaslab_rangesize32_compare;
677c6f84 1432 bt_find = metaslab_rt_find_rangesize32_in_buf;
ca577779
PD
1433 break;
1434 case RANGE_SEG64:
1435 size = sizeof (range_seg64_t);
1436 compare = metaslab_rangesize64_compare;
677c6f84 1437 bt_find = metaslab_rt_find_rangesize64_in_buf;
ca577779
PD
1438 break;
1439 default:
1440 panic("Invalid range seg type %d", rt->rt_type);
1441 }
677c6f84 1442 zfs_btree_create(size_tree, compare, bt_find, size);
ca577779
PD
1443 mrap->mra_floor_shift = metaslab_by_size_min_shift;
1444}
1445
ca577779
PD
1446static void
1447metaslab_rt_destroy(range_tree_t *rt, void *arg)
1448{
14e4e3cb 1449 (void) rt;
ca577779
PD
1450 metaslab_rt_arg_t *mrap = arg;
1451 zfs_btree_t *size_tree = mrap->mra_bt;
1452
1453 zfs_btree_destroy(size_tree);
1454 kmem_free(mrap, sizeof (*mrap));
1455}
1456
ca577779
PD
1457static void
1458metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg)
1459{
1460 metaslab_rt_arg_t *mrap = arg;
1461 zfs_btree_t *size_tree = mrap->mra_bt;
1462
1463 if (rs_get_end(rs, rt) - rs_get_start(rs, rt) <
e506a0ce 1464 (1ULL << mrap->mra_floor_shift))
ca577779
PD
1465 return;
1466
1467 zfs_btree_add(size_tree, rs);
1468}
1469
ca577779
PD
1470static void
1471metaslab_rt_remove(range_tree_t *rt, range_seg_t *rs, void *arg)
1472{
1473 metaslab_rt_arg_t *mrap = arg;
1474 zfs_btree_t *size_tree = mrap->mra_bt;
1475
e506a0ce 1476 if (rs_get_end(rs, rt) - rs_get_start(rs, rt) < (1ULL <<
ca577779
PD
1477 mrap->mra_floor_shift))
1478 return;
1479
1480 zfs_btree_remove(size_tree, rs);
1481}
1482
ca577779
PD
1483static void
1484metaslab_rt_vacate(range_tree_t *rt, void *arg)
1485{
1486 metaslab_rt_arg_t *mrap = arg;
1487 zfs_btree_t *size_tree = mrap->mra_bt;
1488 zfs_btree_clear(size_tree);
1489 zfs_btree_destroy(size_tree);
1490
1491 metaslab_rt_create(rt, arg);
1492}
1493
18168da7 1494static const range_tree_ops_t metaslab_rt_ops = {
ca577779
PD
1495 .rtop_create = metaslab_rt_create,
1496 .rtop_destroy = metaslab_rt_destroy,
1497 .rtop_add = metaslab_rt_add,
1498 .rtop_remove = metaslab_rt_remove,
1499 .rtop_vacate = metaslab_rt_vacate
1500};
1501
93cf2076
GW
1502/*
1503 * ==========================================================================
4e21fd06 1504 * Common allocator routines
93cf2076
GW
1505 * ==========================================================================
1506 */
1507
9babb374 1508/*
428870ff 1509 * Return the maximum contiguous segment within the metaslab.
9babb374 1510 */
9babb374 1511uint64_t
c81f1790 1512metaslab_largest_allocatable(metaslab_t *msp)
9babb374 1513{
ca577779 1514 zfs_btree_t *t = &msp->ms_allocatable_by_size;
93cf2076 1515 range_seg_t *rs;
9babb374 1516
c81f1790
PD
1517 if (t == NULL)
1518 return (0);
ca577779
PD
1519 if (zfs_btree_numnodes(t) == 0)
1520 metaslab_size_tree_full_load(msp->ms_allocatable);
1521
1522 rs = zfs_btree_last(t, NULL);
c81f1790
PD
1523 if (rs == NULL)
1524 return (0);
9babb374 1525
ca577779
PD
1526 return (rs_get_end(rs, msp->ms_allocatable) - rs_get_start(rs,
1527 msp->ms_allocatable));
93cf2076
GW
1528}
1529
c81f1790
PD
1530/*
1531 * Return the maximum contiguous segment within the unflushed frees of this
1532 * metaslab.
1533 */
65c7cc49 1534static uint64_t
c81f1790
PD
1535metaslab_largest_unflushed_free(metaslab_t *msp)
1536{
1537 ASSERT(MUTEX_HELD(&msp->ms_lock));
1538
1539 if (msp->ms_unflushed_frees == NULL)
1540 return (0);
1541
ca577779
PD
1542 if (zfs_btree_numnodes(&msp->ms_unflushed_frees_by_size) == 0)
1543 metaslab_size_tree_full_load(msp->ms_unflushed_frees);
1544 range_seg_t *rs = zfs_btree_last(&msp->ms_unflushed_frees_by_size,
1545 NULL);
c81f1790
PD
1546 if (rs == NULL)
1547 return (0);
1548
1549 /*
1550 * When a range is freed from the metaslab, that range is added to
1551 * both the unflushed frees and the deferred frees. While the block
1552 * will eventually be usable, if the metaslab were loaded the range
1553 * would not be added to the ms_allocatable tree until TXG_DEFER_SIZE
1554 * txgs had passed. As a result, when attempting to estimate an upper
1555 * bound for the largest currently-usable free segment in the
1556 * metaslab, we need to not consider any ranges currently in the defer
1557 * trees. This algorithm approximates the largest available chunk in
1558 * the largest range in the unflushed_frees tree by taking the first
1559 * chunk. While this may be a poor estimate, it should only remain so
1560 * briefly and should eventually self-correct as frees are no longer
1561 * deferred. Similar logic applies to the ms_freed tree. See
1562 * metaslab_load() for more details.
1563 *
e1cfd73f 1564 * There are two primary sources of inaccuracy in this estimate. Both
c81f1790
PD
1565 * are tolerated for performance reasons. The first source is that we
1566 * only check the largest segment for overlaps. Smaller segments may
1567 * have more favorable overlaps with the other trees, resulting in
1568 * larger usable chunks. Second, we only look at the first chunk in
1569 * the largest segment; there may be other usable chunks in the
1570 * largest segment, but we ignore them.
1571 */
ca577779
PD
1572 uint64_t rstart = rs_get_start(rs, msp->ms_unflushed_frees);
1573 uint64_t rsize = rs_get_end(rs, msp->ms_unflushed_frees) - rstart;
c81f1790
PD
1574 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1575 uint64_t start = 0;
1576 uint64_t size = 0;
1577 boolean_t found = range_tree_find_in(msp->ms_defer[t], rstart,
1578 rsize, &start, &size);
1579 if (found) {
1580 if (rstart == start)
1581 return (0);
1582 rsize = start - rstart;
1583 }
1584 }
1585
1586 uint64_t start = 0;
1587 uint64_t size = 0;
1588 boolean_t found = range_tree_find_in(msp->ms_freed, rstart,
1589 rsize, &start, &size);
1590 if (found)
1591 rsize = start - rstart;
1592
1593 return (rsize);
1594}
1595
4e21fd06 1596static range_seg_t *
ca577779
PD
1597metaslab_block_find(zfs_btree_t *t, range_tree_t *rt, uint64_t start,
1598 uint64_t size, zfs_btree_index_t *where)
93cf2076 1599{
ca577779
PD
1600 range_seg_t *rs;
1601 range_seg_max_t rsearch;
93cf2076 1602
ca577779
PD
1603 rs_set_start(&rsearch, rt, start);
1604 rs_set_end(&rsearch, rt, start + size);
93cf2076 1605
ca577779 1606 rs = zfs_btree_find(t, &rsearch, where);
4e21fd06 1607 if (rs == NULL) {
ca577779 1608 rs = zfs_btree_next(t, where, where);
93cf2076 1609 }
93cf2076 1610
4e21fd06
DB
1611 return (rs);
1612}
93cf2076 1613
93cf2076 1614/*
ca577779
PD
1615 * This is a helper function that can be used by the allocator to find a
1616 * suitable block to allocate. This will search the specified B-tree looking
1617 * for a block that matches the specified criteria.
93cf2076
GW
1618 */
1619static uint64_t
ca577779 1620metaslab_block_picker(range_tree_t *rt, uint64_t *cursor, uint64_t size,
d3230d76 1621 uint64_t max_search)
93cf2076 1622{
ca577779
PD
1623 if (*cursor == 0)
1624 *cursor = rt->rt_start;
1625 zfs_btree_t *bt = &rt->rt_root;
1626 zfs_btree_index_t where;
1627 range_seg_t *rs = metaslab_block_find(bt, rt, *cursor, size, &where);
d3230d76 1628 uint64_t first_found;
ca577779 1629 int count_searched = 0;
93cf2076 1630
d3230d76 1631 if (rs != NULL)
ca577779 1632 first_found = rs_get_start(rs, rt);
93cf2076 1633
ca577779
PD
1634 while (rs != NULL && (rs_get_start(rs, rt) - first_found <=
1635 max_search || count_searched < metaslab_min_search_count)) {
1636 uint64_t offset = rs_get_start(rs, rt);
1637 if (offset + size <= rs_get_end(rs, rt)) {
93cf2076
GW
1638 *cursor = offset + size;
1639 return (offset);
1640 }
ca577779
PD
1641 rs = zfs_btree_next(bt, &where, &where);
1642 count_searched++;
93cf2076
GW
1643 }
1644
93cf2076 1645 *cursor = 0;
d3230d76 1646 return (-1ULL);
9babb374 1647}
22c81dd8 1648
95f71c01
EN
1649static uint64_t metaslab_df_alloc(metaslab_t *msp, uint64_t size);
1650static uint64_t metaslab_cf_alloc(metaslab_t *msp, uint64_t size);
1651static uint64_t metaslab_ndf_alloc(metaslab_t *msp, uint64_t size);
1652metaslab_ops_t *metaslab_allocator(spa_t *spa);
1653
1654static metaslab_ops_t metaslab_allocators[] = {
1655 { "dynamic", metaslab_df_alloc },
1656 { "cursor", metaslab_cf_alloc },
1657 { "new-dynamic", metaslab_ndf_alloc },
1658};
1659
1660static int
1661spa_find_allocator_byname(const char *val)
1662{
1663 int a = ARRAY_SIZE(metaslab_allocators) - 1;
1664 if (strcmp("new-dynamic", val) == 0)
1665 return (-1); /* remove when ndf is working */
1666 for (; a >= 0; a--) {
1667 if (strcmp(val, metaslab_allocators[a].msop_name) == 0)
1668 return (a);
1669 }
1670 return (-1);
1671}
1672
1673void
1674spa_set_allocator(spa_t *spa, const char *allocator)
1675{
1676 int a = spa_find_allocator_byname(allocator);
1677 if (a < 0) a = 0;
1678 spa->spa_active_allocator = a;
1679 zfs_dbgmsg("spa allocator: %s\n", metaslab_allocators[a].msop_name);
1680}
1681
1682int
1683spa_get_allocator(spa_t *spa)
1684{
1685 return (spa->spa_active_allocator);
1686}
1687
1688#if defined(_KERNEL)
1689int
1690param_set_active_allocator_common(const char *val)
1691{
1692 char *p;
1693
1694 if (val == NULL)
1695 return (SET_ERROR(EINVAL));
1696
1697 if ((p = strchr(val, '\n')) != NULL)
1698 *p = '\0';
1699
1700 int a = spa_find_allocator_byname(val);
1701 if (a < 0)
1702 return (SET_ERROR(EINVAL));
1703
1704 zfs_active_allocator = metaslab_allocators[a].msop_name;
1705 return (0);
1706}
1707#endif
1708
1709metaslab_ops_t *
1710metaslab_allocator(spa_t *spa)
1711{
1712 int allocator = spa_get_allocator(spa);
1713 return (&metaslab_allocators[allocator]);
1714}
1715
428870ff
BB
1716/*
1717 * ==========================================================================
d3230d76
MA
1718 * Dynamic Fit (df) block allocator
1719 *
1720 * Search for a free chunk of at least this size, starting from the last
1721 * offset (for this alignment of block) looking for up to
1722 * metaslab_df_max_search bytes (16MB). If a large enough free chunk is not
1723 * found within 16MB, then return a free chunk of exactly the requested size (or
1724 * larger).
1725 *
1726 * If it seems like searching from the last offset will be unproductive, skip
1727 * that and just return a free chunk of exactly the requested size (or larger).
1728 * This is based on metaslab_df_alloc_threshold and metaslab_df_free_pct. This
1729 * mechanism is probably not very useful and may be removed in the future.
1730 *
1731 * The behavior when not searching can be changed to return the largest free
1732 * chunk, instead of a free chunk of exactly the requested size, by setting
1733 * metaslab_df_use_largest_segment.
428870ff
BB
1734 * ==========================================================================
1735 */
9babb374 1736static uint64_t
93cf2076 1737metaslab_df_alloc(metaslab_t *msp, uint64_t size)
9babb374 1738{
93cf2076
GW
1739 /*
1740 * Find the largest power of 2 block size that evenly divides the
1741 * requested size. This is used to try to allocate blocks with similar
1742 * alignment from the same area of the metaslab (i.e. same cursor
1743 * bucket) but it does not guarantee that other allocations sizes
1744 * may exist in the same region.
1745 */
9babb374 1746 uint64_t align = size & -size;
9bd274dd 1747 uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
d2734cce 1748 range_tree_t *rt = msp->ms_allocatable;
fdc2d303 1749 uint_t free_pct = range_tree_space(rt) * 100 / msp->ms_size;
d3230d76 1750 uint64_t offset;
9babb374 1751
93cf2076 1752 ASSERT(MUTEX_HELD(&msp->ms_lock));
9babb374 1753
9babb374 1754 /*
d3230d76
MA
1755 * If we're running low on space, find a segment based on size,
1756 * rather than iterating based on offset.
9babb374 1757 */
c81f1790 1758 if (metaslab_largest_allocatable(msp) < metaslab_df_alloc_threshold ||
9babb374 1759 free_pct < metaslab_df_free_pct) {
d3230d76
MA
1760 offset = -1;
1761 } else {
ca577779 1762 offset = metaslab_block_picker(rt,
d3230d76 1763 cursor, size, metaslab_df_max_search);
9babb374
BB
1764 }
1765
d3230d76
MA
1766 if (offset == -1) {
1767 range_seg_t *rs;
ca577779
PD
1768 if (zfs_btree_numnodes(&msp->ms_allocatable_by_size) == 0)
1769 metaslab_size_tree_full_load(msp->ms_allocatable);
b2255edc 1770
d3230d76
MA
1771 if (metaslab_df_use_largest_segment) {
1772 /* use largest free segment */
ca577779 1773 rs = zfs_btree_last(&msp->ms_allocatable_by_size, NULL);
d3230d76 1774 } else {
ca577779 1775 zfs_btree_index_t where;
d3230d76
MA
1776 /* use segment of this size, or next largest */
1777 rs = metaslab_block_find(&msp->ms_allocatable_by_size,
ca577779 1778 rt, msp->ms_start, size, &where);
d3230d76 1779 }
ca577779
PD
1780 if (rs != NULL && rs_get_start(rs, rt) + size <= rs_get_end(rs,
1781 rt)) {
1782 offset = rs_get_start(rs, rt);
d3230d76
MA
1783 *cursor = offset + size;
1784 }
1785 }
1786
1787 return (offset);
9babb374
BB
1788}
1789
428870ff
BB
1790/*
1791 * ==========================================================================
93cf2076
GW
1792 * Cursor fit block allocator -
1793 * Select the largest region in the metaslab, set the cursor to the beginning
1794 * of the range and the cursor_end to the end of the range. As allocations
1795 * are made advance the cursor. Continue allocating from the cursor until
1796 * the range is exhausted and then find a new range.
428870ff
BB
1797 * ==========================================================================
1798 */
1799static uint64_t
93cf2076 1800metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
428870ff 1801{
d2734cce 1802 range_tree_t *rt = msp->ms_allocatable;
ca577779 1803 zfs_btree_t *t = &msp->ms_allocatable_by_size;
93cf2076
GW
1804 uint64_t *cursor = &msp->ms_lbas[0];
1805 uint64_t *cursor_end = &msp->ms_lbas[1];
428870ff
BB
1806 uint64_t offset = 0;
1807
93cf2076 1808 ASSERT(MUTEX_HELD(&msp->ms_lock));
428870ff 1809
93cf2076 1810 ASSERT3U(*cursor_end, >=, *cursor);
428870ff 1811
93cf2076
GW
1812 if ((*cursor + size) > *cursor_end) {
1813 range_seg_t *rs;
428870ff 1814
ca577779
PD
1815 if (zfs_btree_numnodes(t) == 0)
1816 metaslab_size_tree_full_load(msp->ms_allocatable);
1817 rs = zfs_btree_last(t, NULL);
1818 if (rs == NULL || (rs_get_end(rs, rt) - rs_get_start(rs, rt)) <
1819 size)
93cf2076 1820 return (-1ULL);
428870ff 1821
ca577779
PD
1822 *cursor = rs_get_start(rs, rt);
1823 *cursor_end = rs_get_end(rs, rt);
428870ff 1824 }
93cf2076
GW
1825
1826 offset = *cursor;
1827 *cursor += size;
1828
428870ff
BB
1829 return (offset);
1830}
1831
93cf2076
GW
1832/*
1833 * ==========================================================================
1834 * New dynamic fit allocator -
1835 * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1836 * contiguous blocks. If no region is found then just use the largest segment
1837 * that remains.
1838 * ==========================================================================
1839 */
1840
1841/*
1842 * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1843 * to request from the allocator.
1844 */
428870ff
BB
1845uint64_t metaslab_ndf_clump_shift = 4;
1846
1847static uint64_t
93cf2076 1848metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
428870ff 1849{
ca577779
PD
1850 zfs_btree_t *t = &msp->ms_allocatable->rt_root;
1851 range_tree_t *rt = msp->ms_allocatable;
1852 zfs_btree_index_t where;
1853 range_seg_t *rs;
1854 range_seg_max_t rsearch;
9bd274dd 1855 uint64_t hbit = highbit64(size);
93cf2076 1856 uint64_t *cursor = &msp->ms_lbas[hbit - 1];
c81f1790 1857 uint64_t max_size = metaslab_largest_allocatable(msp);
428870ff 1858
93cf2076 1859 ASSERT(MUTEX_HELD(&msp->ms_lock));
428870ff
BB
1860
1861 if (max_size < size)
1862 return (-1ULL);
1863
ca577779
PD
1864 rs_set_start(&rsearch, rt, *cursor);
1865 rs_set_end(&rsearch, rt, *cursor + size);
428870ff 1866
ca577779
PD
1867 rs = zfs_btree_find(t, &rsearch, &where);
1868 if (rs == NULL || (rs_get_end(rs, rt) - rs_get_start(rs, rt)) < size) {
d2734cce 1869 t = &msp->ms_allocatable_by_size;
428870ff 1870
ca577779
PD
1871 rs_set_start(&rsearch, rt, 0);
1872 rs_set_end(&rsearch, rt, MIN(max_size, 1ULL << (hbit +
1873 metaslab_ndf_clump_shift)));
1874
1875 rs = zfs_btree_find(t, &rsearch, &where);
93cf2076 1876 if (rs == NULL)
ca577779 1877 rs = zfs_btree_next(t, &where, &where);
93cf2076 1878 ASSERT(rs != NULL);
428870ff
BB
1879 }
1880
ca577779
PD
1881 if ((rs_get_end(rs, rt) - rs_get_start(rs, rt)) >= size) {
1882 *cursor = rs_get_start(rs, rt) + size;
1883 return (rs_get_start(rs, rt));
428870ff
BB
1884 }
1885 return (-1ULL);
1886}
1887
34dc7c2f
BB
1888/*
1889 * ==========================================================================
1890 * Metaslabs
1891 * ==========================================================================
1892 */
93cf2076 1893
93e28d66
SD
1894/*
1895 * Wait for any in-progress metaslab loads to complete.
1896 */
65c7cc49 1897static void
93e28d66
SD
1898metaslab_load_wait(metaslab_t *msp)
1899{
1900 ASSERT(MUTEX_HELD(&msp->ms_lock));
1901
1902 while (msp->ms_loading) {
1903 ASSERT(!msp->ms_loaded);
1904 cv_wait(&msp->ms_load_cv, &msp->ms_lock);
1905 }
1906}
1907
1908/*
1909 * Wait for any in-progress flushing to complete.
1910 */
65c7cc49 1911static void
93e28d66
SD
1912metaslab_flush_wait(metaslab_t *msp)
1913{
1914 ASSERT(MUTEX_HELD(&msp->ms_lock));
1915
1916 while (msp->ms_flushing)
1917 cv_wait(&msp->ms_flush_cv, &msp->ms_lock);
1918}
1919
f09fda50
PD
1920static unsigned int
1921metaslab_idx_func(multilist_t *ml, void *arg)
1922{
1923 metaslab_t *msp = arg;
5b7053a9
AM
1924
1925 /*
1926 * ms_id values are allocated sequentially, so full 64bit
1927 * division would be a waste of time, so limit it to 32 bits.
1928 */
1929 return ((unsigned int)msp->ms_id % multilist_get_num_sublists(ml));
f09fda50
PD
1930}
1931
93e28d66
SD
1932uint64_t
1933metaslab_allocated_space(metaslab_t *msp)
1934{
1935 return (msp->ms_allocated_space);
1936}
1937
1938/*
1939 * Verify that the space accounting on disk matches the in-core range_trees.
1940 */
1941static void
1942metaslab_verify_space(metaslab_t *msp, uint64_t txg)
1943{
1944 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1945 uint64_t allocating = 0;
1946 uint64_t sm_free_space, msp_free_space;
1947
1948 ASSERT(MUTEX_HELD(&msp->ms_lock));
1949 ASSERT(!msp->ms_condensing);
1950
1951 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
1952 return;
1953
1954 /*
1955 * We can only verify the metaslab space when we're called
1956 * from syncing context with a loaded metaslab that has an
1957 * allocated space map. Calling this in non-syncing context
1958 * does not provide a consistent view of the metaslab since
1959 * we're performing allocations in the future.
1960 */
1961 if (txg != spa_syncing_txg(spa) || msp->ms_sm == NULL ||
1962 !msp->ms_loaded)
1963 return;
1964
1965 /*
1966 * Even though the smp_alloc field can get negative,
1967 * when it comes to a metaslab's space map, that should
1968 * never be the case.
1969 */
1970 ASSERT3S(space_map_allocated(msp->ms_sm), >=, 0);
1971
1972 ASSERT3U(space_map_allocated(msp->ms_sm), >=,
1973 range_tree_space(msp->ms_unflushed_frees));
1974
1975 ASSERT3U(metaslab_allocated_space(msp), ==,
1976 space_map_allocated(msp->ms_sm) +
1977 range_tree_space(msp->ms_unflushed_allocs) -
1978 range_tree_space(msp->ms_unflushed_frees));
1979
1980 sm_free_space = msp->ms_size - metaslab_allocated_space(msp);
1981
1982 /*
1983 * Account for future allocations since we would have
1984 * already deducted that space from the ms_allocatable.
1985 */
1986 for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
1987 allocating +=
1988 range_tree_space(msp->ms_allocating[(txg + t) & TXG_MASK]);
1989 }
f09fda50
PD
1990 ASSERT3U(allocating + msp->ms_allocated_this_txg, ==,
1991 msp->ms_allocating_total);
93e28d66
SD
1992
1993 ASSERT3U(msp->ms_deferspace, ==,
1994 range_tree_space(msp->ms_defer[0]) +
1995 range_tree_space(msp->ms_defer[1]));
1996
1997 msp_free_space = range_tree_space(msp->ms_allocatable) + allocating +
1998 msp->ms_deferspace + range_tree_space(msp->ms_freed);
1999
2000 VERIFY3U(sm_free_space, ==, msp_free_space);
2001}
2002
928e8ad4
SD
2003static void
2004metaslab_aux_histograms_clear(metaslab_t *msp)
2005{
2006 /*
2007 * Auxiliary histograms are only cleared when resetting them,
2008 * which can only happen while the metaslab is loaded.
2009 */
2010 ASSERT(msp->ms_loaded);
2011
861166b0 2012 memset(msp->ms_synchist, 0, sizeof (msp->ms_synchist));
928e8ad4 2013 for (int t = 0; t < TXG_DEFER_SIZE; t++)
861166b0 2014 memset(msp->ms_deferhist[t], 0, sizeof (msp->ms_deferhist[t]));
928e8ad4
SD
2015}
2016
2017static void
2018metaslab_aux_histogram_add(uint64_t *histogram, uint64_t shift,
2019 range_tree_t *rt)
2020{
2021 /*
2022 * This is modeled after space_map_histogram_add(), so refer to that
2023 * function for implementation details. We want this to work like
2024 * the space map histogram, and not the range tree histogram, as we
2025 * are essentially constructing a delta that will be later subtracted
2026 * from the space map histogram.
2027 */
2028 int idx = 0;
2029 for (int i = shift; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
2030 ASSERT3U(i, >=, idx + shift);
2031 histogram[idx] += rt->rt_histogram[i] << (i - idx - shift);
2032
2033 if (idx < SPACE_MAP_HISTOGRAM_SIZE - 1) {
2034 ASSERT3U(idx + shift, ==, i);
2035 idx++;
2036 ASSERT3U(idx, <, SPACE_MAP_HISTOGRAM_SIZE);
2037 }
2038 }
2039}
2040
2041/*
2042 * Called at every sync pass that the metaslab gets synced.
2043 *
2044 * The reason is that we want our auxiliary histograms to be updated
2045 * wherever the metaslab's space map histogram is updated. This way
2046 * we stay consistent on which parts of the metaslab space map's
2047 * histogram are currently not available for allocations (e.g because
2048 * they are in the defer, freed, and freeing trees).
2049 */
2050static void
2051metaslab_aux_histograms_update(metaslab_t *msp)
2052{
2053 space_map_t *sm = msp->ms_sm;
2054 ASSERT(sm != NULL);
2055
2056 /*
2057 * This is similar to the metaslab's space map histogram updates
2058 * that take place in metaslab_sync(). The only difference is that
2059 * we only care about segments that haven't made it into the
2060 * ms_allocatable tree yet.
2061 */
2062 if (msp->ms_loaded) {
2063 metaslab_aux_histograms_clear(msp);
2064
2065 metaslab_aux_histogram_add(msp->ms_synchist,
2066 sm->sm_shift, msp->ms_freed);
2067
2068 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2069 metaslab_aux_histogram_add(msp->ms_deferhist[t],
2070 sm->sm_shift, msp->ms_defer[t]);
2071 }
2072 }
2073
2074 metaslab_aux_histogram_add(msp->ms_synchist,
2075 sm->sm_shift, msp->ms_freeing);
2076}
2077
2078/*
2079 * Called every time we are done syncing (writing to) the metaslab,
2080 * i.e. at the end of each sync pass.
2081 * [see the comment in metaslab_impl.h for ms_synchist, ms_deferhist]
2082 */
2083static void
2084metaslab_aux_histograms_update_done(metaslab_t *msp, boolean_t defer_allowed)
2085{
2086 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2087 space_map_t *sm = msp->ms_sm;
2088
2089 if (sm == NULL) {
2090 /*
2091 * We came here from metaslab_init() when creating/opening a
2092 * pool, looking at a metaslab that hasn't had any allocations
2093 * yet.
2094 */
2095 return;
2096 }
2097
2098 /*
2099 * This is similar to the actions that we take for the ms_freed
2100 * and ms_defer trees in metaslab_sync_done().
2101 */
2102 uint64_t hist_index = spa_syncing_txg(spa) % TXG_DEFER_SIZE;
2103 if (defer_allowed) {
861166b0 2104 memcpy(msp->ms_deferhist[hist_index], msp->ms_synchist,
928e8ad4
SD
2105 sizeof (msp->ms_synchist));
2106 } else {
861166b0 2107 memset(msp->ms_deferhist[hist_index], 0,
928e8ad4
SD
2108 sizeof (msp->ms_deferhist[hist_index]));
2109 }
861166b0 2110 memset(msp->ms_synchist, 0, sizeof (msp->ms_synchist));
928e8ad4
SD
2111}
2112
2113/*
2114 * Ensure that the metaslab's weight and fragmentation are consistent
2115 * with the contents of the histogram (either the range tree's histogram
2116 * or the space map's depending whether the metaslab is loaded).
2117 */
2118static void
2119metaslab_verify_weight_and_frag(metaslab_t *msp)
2120{
2121 ASSERT(MUTEX_HELD(&msp->ms_lock));
2122
2123 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
2124 return;
2125
2fcf4481
SD
2126 /*
2127 * We can end up here from vdev_remove_complete(), in which case we
2128 * cannot do these assertions because we hold spa config locks and
2129 * thus we are not allowed to read from the DMU.
2130 *
2131 * We check if the metaslab group has been removed and if that's
2132 * the case we return immediately as that would mean that we are
2133 * here from the aforementioned code path.
2134 */
928e8ad4
SD
2135 if (msp->ms_group == NULL)
2136 return;
2137
2138 /*
2139 * Devices being removed always return a weight of 0 and leave
2140 * fragmentation and ms_max_size as is - there is nothing for
2141 * us to verify here.
2142 */
2143 vdev_t *vd = msp->ms_group->mg_vd;
2144 if (vd->vdev_removing)
2145 return;
2146
2147 /*
2148 * If the metaslab is dirty it probably means that we've done
2149 * some allocations or frees that have changed our histograms
2150 * and thus the weight.
2151 */
2152 for (int t = 0; t < TXG_SIZE; t++) {
2153 if (txg_list_member(&vd->vdev_ms_list, msp, t))
2154 return;
2155 }
2156
2157 /*
2158 * This verification checks that our in-memory state is consistent
2159 * with what's on disk. If the pool is read-only then there aren't
2160 * any changes and we just have the initially-loaded state.
2161 */
2162 if (!spa_writeable(msp->ms_group->mg_vd->vdev_spa))
2163 return;
2164
2165 /* some extra verification for in-core tree if you can */
2166 if (msp->ms_loaded) {
2167 range_tree_stat_verify(msp->ms_allocatable);
2168 VERIFY(space_map_histogram_verify(msp->ms_sm,
2169 msp->ms_allocatable));
2170 }
2171
2172 uint64_t weight = msp->ms_weight;
2173 uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
2174 boolean_t space_based = WEIGHT_IS_SPACEBASED(msp->ms_weight);
2175 uint64_t frag = msp->ms_fragmentation;
2176 uint64_t max_segsize = msp->ms_max_size;
2177
2178 msp->ms_weight = 0;
2179 msp->ms_fragmentation = 0;
928e8ad4
SD
2180
2181 /*
65a91b16
SD
2182 * This function is used for verification purposes and thus should
2183 * not introduce any side-effects/mutations on the system's state.
2184 *
2185 * Regardless of whether metaslab_weight() thinks this metaslab
2186 * should be active or not, we want to ensure that the actual weight
2187 * (and therefore the value of ms_weight) would be the same if it
2188 * was to be recalculated at this point.
2189 *
2190 * In addition we set the nodirty flag so metaslab_weight() does
2191 * not dirty the metaslab for future TXGs (e.g. when trying to
2192 * force condensing to upgrade the metaslab spacemaps).
928e8ad4 2193 */
65a91b16 2194 msp->ms_weight = metaslab_weight(msp, B_TRUE) | was_active;
928e8ad4
SD
2195
2196 VERIFY3U(max_segsize, ==, msp->ms_max_size);
2197
2198 /*
2199 * If the weight type changed then there is no point in doing
2200 * verification. Revert fields to their original values.
2201 */
2202 if ((space_based && !WEIGHT_IS_SPACEBASED(msp->ms_weight)) ||
2203 (!space_based && WEIGHT_IS_SPACEBASED(msp->ms_weight))) {
2204 msp->ms_fragmentation = frag;
2205 msp->ms_weight = weight;
2206 return;
2207 }
2208
2209 VERIFY3U(msp->ms_fragmentation, ==, frag);
2210 VERIFY3U(msp->ms_weight, ==, weight);
2211}
2212
f09fda50
PD
2213/*
2214 * If we're over the zfs_metaslab_mem_limit, select the loaded metaslab from
2215 * this class that was used longest ago, and attempt to unload it. We don't
2216 * want to spend too much time in this loop to prevent performance
e1cfd73f 2217 * degradation, and we expect that most of the time this operation will
f09fda50
PD
2218 * succeed. Between that and the normal unloading processing during txg sync,
2219 * we expect this to keep the metaslab memory usage under control.
2220 */
2221static void
2222metaslab_potentially_evict(metaslab_class_t *mc)
2223{
2224#ifdef _KERNEL
2225 uint64_t allmem = arc_all_memory();
65019062
MM
2226 uint64_t inuse = spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2227 uint64_t size = spl_kmem_cache_entry_size(zfs_btree_leaf_cache);
fdc2d303 2228 uint_t tries = 0;
f09fda50 2229 for (; allmem * zfs_metaslab_mem_limit / 100 < inuse * size &&
ffdf019c 2230 tries < multilist_get_num_sublists(&mc->mc_metaslab_txg_list) * 2;
f09fda50
PD
2231 tries++) {
2232 unsigned int idx = multilist_get_random_index(
ffdf019c 2233 &mc->mc_metaslab_txg_list);
f09fda50 2234 multilist_sublist_t *mls =
ffdf019c 2235 multilist_sublist_lock(&mc->mc_metaslab_txg_list, idx);
f09fda50
PD
2236 metaslab_t *msp = multilist_sublist_head(mls);
2237 multilist_sublist_unlock(mls);
2238 while (msp != NULL && allmem * zfs_metaslab_mem_limit / 100 <
2239 inuse * size) {
2240 VERIFY3P(mls, ==, multilist_sublist_lock(
ffdf019c 2241 &mc->mc_metaslab_txg_list, idx));
f09fda50 2242 ASSERT3U(idx, ==,
ffdf019c 2243 metaslab_idx_func(&mc->mc_metaslab_txg_list, msp));
f09fda50
PD
2244
2245 if (!multilist_link_active(&msp->ms_class_txg_node)) {
2246 multilist_sublist_unlock(mls);
2247 break;
2248 }
2249 metaslab_t *next_msp = multilist_sublist_next(mls, msp);
2250 multilist_sublist_unlock(mls);
2251 /*
2252 * If the metaslab is currently loading there are two
2253 * cases. If it's the metaslab we're evicting, we
2254 * can't continue on or we'll panic when we attempt to
2255 * recursively lock the mutex. If it's another
2256 * metaslab that's loading, it can be safely skipped,
2257 * since we know it's very new and therefore not a
2258 * good eviction candidate. We check later once the
2259 * lock is held that the metaslab is fully loaded
2260 * before actually unloading it.
2261 */
2262 if (msp->ms_loading) {
2263 msp = next_msp;
65019062
MM
2264 inuse =
2265 spl_kmem_cache_inuse(zfs_btree_leaf_cache);
f09fda50
PD
2266 continue;
2267 }
2268 /*
2269 * We can't unload metaslabs with no spacemap because
2270 * they're not ready to be unloaded yet. We can't
2271 * unload metaslabs with outstanding allocations
2272 * because doing so could cause the metaslab's weight
2273 * to decrease while it's unloaded, which violates an
2274 * invariant that we use to prevent unnecessary
2275 * loading. We also don't unload metaslabs that are
2276 * currently active because they are high-weight
2277 * metaslabs that are likely to be used in the near
2278 * future.
2279 */
2280 mutex_enter(&msp->ms_lock);
2281 if (msp->ms_allocator == -1 && msp->ms_sm != NULL &&
2282 msp->ms_allocating_total == 0) {
2283 metaslab_unload(msp);
2284 }
2285 mutex_exit(&msp->ms_lock);
2286 msp = next_msp;
65019062 2287 inuse = spl_kmem_cache_inuse(zfs_btree_leaf_cache);
f09fda50
PD
2288 }
2289 }
14e4e3cb 2290#else
18168da7 2291 (void) mc, (void) zfs_metaslab_mem_limit;
f09fda50
PD
2292#endif
2293}
2294
b194fab0
SD
2295static int
2296metaslab_load_impl(metaslab_t *msp)
93cf2076
GW
2297{
2298 int error = 0;
93cf2076
GW
2299
2300 ASSERT(MUTEX_HELD(&msp->ms_lock));
b194fab0 2301 ASSERT(msp->ms_loading);
425d3237 2302 ASSERT(!msp->ms_condensing);
93cf2076 2303
a1d477c2 2304 /*
425d3237
SD
2305 * We temporarily drop the lock to unblock other operations while we
2306 * are reading the space map. Therefore, metaslab_sync() and
2307 * metaslab_sync_done() can run at the same time as we do.
2308 *
93e28d66
SD
2309 * If we are using the log space maps, metaslab_sync() can't write to
2310 * the metaslab's space map while we are loading as we only write to
2311 * it when we are flushing the metaslab, and that can't happen while
2312 * we are loading it.
2313 *
2314 * If we are not using log space maps though, metaslab_sync() can
2315 * append to the space map while we are loading. Therefore we load
2316 * only entries that existed when we started the load. Additionally,
2317 * metaslab_sync_done() has to wait for the load to complete because
2318 * there are potential races like metaslab_load() loading parts of the
2319 * space map that are currently being appended by metaslab_sync(). If
2320 * we didn't, the ms_allocatable would have entries that
2321 * metaslab_sync_done() would try to re-add later.
425d3237
SD
2322 *
2323 * That's why before dropping the lock we remember the synced length
2324 * of the metaslab and read up to that point of the space map,
2325 * ignoring entries appended by metaslab_sync() that happen after we
2326 * drop the lock.
a1d477c2 2327 */
425d3237 2328 uint64_t length = msp->ms_synced_length;
a1d477c2 2329 mutex_exit(&msp->ms_lock);
93cf2076 2330
93e28d66 2331 hrtime_t load_start = gethrtime();
ca577779
PD
2332 metaslab_rt_arg_t *mrap;
2333 if (msp->ms_allocatable->rt_arg == NULL) {
2334 mrap = kmem_zalloc(sizeof (*mrap), KM_SLEEP);
2335 } else {
2336 mrap = msp->ms_allocatable->rt_arg;
2337 msp->ms_allocatable->rt_ops = NULL;
2338 msp->ms_allocatable->rt_arg = NULL;
2339 }
2340 mrap->mra_bt = &msp->ms_allocatable_by_size;
2341 mrap->mra_floor_shift = metaslab_by_size_min_shift;
2342
d2734cce 2343 if (msp->ms_sm != NULL) {
425d3237
SD
2344 error = space_map_load_length(msp->ms_sm, msp->ms_allocatable,
2345 SM_FREE, length);
ca577779
PD
2346
2347 /* Now, populate the size-sorted tree. */
2348 metaslab_rt_create(msp->ms_allocatable, mrap);
2349 msp->ms_allocatable->rt_ops = &metaslab_rt_ops;
2350 msp->ms_allocatable->rt_arg = mrap;
2351
2352 struct mssa_arg arg = {0};
2353 arg.rt = msp->ms_allocatable;
2354 arg.mra = mrap;
2355 range_tree_walk(msp->ms_allocatable, metaslab_size_sorted_add,
2356 &arg);
d2734cce 2357 } else {
ca577779
PD
2358 /*
2359 * Add the size-sorted tree first, since we don't need to load
2360 * the metaslab from the spacemap.
2361 */
2362 metaslab_rt_create(msp->ms_allocatable, mrap);
2363 msp->ms_allocatable->rt_ops = &metaslab_rt_ops;
2364 msp->ms_allocatable->rt_arg = mrap;
425d3237
SD
2365 /*
2366 * The space map has not been allocated yet, so treat
2367 * all the space in the metaslab as free and add it to the
2368 * ms_allocatable tree.
2369 */
d2734cce
SD
2370 range_tree_add(msp->ms_allocatable,
2371 msp->ms_start, msp->ms_size);
93e28d66 2372
793c958f 2373 if (msp->ms_new) {
93e28d66
SD
2374 /*
2375 * If the ms_sm doesn't exist, this means that this
2376 * metaslab hasn't gone through metaslab_sync() and
2377 * thus has never been dirtied. So we shouldn't
2378 * expect any unflushed allocs or frees from previous
2379 * TXGs.
93e28d66
SD
2380 */
2381 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
2382 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
2383 }
d2734cce 2384 }
93cf2076 2385
425d3237
SD
2386 /*
2387 * We need to grab the ms_sync_lock to prevent metaslab_sync() from
93e28d66
SD
2388 * changing the ms_sm (or log_sm) and the metaslab's range trees
2389 * while we are about to use them and populate the ms_allocatable.
2390 * The ms_lock is insufficient for this because metaslab_sync() doesn't
2391 * hold the ms_lock while writing the ms_checkpointing tree to disk.
425d3237
SD
2392 */
2393 mutex_enter(&msp->ms_sync_lock);
a1d477c2 2394 mutex_enter(&msp->ms_lock);
93e28d66 2395
425d3237 2396 ASSERT(!msp->ms_condensing);
93e28d66 2397 ASSERT(!msp->ms_flushing);
93cf2076 2398
8eef9976
SD
2399 if (error != 0) {
2400 mutex_exit(&msp->ms_sync_lock);
b194fab0 2401 return (error);
8eef9976 2402 }
4e21fd06 2403
b194fab0
SD
2404 ASSERT3P(msp->ms_group, !=, NULL);
2405 msp->ms_loaded = B_TRUE;
2406
2407 /*
93e28d66
SD
2408 * Apply all the unflushed changes to ms_allocatable right
2409 * away so any manipulations we do below have a clear view
2410 * of what is allocated and what is free.
2411 */
2412 range_tree_walk(msp->ms_unflushed_allocs,
2413 range_tree_remove, msp->ms_allocatable);
2414 range_tree_walk(msp->ms_unflushed_frees,
2415 range_tree_add, msp->ms_allocatable);
2416
93e28d66
SD
2417 ASSERT3P(msp->ms_group, !=, NULL);
2418 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2419 if (spa_syncing_log_sm(spa) != NULL) {
2420 ASSERT(spa_feature_is_enabled(spa,
2421 SPA_FEATURE_LOG_SPACEMAP));
2422
2423 /*
2424 * If we use a log space map we add all the segments
2425 * that are in ms_unflushed_frees so they are available
2426 * for allocation.
2427 *
2428 * ms_allocatable needs to contain all free segments
2429 * that are ready for allocations (thus not segments
2430 * from ms_freeing, ms_freed, and the ms_defer trees).
2431 * But if we grab the lock in this code path at a sync
2432 * pass later that 1, then it also contains the
2433 * segments of ms_freed (they were added to it earlier
2434 * in this path through ms_unflushed_frees). So we
2435 * need to remove all the segments that exist in
2436 * ms_freed from ms_allocatable as they will be added
2437 * later in metaslab_sync_done().
2438 *
2439 * When there's no log space map, the ms_allocatable
2440 * correctly doesn't contain any segments that exist
2441 * in ms_freed [see ms_synced_length].
2442 */
2443 range_tree_walk(msp->ms_freed,
2444 range_tree_remove, msp->ms_allocatable);
2445 }
2446
2447 /*
2448 * If we are not using the log space map, ms_allocatable
2449 * contains the segments that exist in the ms_defer trees
2450 * [see ms_synced_length]. Thus we need to remove them
2451 * from ms_allocatable as they will be added again in
425d3237 2452 * metaslab_sync_done().
93e28d66
SD
2453 *
2454 * If we are using the log space map, ms_allocatable still
2455 * contains the segments that exist in the ms_defer trees.
2456 * Not because it read them through the ms_sm though. But
2457 * because these segments are part of ms_unflushed_frees
2458 * whose segments we add to ms_allocatable earlier in this
2459 * code path.
b194fab0 2460 */
425d3237
SD
2461 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2462 range_tree_walk(msp->ms_defer[t],
2463 range_tree_remove, msp->ms_allocatable);
93cf2076 2464 }
425d3237 2465
928e8ad4
SD
2466 /*
2467 * Call metaslab_recalculate_weight_and_sort() now that the
2468 * metaslab is loaded so we get the metaslab's real weight.
2469 *
2470 * Unless this metaslab was created with older software and
2471 * has not yet been converted to use segment-based weight, we
2472 * expect the new weight to be better or equal to the weight
2473 * that the metaslab had while it was not loaded. This is
2474 * because the old weight does not take into account the
2475 * consolidation of adjacent segments between TXGs. [see
2476 * comment for ms_synchist and ms_deferhist[] for more info]
2477 */
2478 uint64_t weight = msp->ms_weight;
c81f1790 2479 uint64_t max_size = msp->ms_max_size;
928e8ad4
SD
2480 metaslab_recalculate_weight_and_sort(msp);
2481 if (!WEIGHT_IS_SPACEBASED(weight))
2482 ASSERT3U(weight, <=, msp->ms_weight);
c81f1790
PD
2483 msp->ms_max_size = metaslab_largest_allocatable(msp);
2484 ASSERT3U(max_size, <=, msp->ms_max_size);
93e28d66 2485 hrtime_t load_end = gethrtime();
d64c6a2e
MA
2486 msp->ms_load_time = load_end;
2487 zfs_dbgmsg("metaslab_load: txg %llu, spa %s, vdev_id %llu, "
2488 "ms_id %llu, smp_length %llu, "
2489 "unflushed_allocs %llu, unflushed_frees %llu, "
2490 "freed %llu, defer %llu + %llu, unloaded time %llu ms, "
2491 "loading_time %lld ms, ms_max_size %llu, "
2492 "max size error %lld, "
2493 "old_weight %llx, new_weight %llx",
8e739b2c
RE
2494 (u_longlong_t)spa_syncing_txg(spa), spa_name(spa),
2495 (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
2496 (u_longlong_t)msp->ms_id,
2497 (u_longlong_t)space_map_length(msp->ms_sm),
2498 (u_longlong_t)range_tree_space(msp->ms_unflushed_allocs),
2499 (u_longlong_t)range_tree_space(msp->ms_unflushed_frees),
2500 (u_longlong_t)range_tree_space(msp->ms_freed),
2501 (u_longlong_t)range_tree_space(msp->ms_defer[0]),
2502 (u_longlong_t)range_tree_space(msp->ms_defer[1]),
d64c6a2e
MA
2503 (longlong_t)((load_start - msp->ms_unload_time) / 1000000),
2504 (longlong_t)((load_end - load_start) / 1000000),
8e739b2c
RE
2505 (u_longlong_t)msp->ms_max_size,
2506 (u_longlong_t)msp->ms_max_size - max_size,
2507 (u_longlong_t)weight, (u_longlong_t)msp->ms_weight);
93e28d66 2508
425d3237
SD
2509 metaslab_verify_space(msp, spa_syncing_txg(spa));
2510 mutex_exit(&msp->ms_sync_lock);
b194fab0
SD
2511 return (0);
2512}
2513
2514int
2515metaslab_load(metaslab_t *msp)
2516{
2517 ASSERT(MUTEX_HELD(&msp->ms_lock));
2518
2519 /*
2520 * There may be another thread loading the same metaslab, if that's
2521 * the case just wait until the other thread is done and return.
2522 */
2523 metaslab_load_wait(msp);
2524 if (msp->ms_loaded)
2525 return (0);
2526 VERIFY(!msp->ms_loading);
425d3237 2527 ASSERT(!msp->ms_condensing);
b194fab0 2528
93e28d66
SD
2529 /*
2530 * We set the loading flag BEFORE potentially dropping the lock to
2531 * wait for an ongoing flush (see ms_flushing below). This way other
2532 * threads know that there is already a thread that is loading this
2533 * metaslab.
2534 */
b194fab0 2535 msp->ms_loading = B_TRUE;
93e28d66
SD
2536
2537 /*
2538 * Wait for any in-progress flushing to finish as we drop the ms_lock
2539 * both here (during space_map_load()) and in metaslab_flush() (when
2540 * we flush our changes to the ms_sm).
2541 */
2542 if (msp->ms_flushing)
2543 metaslab_flush_wait(msp);
2544
2545 /*
2546 * In the possibility that we were waiting for the metaslab to be
2547 * flushed (where we temporarily dropped the ms_lock), ensure that
2548 * no one else loaded the metaslab somehow.
2549 */
2550 ASSERT(!msp->ms_loaded);
2551
f09fda50
PD
2552 /*
2553 * If we're loading a metaslab in the normal class, consider evicting
2554 * another one to keep our memory usage under the limit defined by the
2555 * zfs_metaslab_mem_limit tunable.
2556 */
2557 if (spa_normal_class(msp->ms_group->mg_class->mc_spa) ==
2558 msp->ms_group->mg_class) {
2559 metaslab_potentially_evict(msp->ms_group->mg_class);
2560 }
2561
b194fab0 2562 int error = metaslab_load_impl(msp);
93e28d66
SD
2563
2564 ASSERT(MUTEX_HELD(&msp->ms_lock));
b194fab0 2565 msp->ms_loading = B_FALSE;
93cf2076 2566 cv_broadcast(&msp->ms_load_cv);
b194fab0 2567
93cf2076
GW
2568 return (error);
2569}
2570
2571void
2572metaslab_unload(metaslab_t *msp)
2573{
2574 ASSERT(MUTEX_HELD(&msp->ms_lock));
928e8ad4 2575
f09fda50
PD
2576 /*
2577 * This can happen if a metaslab is selected for eviction (in
2578 * metaslab_potentially_evict) and then unloaded during spa_sync (via
2579 * metaslab_class_evict_old).
2580 */
2581 if (!msp->ms_loaded)
2582 return;
928e8ad4 2583
d2734cce 2584 range_tree_vacate(msp->ms_allocatable, NULL, NULL);
93cf2076 2585 msp->ms_loaded = B_FALSE;
c81f1790 2586 msp->ms_unload_time = gethrtime();
928e8ad4 2587
679b0f2a 2588 msp->ms_activation_weight = 0;
93cf2076 2589 msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
928e8ad4 2590
f09fda50
PD
2591 if (msp->ms_group != NULL) {
2592 metaslab_class_t *mc = msp->ms_group->mg_class;
2593 multilist_sublist_t *mls =
ffdf019c 2594 multilist_sublist_lock_obj(&mc->mc_metaslab_txg_list, msp);
f09fda50
PD
2595 if (multilist_link_active(&msp->ms_class_txg_node))
2596 multilist_sublist_remove(mls, msp);
2597 multilist_sublist_unlock(mls);
d64c6a2e
MA
2598
2599 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2600 zfs_dbgmsg("metaslab_unload: txg %llu, spa %s, vdev_id %llu, "
2601 "ms_id %llu, weight %llx, "
2602 "selected txg %llu (%llu ms ago), alloc_txg %llu, "
2603 "loaded %llu ms ago, max_size %llu",
8e739b2c
RE
2604 (u_longlong_t)spa_syncing_txg(spa), spa_name(spa),
2605 (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
2606 (u_longlong_t)msp->ms_id,
2607 (u_longlong_t)msp->ms_weight,
2608 (u_longlong_t)msp->ms_selected_txg,
2609 (u_longlong_t)(msp->ms_unload_time -
2610 msp->ms_selected_time) / 1000 / 1000,
2611 (u_longlong_t)msp->ms_alloc_txg,
2612 (u_longlong_t)(msp->ms_unload_time -
2613 msp->ms_load_time) / 1000 / 1000,
2614 (u_longlong_t)msp->ms_max_size);
f09fda50
PD
2615 }
2616
928e8ad4
SD
2617 /*
2618 * We explicitly recalculate the metaslab's weight based on its space
2619 * map (as it is now not loaded). We want unload metaslabs to always
2620 * have their weights calculated from the space map histograms, while
2621 * loaded ones have it calculated from their in-core range tree
2622 * [see metaslab_load()]. This way, the weight reflects the information
93e28d66 2623 * available in-core, whether it is loaded or not.
928e8ad4
SD
2624 *
2625 * If ms_group == NULL means that we came here from metaslab_fini(),
2626 * at which point it doesn't make sense for us to do the recalculation
2627 * and the sorting.
2628 */
2629 if (msp->ms_group != NULL)
2630 metaslab_recalculate_weight_and_sort(msp);
93cf2076
GW
2631}
2632
ca577779
PD
2633/*
2634 * We want to optimize the memory use of the per-metaslab range
2635 * trees. To do this, we store the segments in the range trees in
2636 * units of sectors, zero-indexing from the start of the metaslab. If
2637 * the vdev_ms_shift - the vdev_ashift is less than 32, we can store
2638 * the ranges using two uint32_ts, rather than two uint64_ts.
2639 */
6774931d 2640range_seg_type_t
ca577779
PD
2641metaslab_calculate_range_tree_type(vdev_t *vdev, metaslab_t *msp,
2642 uint64_t *start, uint64_t *shift)
2643{
2644 if (vdev->vdev_ms_shift - vdev->vdev_ashift < 32 &&
2645 !zfs_metaslab_force_large_segs) {
2646 *shift = vdev->vdev_ashift;
2647 *start = msp->ms_start;
2648 return (RANGE_SEG32);
2649 } else {
2650 *shift = 0;
2651 *start = 0;
2652 return (RANGE_SEG64);
2653 }
2654}
2655
f09fda50
PD
2656void
2657metaslab_set_selected_txg(metaslab_t *msp, uint64_t txg)
2658{
2659 ASSERT(MUTEX_HELD(&msp->ms_lock));
2660 metaslab_class_t *mc = msp->ms_group->mg_class;
2661 multilist_sublist_t *mls =
ffdf019c 2662 multilist_sublist_lock_obj(&mc->mc_metaslab_txg_list, msp);
f09fda50
PD
2663 if (multilist_link_active(&msp->ms_class_txg_node))
2664 multilist_sublist_remove(mls, msp);
2665 msp->ms_selected_txg = txg;
eef0f4d8 2666 msp->ms_selected_time = gethrtime();
f09fda50
PD
2667 multilist_sublist_insert_tail(mls, msp);
2668 multilist_sublist_unlock(mls);
2669}
2670
93e28d66 2671void
cc99f275
DB
2672metaslab_space_update(vdev_t *vd, metaslab_class_t *mc, int64_t alloc_delta,
2673 int64_t defer_delta, int64_t space_delta)
2674{
2675 vdev_space_update(vd, alloc_delta, defer_delta, space_delta);
2676
2677 ASSERT3P(vd->vdev_spa->spa_root_vdev, ==, vd->vdev_parent);
2678 ASSERT(vd->vdev_ms_count != 0);
2679
2680 metaslab_class_space_update(mc, alloc_delta, defer_delta, space_delta,
2681 vdev_deflated_space(vd, space_delta));
2682}
2683
fb42a493 2684int
93e28d66
SD
2685metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object,
2686 uint64_t txg, metaslab_t **msp)
34dc7c2f
BB
2687{
2688 vdev_t *vd = mg->mg_vd;
cc99f275
DB
2689 spa_t *spa = vd->vdev_spa;
2690 objset_t *mos = spa->spa_meta_objset;
fb42a493
PS
2691 metaslab_t *ms;
2692 int error;
34dc7c2f 2693
79c76d5b 2694 ms = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
fb42a493 2695 mutex_init(&ms->ms_lock, NULL, MUTEX_DEFAULT, NULL);
a1d477c2 2696 mutex_init(&ms->ms_sync_lock, NULL, MUTEX_DEFAULT, NULL);
fb42a493 2697 cv_init(&ms->ms_load_cv, NULL, CV_DEFAULT, NULL);
93e28d66 2698 cv_init(&ms->ms_flush_cv, NULL, CV_DEFAULT, NULL);
f09fda50 2699 multilist_link_init(&ms->ms_class_txg_node);
619f0976 2700
fb42a493
PS
2701 ms->ms_id = id;
2702 ms->ms_start = id << vd->vdev_ms_shift;
2703 ms->ms_size = 1ULL << vd->vdev_ms_shift;
492f64e9
PD
2704 ms->ms_allocator = -1;
2705 ms->ms_new = B_TRUE;
34dc7c2f 2706
b2255edc
BB
2707 vdev_ops_t *ops = vd->vdev_ops;
2708 if (ops->vdev_op_metaslab_init != NULL)
2709 ops->vdev_op_metaslab_init(vd, &ms->ms_start, &ms->ms_size);
2710
93cf2076
GW
2711 /*
2712 * We only open space map objects that already exist. All others
e39fe05b
FU
2713 * will be opened when we finally allocate an object for it. For
2714 * readonly pools there is no need to open the space map object.
425d3237
SD
2715 *
2716 * Note:
2717 * When called from vdev_expand(), we can't call into the DMU as
2718 * we are holding the spa_config_lock as a writer and we would
2719 * deadlock [see relevant comment in vdev_metaslab_init()]. in
2720 * that case, the object parameter is zero though, so we won't
2721 * call into the DMU.
93cf2076 2722 */
e39fe05b
FU
2723 if (object != 0 && !(spa->spa_mode == SPA_MODE_READ &&
2724 !spa->spa_read_spacemaps)) {
fb42a493 2725 error = space_map_open(&ms->ms_sm, mos, object, ms->ms_start,
a1d477c2 2726 ms->ms_size, vd->vdev_ashift);
fb42a493
PS
2727
2728 if (error != 0) {
2729 kmem_free(ms, sizeof (metaslab_t));
2730 return (error);
2731 }
2732
2733 ASSERT(ms->ms_sm != NULL);
425d3237 2734 ms->ms_allocated_space = space_map_allocated(ms->ms_sm);
93cf2076 2735 }
34dc7c2f 2736
ca577779 2737 uint64_t shift, start;
793c958f
SD
2738 range_seg_type_t type =
2739 metaslab_calculate_range_tree_type(vd, ms, &start, &shift);
ca577779 2740
ca577779 2741 ms->ms_allocatable = range_tree_create(NULL, type, NULL, start, shift);
793c958f
SD
2742 for (int t = 0; t < TXG_SIZE; t++) {
2743 ms->ms_allocating[t] = range_tree_create(NULL, type,
2744 NULL, start, shift);
2745 }
2746 ms->ms_freeing = range_tree_create(NULL, type, NULL, start, shift);
2747 ms->ms_freed = range_tree_create(NULL, type, NULL, start, shift);
2748 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2749 ms->ms_defer[t] = range_tree_create(NULL, type, NULL,
2750 start, shift);
2751 }
2752 ms->ms_checkpointing =
2753 range_tree_create(NULL, type, NULL, start, shift);
2754 ms->ms_unflushed_allocs =
2755 range_tree_create(NULL, type, NULL, start, shift);
2756
2757 metaslab_rt_arg_t *mrap = kmem_zalloc(sizeof (*mrap), KM_SLEEP);
2758 mrap->mra_bt = &ms->ms_unflushed_frees_by_size;
2759 mrap->mra_floor_shift = metaslab_by_size_min_shift;
2760 ms->ms_unflushed_frees = range_tree_create(&metaslab_rt_ops,
2761 type, mrap, start, shift);
34dc7c2f 2762
ca577779 2763 ms->ms_trim = range_tree_create(NULL, type, NULL, start, shift);
1b939560
BB
2764
2765 metaslab_group_add(mg, ms);
65a91b16 2766 metaslab_set_fragmentation(ms, B_FALSE);
428870ff 2767
34dc7c2f
BB
2768 /*
2769 * If we're opening an existing pool (txg == 0) or creating
2770 * a new one (txg == TXG_INITIAL), all space is available now.
2771 * If we're adding space to an existing pool, the new space
2772 * does not become available until after this txg has synced.
4e21fd06
DB
2773 * The metaslab's weight will also be initialized when we sync
2774 * out this txg. This ensures that we don't attempt to allocate
2775 * from it before we have initialized it completely.
34dc7c2f 2776 */
425d3237 2777 if (txg <= TXG_INITIAL) {
fb42a493 2778 metaslab_sync_done(ms, 0);
425d3237
SD
2779 metaslab_space_update(vd, mg->mg_class,
2780 metaslab_allocated_space(ms), 0, 0);
2781 }
34dc7c2f
BB
2782
2783 if (txg != 0) {
34dc7c2f 2784 vdev_dirty(vd, 0, NULL, txg);
fb42a493 2785 vdev_dirty(vd, VDD_METASLAB, ms, txg);
34dc7c2f
BB
2786 }
2787
fb42a493
PS
2788 *msp = ms;
2789
2790 return (0);
34dc7c2f
BB
2791}
2792
93e28d66
SD
2793static void
2794metaslab_fini_flush_data(metaslab_t *msp)
2795{
2796 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2797
2798 if (metaslab_unflushed_txg(msp) == 0) {
2799 ASSERT3P(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL),
2800 ==, NULL);
2801 return;
2802 }
2803 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
2804
2805 mutex_enter(&spa->spa_flushed_ms_lock);
2806 avl_remove(&spa->spa_metaslabs_by_flushed, msp);
2807 mutex_exit(&spa->spa_flushed_ms_lock);
2808
2809 spa_log_sm_decrement_mscount(spa, metaslab_unflushed_txg(msp));
600a02b8
AM
2810 spa_log_summary_decrement_mscount(spa, metaslab_unflushed_txg(msp),
2811 metaslab_unflushed_dirty(msp));
93e28d66
SD
2812}
2813
2814uint64_t
2815metaslab_unflushed_changes_memused(metaslab_t *ms)
2816{
2817 return ((range_tree_numsegs(ms->ms_unflushed_allocs) +
2818 range_tree_numsegs(ms->ms_unflushed_frees)) *
ca577779 2819 ms->ms_unflushed_allocs->rt_root.bt_elem_size);
93e28d66
SD
2820}
2821
34dc7c2f
BB
2822void
2823metaslab_fini(metaslab_t *msp)
2824{
93cf2076 2825 metaslab_group_t *mg = msp->ms_group;
cc99f275 2826 vdev_t *vd = mg->mg_vd;
93e28d66
SD
2827 spa_t *spa = vd->vdev_spa;
2828
2829 metaslab_fini_flush_data(msp);
34dc7c2f
BB
2830
2831 metaslab_group_remove(mg, msp);
2832
2833 mutex_enter(&msp->ms_lock);
93cf2076 2834 VERIFY(msp->ms_group == NULL);
793c958f 2835
aa755b35 2836 /*
793c958f 2837 * If this metaslab hasn't been through metaslab_sync_done() yet its
aa755b35
MA
2838 * space hasn't been accounted for in its vdev and doesn't need to be
2839 * subtracted.
2840 */
793c958f 2841 if (!msp->ms_new) {
aa755b35
MA
2842 metaslab_space_update(vd, mg->mg_class,
2843 -metaslab_allocated_space(msp), 0, -msp->ms_size);
cc99f275 2844
aa755b35 2845 }
93cf2076 2846 space_map_close(msp->ms_sm);
93e28d66 2847 msp->ms_sm = NULL;
93cf2076
GW
2848
2849 metaslab_unload(msp);
aa755b35 2850
d2734cce 2851 range_tree_destroy(msp->ms_allocatable);
793c958f
SD
2852 range_tree_destroy(msp->ms_freeing);
2853 range_tree_destroy(msp->ms_freed);
34dc7c2f 2854
793c958f
SD
2855 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
2856 metaslab_unflushed_changes_memused(msp));
2857 spa->spa_unflushed_stats.sus_memused -=
2858 metaslab_unflushed_changes_memused(msp);
2859 range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
2860 range_tree_destroy(msp->ms_unflushed_allocs);
2861 range_tree_destroy(msp->ms_checkpointing);
2862 range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
2863 range_tree_destroy(msp->ms_unflushed_frees);
93e28d66 2864
793c958f
SD
2865 for (int t = 0; t < TXG_SIZE; t++) {
2866 range_tree_destroy(msp->ms_allocating[t]);
2867 }
2868 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2869 range_tree_destroy(msp->ms_defer[t]);
e51be066 2870 }
c99c9001 2871 ASSERT0(msp->ms_deferspace);
428870ff 2872
928e8ad4
SD
2873 for (int t = 0; t < TXG_SIZE; t++)
2874 ASSERT(!txg_list_member(&vd->vdev_ms_list, msp, t));
2875
1b939560
BB
2876 range_tree_vacate(msp->ms_trim, NULL, NULL);
2877 range_tree_destroy(msp->ms_trim);
2878
34dc7c2f 2879 mutex_exit(&msp->ms_lock);
93cf2076 2880 cv_destroy(&msp->ms_load_cv);
93e28d66 2881 cv_destroy(&msp->ms_flush_cv);
34dc7c2f 2882 mutex_destroy(&msp->ms_lock);
a1d477c2 2883 mutex_destroy(&msp->ms_sync_lock);
492f64e9 2884 ASSERT3U(msp->ms_allocator, ==, -1);
34dc7c2f
BB
2885
2886 kmem_free(msp, sizeof (metaslab_t));
2887}
2888
f3a7f661
GW
2889#define FRAGMENTATION_TABLE_SIZE 17
2890
93cf2076 2891/*
f3a7f661
GW
2892 * This table defines a segment size based fragmentation metric that will
2893 * allow each metaslab to derive its own fragmentation value. This is done
2894 * by calculating the space in each bucket of the spacemap histogram and
928e8ad4 2895 * multiplying that by the fragmentation metric in this table. Doing
f3a7f661
GW
2896 * this for all buckets and dividing it by the total amount of free
2897 * space in this metaslab (i.e. the total free space in all buckets) gives
2898 * us the fragmentation metric. This means that a high fragmentation metric
2899 * equates to most of the free space being comprised of small segments.
2900 * Conversely, if the metric is low, then most of the free space is in
2901 * large segments. A 10% change in fragmentation equates to approximately
2902 * double the number of segments.
93cf2076 2903 *
f3a7f661
GW
2904 * This table defines 0% fragmented space using 16MB segments. Testing has
2905 * shown that segments that are greater than or equal to 16MB do not suffer
2906 * from drastic performance problems. Using this value, we derive the rest
2907 * of the table. Since the fragmentation value is never stored on disk, it
2908 * is possible to change these calculations in the future.
2909 */
18168da7 2910static const int zfs_frag_table[FRAGMENTATION_TABLE_SIZE] = {
f3a7f661
GW
2911 100, /* 512B */
2912 100, /* 1K */
2913 98, /* 2K */
2914 95, /* 4K */
2915 90, /* 8K */
2916 80, /* 16K */
2917 70, /* 32K */
2918 60, /* 64K */
2919 50, /* 128K */
2920 40, /* 256K */
2921 30, /* 512K */
2922 20, /* 1M */
2923 15, /* 2M */
2924 10, /* 4M */
2925 5, /* 8M */
2926 0 /* 16M */
2927};
2928
2929/*
425d3237
SD
2930 * Calculate the metaslab's fragmentation metric and set ms_fragmentation.
2931 * Setting this value to ZFS_FRAG_INVALID means that the metaslab has not
2932 * been upgraded and does not support this metric. Otherwise, the return
2933 * value should be in the range [0, 100].
93cf2076 2934 */
4e21fd06 2935static void
65a91b16 2936metaslab_set_fragmentation(metaslab_t *msp, boolean_t nodirty)
93cf2076 2937{
f3a7f661
GW
2938 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2939 uint64_t fragmentation = 0;
2940 uint64_t total = 0;
2941 boolean_t feature_enabled = spa_feature_is_enabled(spa,
2942 SPA_FEATURE_SPACEMAP_HISTOGRAM);
93cf2076 2943
4e21fd06
DB
2944 if (!feature_enabled) {
2945 msp->ms_fragmentation = ZFS_FRAG_INVALID;
2946 return;
2947 }
f3a7f661 2948
93cf2076 2949 /*
f3a7f661
GW
2950 * A null space map means that the entire metaslab is free
2951 * and thus is not fragmented.
93cf2076 2952 */
4e21fd06
DB
2953 if (msp->ms_sm == NULL) {
2954 msp->ms_fragmentation = 0;
2955 return;
2956 }
f3a7f661
GW
2957
2958 /*
4e21fd06 2959 * If this metaslab's space map has not been upgraded, flag it
f3a7f661
GW
2960 * so that we upgrade next time we encounter it.
2961 */
2962 if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
3b7f360c 2963 uint64_t txg = spa_syncing_txg(spa);
93cf2076
GW
2964 vdev_t *vd = msp->ms_group->mg_vd;
2965
3b7f360c
GW
2966 /*
2967 * If we've reached the final dirty txg, then we must
2968 * be shutting down the pool. We don't want to dirty
2969 * any data past this point so skip setting the condense
2970 * flag. We can retry this action the next time the pool
65a91b16
SD
2971 * is imported. We also skip marking this metaslab for
2972 * condensing if the caller has explicitly set nodirty.
3b7f360c 2973 */
65a91b16
SD
2974 if (!nodirty &&
2975 spa_writeable(spa) && txg < spa_final_dirty_txg(spa)) {
8b0a0840
TC
2976 msp->ms_condense_wanted = B_TRUE;
2977 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
964c2d69 2978 zfs_dbgmsg("txg %llu, requesting force condense: "
8e739b2c
RE
2979 "ms_id %llu, vdev_id %llu", (u_longlong_t)txg,
2980 (u_longlong_t)msp->ms_id,
2981 (u_longlong_t)vd->vdev_id);
8b0a0840 2982 }
4e21fd06
DB
2983 msp->ms_fragmentation = ZFS_FRAG_INVALID;
2984 return;
93cf2076
GW
2985 }
2986
1c27024e 2987 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
f3a7f661
GW
2988 uint64_t space = 0;
2989 uint8_t shift = msp->ms_sm->sm_shift;
4e21fd06 2990
f3a7f661
GW
2991 int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
2992 FRAGMENTATION_TABLE_SIZE - 1);
93cf2076 2993
93cf2076
GW
2994 if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
2995 continue;
2996
f3a7f661
GW
2997 space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
2998 total += space;
2999
3000 ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
3001 fragmentation += space * zfs_frag_table[idx];
93cf2076 3002 }
f3a7f661
GW
3003
3004 if (total > 0)
3005 fragmentation /= total;
3006 ASSERT3U(fragmentation, <=, 100);
4e21fd06
DB
3007
3008 msp->ms_fragmentation = fragmentation;
93cf2076 3009}
34dc7c2f 3010
f3a7f661
GW
3011/*
3012 * Compute a weight -- a selection preference value -- for the given metaslab.
3013 * This is based on the amount of free space, the level of fragmentation,
3014 * the LBA range, and whether the metaslab is loaded.
3015 */
34dc7c2f 3016static uint64_t
4e21fd06 3017metaslab_space_weight(metaslab_t *msp)
34dc7c2f
BB
3018{
3019 metaslab_group_t *mg = msp->ms_group;
34dc7c2f
BB
3020 vdev_t *vd = mg->mg_vd;
3021 uint64_t weight, space;
3022
3023 ASSERT(MUTEX_HELD(&msp->ms_lock));
c2e42f9d 3024
34dc7c2f
BB
3025 /*
3026 * The baseline weight is the metaslab's free space.
3027 */
425d3237 3028 space = msp->ms_size - metaslab_allocated_space(msp);
f3a7f661 3029
f3a7f661
GW
3030 if (metaslab_fragmentation_factor_enabled &&
3031 msp->ms_fragmentation != ZFS_FRAG_INVALID) {
3032 /*
3033 * Use the fragmentation information to inversely scale
3034 * down the baseline weight. We need to ensure that we
3035 * don't exclude this metaslab completely when it's 100%
3036 * fragmented. To avoid this we reduce the fragmented value
3037 * by 1.
3038 */
3039 space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
3040
3041 /*
3042 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
3043 * this metaslab again. The fragmentation metric may have
3044 * decreased the space to something smaller than
3045 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
3046 * so that we can consume any remaining space.
3047 */
3048 if (space > 0 && space < SPA_MINBLOCKSIZE)
3049 space = SPA_MINBLOCKSIZE;
3050 }
34dc7c2f
BB
3051 weight = space;
3052
3053 /*
3054 * Modern disks have uniform bit density and constant angular velocity.
3055 * Therefore, the outer recording zones are faster (higher bandwidth)
3056 * than the inner zones by the ratio of outer to inner track diameter,
3057 * which is typically around 2:1. We account for this by assigning
3058 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
3059 * In effect, this means that we'll select the metaslab with the most
3060 * free bandwidth rather than simply the one with the most free space.
3061 */
fb40095f 3062 if (!vd->vdev_nonrot && metaslab_lba_weighting_enabled) {
f3a7f661
GW
3063 weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
3064 ASSERT(weight >= space && weight <= 2 * space);
3065 }
428870ff 3066
f3a7f661
GW
3067 /*
3068 * If this metaslab is one we're actively using, adjust its
3069 * weight to make it preferable to any inactive metaslab so
3070 * we'll polish it off. If the fragmentation on this metaslab
3071 * has exceed our threshold, then don't mark it active.
3072 */
3073 if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
3074 msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
428870ff
BB
3075 weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
3076 }
34dc7c2f 3077
4e21fd06
DB
3078 WEIGHT_SET_SPACEBASED(weight);
3079 return (weight);
3080}
3081
3082/*
3083 * Return the weight of the specified metaslab, according to the segment-based
3084 * weighting algorithm. The metaslab must be loaded. This function can
3085 * be called within a sync pass since it relies only on the metaslab's
3086 * range tree which is always accurate when the metaslab is loaded.
3087 */
3088static uint64_t
3089metaslab_weight_from_range_tree(metaslab_t *msp)
3090{
3091 uint64_t weight = 0;
3092 uint32_t segments = 0;
4e21fd06
DB
3093
3094 ASSERT(msp->ms_loaded);
3095
1c27024e
DB
3096 for (int i = RANGE_TREE_HISTOGRAM_SIZE - 1; i >= SPA_MINBLOCKSHIFT;
3097 i--) {
4e21fd06
DB
3098 uint8_t shift = msp->ms_group->mg_vd->vdev_ashift;
3099 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
3100
3101 segments <<= 1;
d2734cce 3102 segments += msp->ms_allocatable->rt_histogram[i];
4e21fd06
DB
3103
3104 /*
3105 * The range tree provides more precision than the space map
3106 * and must be downgraded so that all values fit within the
3107 * space map's histogram. This allows us to compare loaded
3108 * vs. unloaded metaslabs to determine which metaslab is
3109 * considered "best".
3110 */
3111 if (i > max_idx)
3112 continue;
3113
3114 if (segments != 0) {
3115 WEIGHT_SET_COUNT(weight, segments);
3116 WEIGHT_SET_INDEX(weight, i);
3117 WEIGHT_SET_ACTIVE(weight, 0);
3118 break;
3119 }
3120 }
3121 return (weight);
3122}
3123
3124/*
93e28d66
SD
3125 * Calculate the weight based on the on-disk histogram. Should be applied
3126 * only to unloaded metaslabs (i.e no incoming allocations) in-order to
3127 * give results consistent with the on-disk state
4e21fd06
DB
3128 */
3129static uint64_t
3130metaslab_weight_from_spacemap(metaslab_t *msp)
3131{
928e8ad4
SD
3132 space_map_t *sm = msp->ms_sm;
3133 ASSERT(!msp->ms_loaded);
3134 ASSERT(sm != NULL);
3135 ASSERT3U(space_map_object(sm), !=, 0);
3136 ASSERT3U(sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
4e21fd06 3137
928e8ad4
SD
3138 /*
3139 * Create a joint histogram from all the segments that have made
3140 * it to the metaslab's space map histogram, that are not yet
3141 * available for allocation because they are still in the freeing
3142 * pipeline (e.g. freeing, freed, and defer trees). Then subtract
3143 * these segments from the space map's histogram to get a more
3144 * accurate weight.
3145 */
3146 uint64_t deferspace_histogram[SPACE_MAP_HISTOGRAM_SIZE] = {0};
3147 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
3148 deferspace_histogram[i] += msp->ms_synchist[i];
3149 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3150 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
3151 deferspace_histogram[i] += msp->ms_deferhist[t][i];
3152 }
3153 }
3154
3155 uint64_t weight = 0;
1c27024e 3156 for (int i = SPACE_MAP_HISTOGRAM_SIZE - 1; i >= 0; i--) {
928e8ad4
SD
3157 ASSERT3U(sm->sm_phys->smp_histogram[i], >=,
3158 deferspace_histogram[i]);
3159 uint64_t count =
3160 sm->sm_phys->smp_histogram[i] - deferspace_histogram[i];
3161 if (count != 0) {
3162 WEIGHT_SET_COUNT(weight, count);
3163 WEIGHT_SET_INDEX(weight, i + sm->sm_shift);
4e21fd06
DB
3164 WEIGHT_SET_ACTIVE(weight, 0);
3165 break;
3166 }
3167 }
3168 return (weight);
3169}
3170
3171/*
3172 * Compute a segment-based weight for the specified metaslab. The weight
3173 * is determined by highest bucket in the histogram. The information
3174 * for the highest bucket is encoded into the weight value.
3175 */
3176static uint64_t
3177metaslab_segment_weight(metaslab_t *msp)
3178{
3179 metaslab_group_t *mg = msp->ms_group;
3180 uint64_t weight = 0;
3181 uint8_t shift = mg->mg_vd->vdev_ashift;
3182
3183 ASSERT(MUTEX_HELD(&msp->ms_lock));
3184
3185 /*
3186 * The metaslab is completely free.
3187 */
425d3237 3188 if (metaslab_allocated_space(msp) == 0) {
4e21fd06
DB
3189 int idx = highbit64(msp->ms_size) - 1;
3190 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
3191
3192 if (idx < max_idx) {
3193 WEIGHT_SET_COUNT(weight, 1ULL);
3194 WEIGHT_SET_INDEX(weight, idx);
3195 } else {
3196 WEIGHT_SET_COUNT(weight, 1ULL << (idx - max_idx));
3197 WEIGHT_SET_INDEX(weight, max_idx);
3198 }
3199 WEIGHT_SET_ACTIVE(weight, 0);
3200 ASSERT(!WEIGHT_IS_SPACEBASED(weight));
4e21fd06
DB
3201 return (weight);
3202 }
3203
3204 ASSERT3U(msp->ms_sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
3205
3206 /*
3207 * If the metaslab is fully allocated then just make the weight 0.
3208 */
425d3237 3209 if (metaslab_allocated_space(msp) == msp->ms_size)
4e21fd06
DB
3210 return (0);
3211 /*
3212 * If the metaslab is already loaded, then use the range tree to
3213 * determine the weight. Otherwise, we rely on the space map information
3214 * to generate the weight.
3215 */
3216 if (msp->ms_loaded) {
3217 weight = metaslab_weight_from_range_tree(msp);
3218 } else {
3219 weight = metaslab_weight_from_spacemap(msp);
3220 }
3221
3222 /*
3223 * If the metaslab was active the last time we calculated its weight
3224 * then keep it active. We want to consume the entire region that
3225 * is associated with this weight.
3226 */
3227 if (msp->ms_activation_weight != 0 && weight != 0)
3228 WEIGHT_SET_ACTIVE(weight, WEIGHT_GET_ACTIVE(msp->ms_weight));
3229 return (weight);
3230}
3231
3232/*
3233 * Determine if we should attempt to allocate from this metaslab. If the
7f319089
SD
3234 * metaslab is loaded, then we can determine if the desired allocation
3235 * can be satisfied by looking at the size of the maximum free segment
3236 * on that metaslab. Otherwise, we make our decision based on the metaslab's
3237 * weight. For segment-based weighting we can determine the maximum
3238 * allocation based on the index encoded in its value. For space-based
3239 * weights we rely on the entire weight (excluding the weight-type bit).
4e21fd06 3240 */
65c7cc49 3241static boolean_t
c81f1790 3242metaslab_should_allocate(metaslab_t *msp, uint64_t asize, boolean_t try_hard)
4e21fd06 3243{
5551dcd7
PD
3244 /*
3245 * This case will usually but not always get caught by the checks below;
3246 * metaslabs can be loaded by various means, including the trim and
3247 * initialize code. Once that happens, without this check they are
3248 * allocatable even before they finish their first txg sync.
3249 */
3250 if (unlikely(msp->ms_new))
3251 return (B_FALSE);
3252
c81f1790
PD
3253 /*
3254 * If the metaslab is loaded, ms_max_size is definitive and we can use
3255 * the fast check. If it's not, the ms_max_size is a lower bound (once
3256 * set), and we should use the fast check as long as we're not in
3257 * try_hard and it's been less than zfs_metaslab_max_size_cache_sec
3258 * seconds since the metaslab was unloaded.
3259 */
3260 if (msp->ms_loaded ||
3261 (msp->ms_max_size != 0 && !try_hard && gethrtime() <
3262 msp->ms_unload_time + SEC2NSEC(zfs_metaslab_max_size_cache_sec)))
4e21fd06
DB
3263 return (msp->ms_max_size >= asize);
3264
679b0f2a 3265 boolean_t should_allocate;
4e21fd06
DB
3266 if (!WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
3267 /*
3268 * The metaslab segment weight indicates segments in the
3269 * range [2^i, 2^(i+1)), where i is the index in the weight.
3270 * Since the asize might be in the middle of the range, we
3271 * should attempt the allocation if asize < 2^(i+1).
3272 */
3273 should_allocate = (asize <
3274 1ULL << (WEIGHT_GET_INDEX(msp->ms_weight) + 1));
3275 } else {
3276 should_allocate = (asize <=
3277 (msp->ms_weight & ~METASLAB_WEIGHT_TYPE));
3278 }
679b0f2a 3279
4e21fd06
DB
3280 return (should_allocate);
3281}
65a91b16 3282
4e21fd06 3283static uint64_t
65a91b16 3284metaslab_weight(metaslab_t *msp, boolean_t nodirty)
4e21fd06
DB
3285{
3286 vdev_t *vd = msp->ms_group->mg_vd;
3287 spa_t *spa = vd->vdev_spa;
3288 uint64_t weight;
3289
3290 ASSERT(MUTEX_HELD(&msp->ms_lock));
3291
65a91b16 3292 metaslab_set_fragmentation(msp, nodirty);
4e21fd06
DB
3293
3294 /*
c81f1790 3295 * Update the maximum size. If the metaslab is loaded, this will
4e21fd06 3296 * ensure that we get an accurate maximum size if newly freed space
c81f1790
PD
3297 * has been added back into the free tree. If the metaslab is
3298 * unloaded, we check if there's a larger free segment in the
3299 * unflushed frees. This is a lower bound on the largest allocatable
3300 * segment size. Coalescing of adjacent entries may reveal larger
3301 * allocatable segments, but we aren't aware of those until loading
3302 * the space map into a range tree.
4e21fd06 3303 */
c81f1790
PD
3304 if (msp->ms_loaded) {
3305 msp->ms_max_size = metaslab_largest_allocatable(msp);
3306 } else {
3307 msp->ms_max_size = MAX(msp->ms_max_size,
3308 metaslab_largest_unflushed_free(msp));
3309 }
4e21fd06
DB
3310
3311 /*
3312 * Segment-based weighting requires space map histogram support.
3313 */
3314 if (zfs_metaslab_segment_weight_enabled &&
3315 spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM) &&
3316 (msp->ms_sm == NULL || msp->ms_sm->sm_dbuf->db_size ==
3317 sizeof (space_map_phys_t))) {
3318 weight = metaslab_segment_weight(msp);
3319 } else {
3320 weight = metaslab_space_weight(msp);
3321 }
93cf2076 3322 return (weight);
34dc7c2f
BB
3323}
3324
928e8ad4
SD
3325void
3326metaslab_recalculate_weight_and_sort(metaslab_t *msp)
3327{
679b0f2a
PD
3328 ASSERT(MUTEX_HELD(&msp->ms_lock));
3329
928e8ad4
SD
3330 /* note: we preserve the mask (e.g. indication of primary, etc..) */
3331 uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
3332 metaslab_group_sort(msp->ms_group, msp,
65a91b16 3333 metaslab_weight(msp, B_FALSE) | was_active);
928e8ad4
SD
3334}
3335
34dc7c2f 3336static int
492f64e9
PD
3337metaslab_activate_allocator(metaslab_group_t *mg, metaslab_t *msp,
3338 int allocator, uint64_t activation_weight)
3339{
32d805c3 3340 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
679b0f2a
PD
3341 ASSERT(MUTEX_HELD(&msp->ms_lock));
3342
492f64e9
PD
3343 /*
3344 * If we're activating for the claim code, we don't want to actually
3345 * set the metaslab up for a specific allocator.
3346 */
f09fda50
PD
3347 if (activation_weight == METASLAB_WEIGHT_CLAIM) {
3348 ASSERT0(msp->ms_activation_weight);
3349 msp->ms_activation_weight = msp->ms_weight;
3350 metaslab_group_sort(mg, msp, msp->ms_weight |
3351 activation_weight);
492f64e9 3352 return (0);
f09fda50 3353 }
679b0f2a 3354
32d805c3
MA
3355 metaslab_t **mspp = (activation_weight == METASLAB_WEIGHT_PRIMARY ?
3356 &mga->mga_primary : &mga->mga_secondary);
492f64e9 3357
492f64e9 3358 mutex_enter(&mg->mg_lock);
32d805c3 3359 if (*mspp != NULL) {
492f64e9
PD
3360 mutex_exit(&mg->mg_lock);
3361 return (EEXIST);
3362 }
3363
32d805c3 3364 *mspp = msp;
492f64e9
PD
3365 ASSERT3S(msp->ms_allocator, ==, -1);
3366 msp->ms_allocator = allocator;
3367 msp->ms_primary = (activation_weight == METASLAB_WEIGHT_PRIMARY);
f09fda50
PD
3368
3369 ASSERT0(msp->ms_activation_weight);
3370 msp->ms_activation_weight = msp->ms_weight;
3371 metaslab_group_sort_impl(mg, msp,
3372 msp->ms_weight | activation_weight);
492f64e9
PD
3373 mutex_exit(&mg->mg_lock);
3374
3375 return (0);
3376}
3377
3378static int
3379metaslab_activate(metaslab_t *msp, int allocator, uint64_t activation_weight)
34dc7c2f 3380{
34dc7c2f
BB
3381 ASSERT(MUTEX_HELD(&msp->ms_lock));
3382
679b0f2a
PD
3383 /*
3384 * The current metaslab is already activated for us so there
3385 * is nothing to do. Already activated though, doesn't mean
3386 * that this metaslab is activated for our allocator nor our
3387 * requested activation weight. The metaslab could have started
3388 * as an active one for our allocator but changed allocators
3389 * while we were waiting to grab its ms_lock or we stole it
3390 * [see find_valid_metaslab()]. This means that there is a
3391 * possibility of passivating a metaslab of another allocator
3392 * or from a different activation mask, from this thread.
3393 */
3394 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
3395 ASSERT(msp->ms_loaded);
3396 return (0);
3397 }
3398
3399 int error = metaslab_load(msp);
3400 if (error != 0) {
3401 metaslab_group_sort(msp->ms_group, msp, 0);
3402 return (error);
3403 }
3404
3405 /*
3406 * When entering metaslab_load() we may have dropped the
3407 * ms_lock because we were loading this metaslab, or we
3408 * were waiting for another thread to load it for us. In
3409 * that scenario, we recheck the weight of the metaslab
3410 * to see if it was activated by another thread.
3411 *
3412 * If the metaslab was activated for another allocator or
3413 * it was activated with a different activation weight (e.g.
3414 * we wanted to make it a primary but it was activated as
3415 * secondary) we return error (EBUSY).
3416 *
3417 * If the metaslab was activated for the same allocator
3418 * and requested activation mask, skip activating it.
3419 */
3420 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
3421 if (msp->ms_allocator != allocator)
3422 return (EBUSY);
3423
3424 if ((msp->ms_weight & activation_weight) == 0)
7ab96299 3425 return (SET_ERROR(EBUSY));
9babb374 3426
679b0f2a
PD
3427 EQUIV((activation_weight == METASLAB_WEIGHT_PRIMARY),
3428 msp->ms_primary);
3429 return (0);
34dc7c2f 3430 }
679b0f2a 3431
fe0ea848
PD
3432 /*
3433 * If the metaslab has literally 0 space, it will have weight 0. In
3434 * that case, don't bother activating it. This can happen if the
3435 * metaslab had space during find_valid_metaslab, but another thread
3436 * loaded it and used all that space while we were waiting to grab the
3437 * lock.
3438 */
3439 if (msp->ms_weight == 0) {
3440 ASSERT0(range_tree_space(msp->ms_allocatable));
3441 return (SET_ERROR(ENOSPC));
3442 }
3443
679b0f2a
PD
3444 if ((error = metaslab_activate_allocator(msp->ms_group, msp,
3445 allocator, activation_weight)) != 0) {
3446 return (error);
3447 }
3448
93cf2076 3449 ASSERT(msp->ms_loaded);
34dc7c2f
BB
3450 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
3451
3452 return (0);
3453}
3454
492f64e9
PD
3455static void
3456metaslab_passivate_allocator(metaslab_group_t *mg, metaslab_t *msp,
3457 uint64_t weight)
3458{
3459 ASSERT(MUTEX_HELD(&msp->ms_lock));
679b0f2a
PD
3460 ASSERT(msp->ms_loaded);
3461
492f64e9
PD
3462 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
3463 metaslab_group_sort(mg, msp, weight);
3464 return;
3465 }
3466
3467 mutex_enter(&mg->mg_lock);
3468 ASSERT3P(msp->ms_group, ==, mg);
679b0f2a
PD
3469 ASSERT3S(0, <=, msp->ms_allocator);
3470 ASSERT3U(msp->ms_allocator, <, mg->mg_allocators);
3471
32d805c3 3472 metaslab_group_allocator_t *mga = &mg->mg_allocator[msp->ms_allocator];
492f64e9 3473 if (msp->ms_primary) {
32d805c3 3474 ASSERT3P(mga->mga_primary, ==, msp);
492f64e9 3475 ASSERT(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
32d805c3 3476 mga->mga_primary = NULL;
492f64e9 3477 } else {
32d805c3 3478 ASSERT3P(mga->mga_secondary, ==, msp);
679b0f2a 3479 ASSERT(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
32d805c3 3480 mga->mga_secondary = NULL;
492f64e9
PD
3481 }
3482 msp->ms_allocator = -1;
3483 metaslab_group_sort_impl(mg, msp, weight);
3484 mutex_exit(&mg->mg_lock);
3485}
3486
34dc7c2f 3487static void
4e21fd06 3488metaslab_passivate(metaslab_t *msp, uint64_t weight)
34dc7c2f 3489{
2a8ba608 3490 uint64_t size __maybe_unused = weight & ~METASLAB_WEIGHT_TYPE;
4e21fd06 3491
34dc7c2f
BB
3492 /*
3493 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
3494 * this metaslab again. In that case, it had better be empty,
3495 * or we would be leaving space on the table.
3496 */
94d49e8f
TC
3497 ASSERT(!WEIGHT_IS_SPACEBASED(msp->ms_weight) ||
3498 size >= SPA_MINBLOCKSIZE ||
d2734cce 3499 range_tree_space(msp->ms_allocatable) == 0);
4e21fd06
DB
3500 ASSERT0(weight & METASLAB_ACTIVE_MASK);
3501
679b0f2a 3502 ASSERT(msp->ms_activation_weight != 0);
4e21fd06 3503 msp->ms_activation_weight = 0;
492f64e9 3504 metaslab_passivate_allocator(msp->ms_group, msp, weight);
679b0f2a 3505 ASSERT0(msp->ms_weight & METASLAB_ACTIVE_MASK);
34dc7c2f
BB
3506}
3507
4e21fd06
DB
3508/*
3509 * Segment-based metaslabs are activated once and remain active until
3510 * we either fail an allocation attempt (similar to space-based metaslabs)
3511 * or have exhausted the free space in zfs_metaslab_switch_threshold
3512 * buckets since the metaslab was activated. This function checks to see
e1cfd73f 3513 * if we've exhausted the zfs_metaslab_switch_threshold buckets in the
4e21fd06
DB
3514 * metaslab and passivates it proactively. This will allow us to select a
3515 * metaslab with a larger contiguous region, if any, remaining within this
3516 * metaslab group. If we're in sync pass > 1, then we continue using this
3517 * metaslab so that we don't dirty more block and cause more sync passes.
3518 */
65c7cc49 3519static void
4e21fd06
DB
3520metaslab_segment_may_passivate(metaslab_t *msp)
3521{
3522 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
4e21fd06
DB
3523
3524 if (WEIGHT_IS_SPACEBASED(msp->ms_weight) || spa_sync_pass(spa) > 1)
3525 return;
3526
3527 /*
3528 * Since we are in the middle of a sync pass, the most accurate
3529 * information that is accessible to us is the in-core range tree
3530 * histogram; calculate the new weight based on that information.
3531 */
1c27024e
DB
3532 uint64_t weight = metaslab_weight_from_range_tree(msp);
3533 int activation_idx = WEIGHT_GET_INDEX(msp->ms_activation_weight);
3534 int current_idx = WEIGHT_GET_INDEX(weight);
4e21fd06
DB
3535
3536 if (current_idx <= activation_idx - zfs_metaslab_switch_threshold)
3537 metaslab_passivate(msp, weight);
3538}
3539
93cf2076
GW
3540static void
3541metaslab_preload(void *arg)
3542{
3543 metaslab_t *msp = arg;
f09fda50
PD
3544 metaslab_class_t *mc = msp->ms_group->mg_class;
3545 spa_t *spa = mc->mc_spa;
1cd77734 3546 fstrans_cookie_t cookie = spl_fstrans_mark();
93cf2076 3547
080b3100
GW
3548 ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
3549
93cf2076 3550 mutex_enter(&msp->ms_lock);
b194fab0 3551 (void) metaslab_load(msp);
f09fda50 3552 metaslab_set_selected_txg(msp, spa_syncing_txg(spa));
93cf2076 3553 mutex_exit(&msp->ms_lock);
1cd77734 3554 spl_fstrans_unmark(cookie);
93cf2076
GW
3555}
3556
3557static void
3558metaslab_group_preload(metaslab_group_t *mg)
3559{
3560 spa_t *spa = mg->mg_vd->vdev_spa;
3561 metaslab_t *msp;
3562 avl_tree_t *t = &mg->mg_metaslab_tree;
3563 int m = 0;
3564
342357cd 3565 if (spa_shutting_down(spa) || !metaslab_preload_enabled)
93cf2076 3566 return;
93cf2076 3567
080b3100 3568 mutex_enter(&mg->mg_lock);
a1d477c2 3569
93cf2076 3570 /*
080b3100 3571 * Load the next potential metaslabs
93cf2076 3572 */
4e21fd06 3573 for (msp = avl_first(t); msp != NULL; msp = AVL_NEXT(t, msp)) {
a1d477c2
MA
3574 ASSERT3P(msp->ms_group, ==, mg);
3575
f3a7f661
GW
3576 /*
3577 * We preload only the maximum number of metaslabs specified
3578 * by metaslab_preload_limit. If a metaslab is being forced
3579 * to condense then we preload it too. This will ensure
3580 * that force condensing happens in the next txg.
3581 */
3582 if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
f3a7f661
GW
3583 continue;
3584 }
93cf2076 3585
342357cd
AM
3586 VERIFY(taskq_dispatch(spa->spa_metaslab_taskq, metaslab_preload,
3587 msp, TQ_SLEEP | (m <= mg->mg_allocators ? TQ_FRONT : 0))
3588 != TASKQID_INVALID);
93cf2076
GW
3589 }
3590 mutex_exit(&mg->mg_lock);
3591}
3592
e51be066 3593/*
93e28d66
SD
3594 * Determine if the space map's on-disk footprint is past our tolerance for
3595 * inefficiency. We would like to use the following criteria to make our
3596 * decision:
e51be066 3597 *
93e28d66
SD
3598 * 1. Do not condense if the size of the space map object would dramatically
3599 * increase as a result of writing out the free space range tree.
e51be066 3600 *
93e28d66
SD
3601 * 2. Condense if the on on-disk space map representation is at least
3602 * zfs_condense_pct/100 times the size of the optimal representation
3603 * (i.e. zfs_condense_pct = 110 and in-core = 1MB, optimal = 1.1MB).
e51be066 3604 *
93e28d66
SD
3605 * 3. Do not condense if the on-disk size of the space map does not actually
3606 * decrease.
b02fe35d 3607 *
b02fe35d
AR
3608 * Unfortunately, we cannot compute the on-disk size of the space map in this
3609 * context because we cannot accurately compute the effects of compression, etc.
3610 * Instead, we apply the heuristic described in the block comment for
3611 * zfs_metaslab_condense_block_threshold - we only condense if the space used
3612 * is greater than a threshold number of blocks.
e51be066
GW
3613 */
3614static boolean_t
3615metaslab_should_condense(metaslab_t *msp)
3616{
93cf2076 3617 space_map_t *sm = msp->ms_sm;
d2734cce 3618 vdev_t *vd = msp->ms_group->mg_vd;
e506a0ce 3619 uint64_t vdev_blocksize = 1ULL << vd->vdev_ashift;
e51be066
GW
3620
3621 ASSERT(MUTEX_HELD(&msp->ms_lock));
93cf2076 3622 ASSERT(msp->ms_loaded);
93e28d66
SD
3623 ASSERT(sm != NULL);
3624 ASSERT3U(spa_sync_pass(vd->vdev_spa), ==, 1);
d2734cce
SD
3625
3626 /*
4d044c4c
SD
3627 * We always condense metaslabs that are empty and metaslabs for
3628 * which a condense request has been made.
e51be066 3629 */
ca577779 3630 if (range_tree_numsegs(msp->ms_allocatable) == 0 ||
4d044c4c 3631 msp->ms_condense_wanted)
e51be066
GW
3632 return (B_TRUE);
3633
93e28d66
SD
3634 uint64_t record_size = MAX(sm->sm_blksz, vdev_blocksize);
3635 uint64_t object_size = space_map_length(sm);
4d044c4c
SD
3636 uint64_t optimal_size = space_map_estimate_optimal_size(sm,
3637 msp->ms_allocatable, SM_NO_VDEVID);
b02fe35d 3638
4d044c4c 3639 return (object_size >= (optimal_size * zfs_condense_pct / 100) &&
b02fe35d 3640 object_size > zfs_metaslab_condense_block_threshold * record_size);
e51be066
GW
3641}
3642
3643/*
3644 * Condense the on-disk space map representation to its minimized form.
93e28d66
SD
3645 * The minimized form consists of a small number of allocations followed
3646 * by the entries of the free range tree (ms_allocatable). The condensed
3647 * spacemap contains all the entries of previous TXGs (including those in
3648 * the pool-wide log spacemaps; thus this is effectively a superset of
3649 * metaslab_flush()), but this TXG's entries still need to be written.
e51be066
GW
3650 */
3651static void
93e28d66 3652metaslab_condense(metaslab_t *msp, dmu_tx_t *tx)
e51be066 3653{
93cf2076
GW
3654 range_tree_t *condense_tree;
3655 space_map_t *sm = msp->ms_sm;
93e28d66
SD
3656 uint64_t txg = dmu_tx_get_txg(tx);
3657 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
e51be066
GW
3658
3659 ASSERT(MUTEX_HELD(&msp->ms_lock));
93cf2076 3660 ASSERT(msp->ms_loaded);
93e28d66 3661 ASSERT(msp->ms_sm != NULL);
e51be066 3662
93e28d66
SD
3663 /*
3664 * In order to condense the space map, we need to change it so it
3665 * only describes which segments are currently allocated and free.
3666 *
3667 * All the current free space resides in the ms_allocatable, all
3668 * the ms_defer trees, and all the ms_allocating trees. We ignore
3669 * ms_freed because it is empty because we're in sync pass 1. We
3670 * ignore ms_freeing because these changes are not yet reflected
3671 * in the spacemap (they will be written later this txg).
3672 *
3673 * So to truncate the space map to represent all the entries of
3674 * previous TXGs we do the following:
3675 *
ca577779
PD
3676 * 1] We create a range tree (condense tree) that is 100% empty.
3677 * 2] We add to it all segments found in the ms_defer trees
93e28d66
SD
3678 * as those segments are marked as free in the original space
3679 * map. We do the same with the ms_allocating trees for the same
ca577779 3680 * reason. Adding these segments should be a relatively
93e28d66
SD
3681 * inexpensive operation since we expect these trees to have a
3682 * small number of nodes.
ca577779
PD
3683 * 3] We vacate any unflushed allocs, since they are not frees we
3684 * need to add to the condense tree. Then we vacate any
3685 * unflushed frees as they should already be part of ms_allocatable.
3686 * 4] At this point, we would ideally like to add all segments
93e28d66
SD
3687 * in the ms_allocatable tree from the condense tree. This way
3688 * we would write all the entries of the condense tree as the
dd4bc569 3689 * condensed space map, which would only contain freed
ca577779 3690 * segments with everything else assumed to be allocated.
93e28d66
SD
3691 *
3692 * Doing so can be prohibitively expensive as ms_allocatable can
ca577779
PD
3693 * be large, and therefore computationally expensive to add to
3694 * the condense_tree. Instead we first sync out an entry marking
3695 * everything as allocated, then the condense_tree and then the
3696 * ms_allocatable, in the condensed space map. While this is not
3697 * optimal, it is typically close to optimal and more importantly
3698 * much cheaper to compute.
93e28d66
SD
3699 *
3700 * 5] Finally, as both of the unflushed trees were written to our
3701 * new and condensed metaslab space map, we basically flushed
3702 * all the unflushed changes to disk, thus we call
3703 * metaslab_flush_update().
3704 */
3705 ASSERT3U(spa_sync_pass(spa), ==, 1);
3706 ASSERT(range_tree_is_empty(msp->ms_freed)); /* since it is pass 1 */
f3a7f661 3707
a887d653 3708 zfs_dbgmsg("condensing: txg %llu, msp[%llu] %px, vdev id %llu, "
8e739b2c
RE
3709 "spa %s, smp size %llu, segments %llu, forcing condense=%s",
3710 (u_longlong_t)txg, (u_longlong_t)msp->ms_id, msp,
3711 (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
3712 spa->spa_name, (u_longlong_t)space_map_length(msp->ms_sm),
3713 (u_longlong_t)range_tree_numsegs(msp->ms_allocatable),
f3a7f661
GW
3714 msp->ms_condense_wanted ? "TRUE" : "FALSE");
3715
3716 msp->ms_condense_wanted = B_FALSE;
e51be066 3717
ca577779
PD
3718 range_seg_type_t type;
3719 uint64_t shift, start;
3720 type = metaslab_calculate_range_tree_type(msp->ms_group->mg_vd, msp,
3721 &start, &shift);
3722
3723 condense_tree = range_tree_create(NULL, type, NULL, start, shift);
e51be066 3724
1c27024e 3725 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
d2734cce 3726 range_tree_walk(msp->ms_defer[t],
ca577779 3727 range_tree_add, condense_tree);
93cf2076 3728 }
e51be066 3729
93e28d66 3730 for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
d2734cce 3731 range_tree_walk(msp->ms_allocating[(txg + t) & TXG_MASK],
ca577779 3732 range_tree_add, condense_tree);
93cf2076 3733 }
e51be066 3734
93e28d66
SD
3735 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
3736 metaslab_unflushed_changes_memused(msp));
3737 spa->spa_unflushed_stats.sus_memused -=
3738 metaslab_unflushed_changes_memused(msp);
3739 range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
3740 range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
3741
e51be066 3742 /*
93e28d66
SD
3743 * We're about to drop the metaslab's lock thus allowing other
3744 * consumers to change it's content. Set the metaslab's ms_condensing
3745 * flag to ensure that allocations on this metaslab do not occur
3746 * while we're in the middle of committing it to disk. This is only
3747 * critical for ms_allocatable as all other range trees use per TXG
e51be066
GW
3748 * views of their content.
3749 */
93cf2076 3750 msp->ms_condensing = B_TRUE;
e51be066
GW
3751
3752 mutex_exit(&msp->ms_lock);
93e28d66
SD
3753 uint64_t object = space_map_object(msp->ms_sm);
3754 space_map_truncate(sm,
3755 spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP) ?
3756 zfs_metaslab_sm_blksz_with_log : zfs_metaslab_sm_blksz_no_log, tx);
3757
3758 /*
3759 * space_map_truncate() may have reallocated the spacemap object.
3760 * If so, update the vdev_ms_array.
3761 */
3762 if (space_map_object(msp->ms_sm) != object) {
3763 object = space_map_object(msp->ms_sm);
3764 dmu_write(spa->spa_meta_objset,
3765 msp->ms_group->mg_vd->vdev_ms_array, sizeof (uint64_t) *
3766 msp->ms_id, sizeof (uint64_t), &object, tx);
3767 }
e51be066
GW
3768
3769 /*
93e28d66
SD
3770 * Note:
3771 * When the log space map feature is enabled, each space map will
3772 * always have ALLOCS followed by FREES for each sync pass. This is
3773 * typically true even when the log space map feature is disabled,
3774 * except from the case where a metaslab goes through metaslab_sync()
3775 * and gets condensed. In that case the metaslab's space map will have
3776 * ALLOCS followed by FREES (due to condensing) followed by ALLOCS
3777 * followed by FREES (due to space_map_write() in metaslab_sync()) for
3778 * sync pass 1.
e51be066 3779 */
ca577779
PD
3780 range_tree_t *tmp_tree = range_tree_create(NULL, type, NULL, start,
3781 shift);
3782 range_tree_add(tmp_tree, msp->ms_start, msp->ms_size);
3783 space_map_write(sm, tmp_tree, SM_ALLOC, SM_NO_VDEVID, tx);
93e28d66 3784 space_map_write(sm, msp->ms_allocatable, SM_FREE, SM_NO_VDEVID, tx);
ca577779 3785 space_map_write(sm, condense_tree, SM_FREE, SM_NO_VDEVID, tx);
93e28d66 3786
93cf2076
GW
3787 range_tree_vacate(condense_tree, NULL, NULL);
3788 range_tree_destroy(condense_tree);
ca577779
PD
3789 range_tree_vacate(tmp_tree, NULL, NULL);
3790 range_tree_destroy(tmp_tree);
a1d477c2 3791 mutex_enter(&msp->ms_lock);
93e28d66 3792
93cf2076 3793 msp->ms_condensing = B_FALSE;
93e28d66
SD
3794 metaslab_flush_update(msp, tx);
3795}
3796
93e28d66 3797static void
600a02b8 3798metaslab_unflushed_add(metaslab_t *msp, dmu_tx_t *tx)
93e28d66 3799{
600a02b8
AM
3800 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3801 ASSERT(spa_syncing_log_sm(spa) != NULL);
3802 ASSERT(msp->ms_sm != NULL);
93e28d66
SD
3803 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
3804 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
3805
600a02b8
AM
3806 mutex_enter(&spa->spa_flushed_ms_lock);
3807 metaslab_set_unflushed_txg(msp, spa_syncing_txg(spa), tx);
3808 metaslab_set_unflushed_dirty(msp, B_TRUE);
3809 avl_add(&spa->spa_metaslabs_by_flushed, msp);
3810 mutex_exit(&spa->spa_flushed_ms_lock);
93e28d66 3811
600a02b8
AM
3812 spa_log_sm_increment_current_mscount(spa);
3813 spa_log_summary_add_flushed_metaslab(spa, B_TRUE);
3814}
93e28d66 3815
600a02b8
AM
3816void
3817metaslab_unflushed_bump(metaslab_t *msp, dmu_tx_t *tx, boolean_t dirty)
3818{
3819 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
93e28d66
SD
3820 ASSERT(spa_syncing_log_sm(spa) != NULL);
3821 ASSERT(msp->ms_sm != NULL);
3822 ASSERT(metaslab_unflushed_txg(msp) != 0);
3823 ASSERT3P(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL), ==, msp);
600a02b8
AM
3824 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
3825 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
93e28d66
SD
3826
3827 VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(spa));
3828
3829 /* update metaslab's position in our flushing tree */
3830 uint64_t ms_prev_flushed_txg = metaslab_unflushed_txg(msp);
600a02b8 3831 boolean_t ms_prev_flushed_dirty = metaslab_unflushed_dirty(msp);
93e28d66
SD
3832 mutex_enter(&spa->spa_flushed_ms_lock);
3833 avl_remove(&spa->spa_metaslabs_by_flushed, msp);
3834 metaslab_set_unflushed_txg(msp, spa_syncing_txg(spa), tx);
600a02b8 3835 metaslab_set_unflushed_dirty(msp, dirty);
93e28d66
SD
3836 avl_add(&spa->spa_metaslabs_by_flushed, msp);
3837 mutex_exit(&spa->spa_flushed_ms_lock);
3838
3839 /* update metaslab counts of spa_log_sm_t nodes */
3840 spa_log_sm_decrement_mscount(spa, ms_prev_flushed_txg);
3841 spa_log_sm_increment_current_mscount(spa);
3842
600a02b8
AM
3843 /* update log space map summary */
3844 spa_log_summary_decrement_mscount(spa, ms_prev_flushed_txg,
3845 ms_prev_flushed_dirty);
3846 spa_log_summary_add_flushed_metaslab(spa, dirty);
3847
93e28d66 3848 /* cleanup obsolete logs if any */
93e28d66 3849 spa_cleanup_old_sm_logs(spa, tx);
600a02b8 3850}
93e28d66 3851
600a02b8
AM
3852/*
3853 * Called when the metaslab has been flushed (its own spacemap now reflects
3854 * all the contents of the pool-wide spacemap log). Updates the metaslab's
3855 * metadata and any pool-wide related log space map data (e.g. summary,
3856 * obsolete logs, etc..) to reflect that.
3857 */
3858static void
3859metaslab_flush_update(metaslab_t *msp, dmu_tx_t *tx)
3860{
3861 metaslab_group_t *mg = msp->ms_group;
3862 spa_t *spa = mg->mg_vd->vdev_spa;
3863
3864 ASSERT(MUTEX_HELD(&msp->ms_lock));
3865
3866 ASSERT3U(spa_sync_pass(spa), ==, 1);
3867
3868 /*
3869 * Just because a metaslab got flushed, that doesn't mean that
3870 * it will pass through metaslab_sync_done(). Thus, make sure to
3871 * update ms_synced_length here in case it doesn't.
3872 */
3873 msp->ms_synced_length = space_map_length(msp->ms_sm);
3874
3875 /*
3876 * We may end up here from metaslab_condense() without the
3877 * feature being active. In that case this is a no-op.
3878 */
3879 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP) ||
3880 metaslab_unflushed_txg(msp) == 0)
3881 return;
3882
3883 metaslab_unflushed_bump(msp, tx, B_FALSE);
93e28d66
SD
3884}
3885
3886boolean_t
3887metaslab_flush(metaslab_t *msp, dmu_tx_t *tx)
3888{
3889 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3890
3891 ASSERT(MUTEX_HELD(&msp->ms_lock));
3892 ASSERT3U(spa_sync_pass(spa), ==, 1);
3893 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
3894
3895 ASSERT(msp->ms_sm != NULL);
3896 ASSERT(metaslab_unflushed_txg(msp) != 0);
3897 ASSERT(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL) != NULL);
3898
3899 /*
3900 * There is nothing wrong with flushing the same metaslab twice, as
3901 * this codepath should work on that case. However, the current
3902 * flushing scheme makes sure to avoid this situation as we would be
3903 * making all these calls without having anything meaningful to write
3904 * to disk. We assert this behavior here.
3905 */
3906 ASSERT3U(metaslab_unflushed_txg(msp), <, dmu_tx_get_txg(tx));
3907
3908 /*
3909 * We can not flush while loading, because then we would
3910 * not load the ms_unflushed_{allocs,frees}.
3911 */
3912 if (msp->ms_loading)
3913 return (B_FALSE);
3914
3915 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3916 metaslab_verify_weight_and_frag(msp);
3917
3918 /*
3919 * Metaslab condensing is effectively flushing. Therefore if the
3920 * metaslab can be condensed we can just condense it instead of
3921 * flushing it.
3922 *
3923 * Note that metaslab_condense() does call metaslab_flush_update()
3924 * so we can just return immediately after condensing. We also
3925 * don't need to care about setting ms_flushing or broadcasting
3926 * ms_flush_cv, even if we temporarily drop the ms_lock in
3927 * metaslab_condense(), as the metaslab is already loaded.
3928 */
3929 if (msp->ms_loaded && metaslab_should_condense(msp)) {
3930 metaslab_group_t *mg = msp->ms_group;
3931
3932 /*
3933 * For all histogram operations below refer to the
3934 * comments of metaslab_sync() where we follow a
3935 * similar procedure.
3936 */
3937 metaslab_group_histogram_verify(mg);
3938 metaslab_class_histogram_verify(mg->mg_class);
3939 metaslab_group_histogram_remove(mg, msp);
3940
3941 metaslab_condense(msp, tx);
3942
3943 space_map_histogram_clear(msp->ms_sm);
3944 space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
3945 ASSERT(range_tree_is_empty(msp->ms_freed));
3946 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3947 space_map_histogram_add(msp->ms_sm,
3948 msp->ms_defer[t], tx);
3949 }
3950 metaslab_aux_histograms_update(msp);
3951
3952 metaslab_group_histogram_add(mg, msp);
3953 metaslab_group_histogram_verify(mg);
3954 metaslab_class_histogram_verify(mg->mg_class);
3955
3956 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3957
3958 /*
3959 * Since we recreated the histogram (and potentially
3960 * the ms_sm too while condensing) ensure that the
3961 * weight is updated too because we are not guaranteed
3962 * that this metaslab is dirty and will go through
3963 * metaslab_sync_done().
3964 */
3965 metaslab_recalculate_weight_and_sort(msp);
3966 return (B_TRUE);
3967 }
3968
3969 msp->ms_flushing = B_TRUE;
3970 uint64_t sm_len_before = space_map_length(msp->ms_sm);
3971
3972 mutex_exit(&msp->ms_lock);
3973 space_map_write(msp->ms_sm, msp->ms_unflushed_allocs, SM_ALLOC,
3974 SM_NO_VDEVID, tx);
3975 space_map_write(msp->ms_sm, msp->ms_unflushed_frees, SM_FREE,
3976 SM_NO_VDEVID, tx);
3977 mutex_enter(&msp->ms_lock);
3978
3979 uint64_t sm_len_after = space_map_length(msp->ms_sm);
3980 if (zfs_flags & ZFS_DEBUG_LOG_SPACEMAP) {
3981 zfs_dbgmsg("flushing: txg %llu, spa %s, vdev_id %llu, "
3982 "ms_id %llu, unflushed_allocs %llu, unflushed_frees %llu, "
8e739b2c
RE
3983 "appended %llu bytes", (u_longlong_t)dmu_tx_get_txg(tx),
3984 spa_name(spa),
3985 (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
3986 (u_longlong_t)msp->ms_id,
3987 (u_longlong_t)range_tree_space(msp->ms_unflushed_allocs),
3988 (u_longlong_t)range_tree_space(msp->ms_unflushed_frees),
3989 (u_longlong_t)(sm_len_after - sm_len_before));
93e28d66
SD
3990 }
3991
3992 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
3993 metaslab_unflushed_changes_memused(msp));
3994 spa->spa_unflushed_stats.sus_memused -=
3995 metaslab_unflushed_changes_memused(msp);
3996 range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
3997 range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
3998
3999 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
4000 metaslab_verify_weight_and_frag(msp);
4001
4002 metaslab_flush_update(msp, tx);
4003
4004 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
4005 metaslab_verify_weight_and_frag(msp);
4006
4007 msp->ms_flushing = B_FALSE;
4008 cv_broadcast(&msp->ms_flush_cv);
4009 return (B_TRUE);
e51be066
GW
4010}
4011
34dc7c2f
BB
4012/*
4013 * Write a metaslab to disk in the context of the specified transaction group.
4014 */
4015void
4016metaslab_sync(metaslab_t *msp, uint64_t txg)
4017{
93cf2076
GW
4018 metaslab_group_t *mg = msp->ms_group;
4019 vdev_t *vd = mg->mg_vd;
34dc7c2f 4020 spa_t *spa = vd->vdev_spa;
428870ff 4021 objset_t *mos = spa_meta_objset(spa);
d2734cce 4022 range_tree_t *alloctree = msp->ms_allocating[txg & TXG_MASK];
34dc7c2f 4023 dmu_tx_t *tx;
34dc7c2f 4024
428870ff
BB
4025 ASSERT(!vd->vdev_ishole);
4026
e51be066
GW
4027 /*
4028 * This metaslab has just been added so there's no work to do now.
4029 */
793c958f
SD
4030 if (msp->ms_new) {
4031 ASSERT0(range_tree_space(alloctree));
4032 ASSERT0(range_tree_space(msp->ms_freeing));
4033 ASSERT0(range_tree_space(msp->ms_freed));
4034 ASSERT0(range_tree_space(msp->ms_checkpointing));
4035 ASSERT0(range_tree_space(msp->ms_trim));
e51be066
GW
4036 return;
4037 }
4038
f3a7f661 4039 /*
d2734cce
SD
4040 * Normally, we don't want to process a metaslab if there are no
4041 * allocations or frees to perform. However, if the metaslab is being
475aa97c
PD
4042 * forced to condense, it's loaded and we're not beyond the final
4043 * dirty txg, we need to let it through. Not condensing beyond the
4044 * final dirty txg prevents an issue where metaslabs that need to be
4045 * condensed but were loaded for other reasons could cause a panic
4046 * here. By only checking the txg in that branch of the conditional,
4047 * we preserve the utility of the VERIFY statements in all other
4048 * cases.
f3a7f661 4049 */
d2734cce
SD
4050 if (range_tree_is_empty(alloctree) &&
4051 range_tree_is_empty(msp->ms_freeing) &&
4052 range_tree_is_empty(msp->ms_checkpointing) &&
475aa97c
PD
4053 !(msp->ms_loaded && msp->ms_condense_wanted &&
4054 txg <= spa_final_dirty_txg(spa)))
428870ff 4055 return;
34dc7c2f 4056
3b7f360c 4057
ca577779 4058 VERIFY3U(txg, <=, spa_final_dirty_txg(spa));
3b7f360c 4059
34dc7c2f 4060 /*
425d3237
SD
4061 * The only state that can actually be changing concurrently
4062 * with metaslab_sync() is the metaslab's ms_allocatable. No
4063 * other thread can be modifying this txg's alloc, freeing,
d2734cce 4064 * freed, or space_map_phys_t. We drop ms_lock whenever we
425d3237
SD
4065 * could call into the DMU, because the DMU can call down to
4066 * us (e.g. via zio_free()) at any time.
a1d477c2
MA
4067 *
4068 * The spa_vdev_remove_thread() can be reading metaslab state
425d3237
SD
4069 * concurrently, and it is locked out by the ms_sync_lock.
4070 * Note that the ms_lock is insufficient for this, because it
4071 * is dropped by space_map_write().
34dc7c2f 4072 */
428870ff 4073 tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
34dc7c2f 4074
93e28d66
SD
4075 /*
4076 * Generate a log space map if one doesn't exist already.
4077 */
4078 spa_generate_syncing_log_sm(spa, tx);
93cf2076 4079
93e28d66
SD
4080 if (msp->ms_sm == NULL) {
4081 uint64_t new_object = space_map_alloc(mos,
4082 spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP) ?
4083 zfs_metaslab_sm_blksz_with_log :
4084 zfs_metaslab_sm_blksz_no_log, tx);
93cf2076
GW
4085 VERIFY3U(new_object, !=, 0);
4086
93e28d66
SD
4087 dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
4088 msp->ms_id, sizeof (uint64_t), &new_object, tx);
4089
93cf2076 4090 VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
a1d477c2 4091 msp->ms_start, msp->ms_size, vd->vdev_ashift));
93cf2076 4092 ASSERT(msp->ms_sm != NULL);
93e28d66
SD
4093
4094 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
4095 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
425d3237 4096 ASSERT0(metaslab_allocated_space(msp));
34dc7c2f
BB
4097 }
4098
d2734cce
SD
4099 if (!range_tree_is_empty(msp->ms_checkpointing) &&
4100 vd->vdev_checkpoint_sm == NULL) {
4101 ASSERT(spa_has_checkpoint(spa));
4102
4103 uint64_t new_object = space_map_alloc(mos,
93e28d66 4104 zfs_vdev_standard_sm_blksz, tx);
d2734cce
SD
4105 VERIFY3U(new_object, !=, 0);
4106
4107 VERIFY0(space_map_open(&vd->vdev_checkpoint_sm,
4108 mos, new_object, 0, vd->vdev_asize, vd->vdev_ashift));
4109 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
4110
4111 /*
4112 * We save the space map object as an entry in vdev_top_zap
4113 * so it can be retrieved when the pool is reopened after an
4114 * export or through zdb.
4115 */
4116 VERIFY0(zap_add(vd->vdev_spa->spa_meta_objset,
4117 vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
4118 sizeof (new_object), 1, &new_object, tx));
4119 }
4120
a1d477c2 4121 mutex_enter(&msp->ms_sync_lock);
428870ff
BB
4122 mutex_enter(&msp->ms_lock);
4123
96358617 4124 /*
4e21fd06
DB
4125 * Note: metaslab_condense() clears the space map's histogram.
4126 * Therefore we must verify and remove this histogram before
96358617
MA
4127 * condensing.
4128 */
4129 metaslab_group_histogram_verify(mg);
4130 metaslab_class_histogram_verify(mg->mg_class);
4131 metaslab_group_histogram_remove(mg, msp);
4132
93e28d66
SD
4133 if (spa->spa_sync_pass == 1 && msp->ms_loaded &&
4134 metaslab_should_condense(msp))
4135 metaslab_condense(msp, tx);
4136
4137 /*
4138 * We'll be going to disk to sync our space accounting, thus we
4139 * drop the ms_lock during that time so allocations coming from
4140 * open-context (ZIL) for future TXGs do not block.
4141 */
4142 mutex_exit(&msp->ms_lock);
4143 space_map_t *log_sm = spa_syncing_log_sm(spa);
4144 if (log_sm != NULL) {
4145 ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP));
600a02b8
AM
4146 if (metaslab_unflushed_txg(msp) == 0)
4147 metaslab_unflushed_add(msp, tx);
4148 else if (!metaslab_unflushed_dirty(msp))
4149 metaslab_unflushed_bump(msp, tx, B_TRUE);
93e28d66
SD
4150
4151 space_map_write(log_sm, alloctree, SM_ALLOC,
4152 vd->vdev_id, tx);
4153 space_map_write(log_sm, msp->ms_freeing, SM_FREE,
4154 vd->vdev_id, tx);
4155 mutex_enter(&msp->ms_lock);
4156
4157 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
4158 metaslab_unflushed_changes_memused(msp));
4159 spa->spa_unflushed_stats.sus_memused -=
4160 metaslab_unflushed_changes_memused(msp);
4161 range_tree_remove_xor_add(alloctree,
4162 msp->ms_unflushed_frees, msp->ms_unflushed_allocs);
4163 range_tree_remove_xor_add(msp->ms_freeing,
4164 msp->ms_unflushed_allocs, msp->ms_unflushed_frees);
4165 spa->spa_unflushed_stats.sus_memused +=
4166 metaslab_unflushed_changes_memused(msp);
e51be066 4167 } else {
93e28d66
SD
4168 ASSERT(!spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP));
4169
4d044c4c
SD
4170 space_map_write(msp->ms_sm, alloctree, SM_ALLOC,
4171 SM_NO_VDEVID, tx);
4172 space_map_write(msp->ms_sm, msp->ms_freeing, SM_FREE,
4173 SM_NO_VDEVID, tx);
a1d477c2 4174 mutex_enter(&msp->ms_lock);
e51be066 4175 }
428870ff 4176
425d3237
SD
4177 msp->ms_allocated_space += range_tree_space(alloctree);
4178 ASSERT3U(msp->ms_allocated_space, >=,
4179 range_tree_space(msp->ms_freeing));
4180 msp->ms_allocated_space -= range_tree_space(msp->ms_freeing);
4181
d2734cce
SD
4182 if (!range_tree_is_empty(msp->ms_checkpointing)) {
4183 ASSERT(spa_has_checkpoint(spa));
4184 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
4185
4186 /*
4187 * Since we are doing writes to disk and the ms_checkpointing
4188 * tree won't be changing during that time, we drop the
93e28d66
SD
4189 * ms_lock while writing to the checkpoint space map, for the
4190 * same reason mentioned above.
d2734cce
SD
4191 */
4192 mutex_exit(&msp->ms_lock);
4193 space_map_write(vd->vdev_checkpoint_sm,
4d044c4c 4194 msp->ms_checkpointing, SM_FREE, SM_NO_VDEVID, tx);
d2734cce 4195 mutex_enter(&msp->ms_lock);
d2734cce
SD
4196
4197 spa->spa_checkpoint_info.sci_dspace +=
4198 range_tree_space(msp->ms_checkpointing);
4199 vd->vdev_stat.vs_checkpoint_space +=
4200 range_tree_space(msp->ms_checkpointing);
4201 ASSERT3U(vd->vdev_stat.vs_checkpoint_space, ==,
425d3237 4202 -space_map_allocated(vd->vdev_checkpoint_sm));
d2734cce
SD
4203
4204 range_tree_vacate(msp->ms_checkpointing, NULL, NULL);
4205 }
4206
93cf2076
GW
4207 if (msp->ms_loaded) {
4208 /*
a1d477c2 4209 * When the space map is loaded, we have an accurate
93cf2076
GW
4210 * histogram in the range tree. This gives us an opportunity
4211 * to bring the space map's histogram up-to-date so we clear
4212 * it first before updating it.
4213 */
4214 space_map_histogram_clear(msp->ms_sm);
d2734cce 4215 space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
4e21fd06
DB
4216
4217 /*
4218 * Since we've cleared the histogram we need to add back
4219 * any free space that has already been processed, plus
4220 * any deferred space. This allows the on-disk histogram
4221 * to accurately reflect all free space even if some space
4222 * is not yet available for allocation (i.e. deferred).
4223 */
d2734cce 4224 space_map_histogram_add(msp->ms_sm, msp->ms_freed, tx);
4e21fd06 4225
93cf2076 4226 /*
4e21fd06
DB
4227 * Add back any deferred free space that has not been
4228 * added back into the in-core free tree yet. This will
4229 * ensure that we don't end up with a space map histogram
4230 * that is completely empty unless the metaslab is fully
4231 * allocated.
93cf2076 4232 */
1c27024e 4233 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
4e21fd06 4234 space_map_histogram_add(msp->ms_sm,
d2734cce 4235 msp->ms_defer[t], tx);
4e21fd06 4236 }
93cf2076 4237 }
4e21fd06
DB
4238
4239 /*
4240 * Always add the free space from this sync pass to the space
4241 * map histogram. We want to make sure that the on-disk histogram
4242 * accounts for all free space. If the space map is not loaded,
4243 * then we will lose some accuracy but will correct it the next
4244 * time we load the space map.
4245 */
d2734cce 4246 space_map_histogram_add(msp->ms_sm, msp->ms_freeing, tx);
928e8ad4 4247 metaslab_aux_histograms_update(msp);
4e21fd06 4248
f3a7f661
GW
4249 metaslab_group_histogram_add(mg, msp);
4250 metaslab_group_histogram_verify(mg);
4251 metaslab_class_histogram_verify(mg->mg_class);
34dc7c2f 4252
e51be066 4253 /*
93cf2076 4254 * For sync pass 1, we avoid traversing this txg's free range tree
425d3237
SD
4255 * and instead will just swap the pointers for freeing and freed.
4256 * We can safely do this since the freed_tree is guaranteed to be
4257 * empty on the initial pass.
93e28d66
SD
4258 *
4259 * Keep in mind that even if we are currently using a log spacemap
4260 * we want current frees to end up in the ms_allocatable (but not
4261 * get appended to the ms_sm) so their ranges can be reused as usual.
e51be066
GW
4262 */
4263 if (spa_sync_pass(spa) == 1) {
d2734cce 4264 range_tree_swap(&msp->ms_freeing, &msp->ms_freed);
425d3237 4265 ASSERT0(msp->ms_allocated_this_txg);
e51be066 4266 } else {
d2734cce
SD
4267 range_tree_vacate(msp->ms_freeing,
4268 range_tree_add, msp->ms_freed);
34dc7c2f 4269 }
425d3237 4270 msp->ms_allocated_this_txg += range_tree_space(alloctree);
f3a7f661 4271 range_tree_vacate(alloctree, NULL, NULL);
34dc7c2f 4272
d2734cce
SD
4273 ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
4274 ASSERT0(range_tree_space(msp->ms_allocating[TXG_CLEAN(txg)
4275 & TXG_MASK]));
4276 ASSERT0(range_tree_space(msp->ms_freeing));
4277 ASSERT0(range_tree_space(msp->ms_checkpointing));
34dc7c2f
BB
4278
4279 mutex_exit(&msp->ms_lock);
4280
93e28d66
SD
4281 /*
4282 * Verify that the space map object ID has been recorded in the
4283 * vdev_ms_array.
4284 */
4285 uint64_t object;
4286 VERIFY0(dmu_read(mos, vd->vdev_ms_array,
4287 msp->ms_id * sizeof (uint64_t), sizeof (uint64_t), &object, 0));
4288 VERIFY3U(object, ==, space_map_object(msp->ms_sm));
4289
a1d477c2 4290 mutex_exit(&msp->ms_sync_lock);
34dc7c2f
BB
4291 dmu_tx_commit(tx);
4292}
4293
f09fda50
PD
4294static void
4295metaslab_evict(metaslab_t *msp, uint64_t txg)
893a6d62 4296{
f09fda50
PD
4297 if (!msp->ms_loaded || msp->ms_disabled != 0)
4298 return;
893a6d62 4299
f09fda50
PD
4300 for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
4301 VERIFY0(range_tree_space(
4302 msp->ms_allocating[(txg + t) & TXG_MASK]));
893a6d62 4303 }
f09fda50
PD
4304 if (msp->ms_allocator != -1)
4305 metaslab_passivate(msp, msp->ms_weight & ~METASLAB_ACTIVE_MASK);
4306
4307 if (!metaslab_debug_unload)
4308 metaslab_unload(msp);
893a6d62
PD
4309}
4310
34dc7c2f
BB
4311/*
4312 * Called after a transaction group has completely synced to mark
4313 * all of the metaslab's free space as usable.
4314 */
4315void
4316metaslab_sync_done(metaslab_t *msp, uint64_t txg)
4317{
34dc7c2f
BB
4318 metaslab_group_t *mg = msp->ms_group;
4319 vdev_t *vd = mg->mg_vd;
4e21fd06 4320 spa_t *spa = vd->vdev_spa;
93cf2076 4321 range_tree_t **defer_tree;
428870ff 4322 int64_t alloc_delta, defer_delta;
4e21fd06 4323 boolean_t defer_allowed = B_TRUE;
428870ff
BB
4324
4325 ASSERT(!vd->vdev_ishole);
34dc7c2f
BB
4326
4327 mutex_enter(&msp->ms_lock);
4328
793c958f
SD
4329 if (msp->ms_new) {
4330 /* this is a new metaslab, add its capacity to the vdev */
cc99f275 4331 metaslab_space_update(vd, mg->mg_class, 0, 0, msp->ms_size);
793c958f
SD
4332
4333 /* there should be no allocations nor frees at this point */
4334 VERIFY0(msp->ms_allocated_this_txg);
4335 VERIFY0(range_tree_space(msp->ms_freed));
34dc7c2f 4336 }
793c958f 4337
d2734cce
SD
4338 ASSERT0(range_tree_space(msp->ms_freeing));
4339 ASSERT0(range_tree_space(msp->ms_checkpointing));
34dc7c2f 4340
d2734cce 4341 defer_tree = &msp->ms_defer[txg % TXG_DEFER_SIZE];
93cf2076 4342
1c27024e 4343 uint64_t free_space = metaslab_class_get_space(spa_normal_class(spa)) -
4e21fd06 4344 metaslab_class_get_alloc(spa_normal_class(spa));
5caeef02
DB
4345 if (free_space <= spa_get_slop_space(spa) || vd->vdev_removing ||
4346 vd->vdev_rz_expanding) {
4e21fd06
DB
4347 defer_allowed = B_FALSE;
4348 }
4349
4350 defer_delta = 0;
425d3237
SD
4351 alloc_delta = msp->ms_allocated_this_txg -
4352 range_tree_space(msp->ms_freed);
93e28d66 4353
4e21fd06 4354 if (defer_allowed) {
d2734cce 4355 defer_delta = range_tree_space(msp->ms_freed) -
4e21fd06
DB
4356 range_tree_space(*defer_tree);
4357 } else {
4358 defer_delta -= range_tree_space(*defer_tree);
4359 }
cc99f275
DB
4360 metaslab_space_update(vd, mg->mg_class, alloc_delta + defer_delta,
4361 defer_delta, 0);
34dc7c2f 4362
93e28d66
SD
4363 if (spa_syncing_log_sm(spa) == NULL) {
4364 /*
4365 * If there's a metaslab_load() in progress and we don't have
4366 * a log space map, it means that we probably wrote to the
4367 * metaslab's space map. If this is the case, we need to
4368 * make sure that we wait for the load to complete so that we
4369 * have a consistent view at the in-core side of the metaslab.
4370 */
4371 metaslab_load_wait(msp);
4372 } else {
4373 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
4374 }
c2e42f9d 4375
1b939560
BB
4376 /*
4377 * When auto-trimming is enabled, free ranges which are added to
4378 * ms_allocatable are also be added to ms_trim. The ms_trim tree is
4379 * periodically consumed by the vdev_autotrim_thread() which issues
4380 * trims for all ranges and then vacates the tree. The ms_trim tree
4381 * can be discarded at any time with the sole consequence of recent
4382 * frees not being trimmed.
4383 */
4384 if (spa_get_autotrim(spa) == SPA_AUTOTRIM_ON) {
4385 range_tree_walk(*defer_tree, range_tree_add, msp->ms_trim);
4386 if (!defer_allowed) {
4387 range_tree_walk(msp->ms_freed, range_tree_add,
4388 msp->ms_trim);
4389 }
4390 } else {
4391 range_tree_vacate(msp->ms_trim, NULL, NULL);
4392 }
4393
c2e42f9d 4394 /*
93cf2076 4395 * Move the frees from the defer_tree back to the free
d2734cce
SD
4396 * range tree (if it's loaded). Swap the freed_tree and
4397 * the defer_tree -- this is safe to do because we've
4398 * just emptied out the defer_tree.
c2e42f9d 4399 */
93cf2076 4400 range_tree_vacate(*defer_tree,
d2734cce 4401 msp->ms_loaded ? range_tree_add : NULL, msp->ms_allocatable);
4e21fd06 4402 if (defer_allowed) {
d2734cce 4403 range_tree_swap(&msp->ms_freed, defer_tree);
4e21fd06 4404 } else {
d2734cce
SD
4405 range_tree_vacate(msp->ms_freed,
4406 msp->ms_loaded ? range_tree_add : NULL,
4407 msp->ms_allocatable);
4e21fd06 4408 }
425d3237
SD
4409
4410 msp->ms_synced_length = space_map_length(msp->ms_sm);
34dc7c2f 4411
428870ff
BB
4412 msp->ms_deferspace += defer_delta;
4413 ASSERT3S(msp->ms_deferspace, >=, 0);
93cf2076 4414 ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
428870ff
BB
4415 if (msp->ms_deferspace != 0) {
4416 /*
4417 * Keep syncing this metaslab until all deferred frees
4418 * are back in circulation.
4419 */
4420 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
4421 }
928e8ad4 4422 metaslab_aux_histograms_update_done(msp, defer_allowed);
428870ff 4423
492f64e9
PD
4424 if (msp->ms_new) {
4425 msp->ms_new = B_FALSE;
4426 mutex_enter(&mg->mg_lock);
4427 mg->mg_ms_ready++;
4428 mutex_exit(&mg->mg_lock);
4429 }
928e8ad4 4430
4e21fd06 4431 /*
928e8ad4
SD
4432 * Re-sort metaslab within its group now that we've adjusted
4433 * its allocatable space.
4e21fd06 4434 */
928e8ad4 4435 metaslab_recalculate_weight_and_sort(msp);
4e21fd06 4436
d2734cce
SD
4437 ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
4438 ASSERT0(range_tree_space(msp->ms_freeing));
4439 ASSERT0(range_tree_space(msp->ms_freed));
4440 ASSERT0(range_tree_space(msp->ms_checkpointing));
f09fda50 4441 msp->ms_allocating_total -= msp->ms_allocated_this_txg;
425d3237 4442 msp->ms_allocated_this_txg = 0;
34dc7c2f
BB
4443 mutex_exit(&msp->ms_lock);
4444}
4445
428870ff
BB
4446void
4447metaslab_sync_reassess(metaslab_group_t *mg)
4448{
a1d477c2
MA
4449 spa_t *spa = mg->mg_class->mc_spa;
4450
4451 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
1be627f5 4452 metaslab_group_alloc_update(mg);
f3a7f661 4453 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
6d974228 4454
428870ff 4455 /*
a1d477c2
MA
4456 * Preload the next potential metaslabs but only on active
4457 * metaslab groups. We can get into a state where the metaslab
4458 * is no longer active since we dirty metaslabs as we remove a
4459 * a device, thus potentially making the metaslab group eligible
4460 * for preloading.
428870ff 4461 */
a1d477c2
MA
4462 if (mg->mg_activation_count > 0) {
4463 metaslab_group_preload(mg);
4464 }
4465 spa_config_exit(spa, SCL_ALLOC, FTAG);
428870ff
BB
4466}
4467
cc99f275
DB
4468/*
4469 * When writing a ditto block (i.e. more than one DVA for a given BP) on
4470 * the same vdev as an existing DVA of this BP, then try to allocate it
4471 * on a different metaslab than existing DVAs (i.e. a unique metaslab).
4472 */
4473static boolean_t
4474metaslab_is_unique(metaslab_t *msp, dva_t *dva)
34dc7c2f 4475{
cc99f275
DB
4476 uint64_t dva_ms_id;
4477
4478 if (DVA_GET_ASIZE(dva) == 0)
4479 return (B_TRUE);
34dc7c2f
BB
4480
4481 if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
cc99f275 4482 return (B_TRUE);
34dc7c2f 4483
cc99f275
DB
4484 dva_ms_id = DVA_GET_OFFSET(dva) >> msp->ms_group->mg_vd->vdev_ms_shift;
4485
4486 return (msp->ms_id != dva_ms_id);
34dc7c2f
BB
4487}
4488
4e21fd06
DB
4489/*
4490 * ==========================================================================
4491 * Metaslab allocation tracing facility
4492 * ==========================================================================
4493 */
4e21fd06
DB
4494
4495/*
4496 * Add an allocation trace element to the allocation tracing list.
4497 */
4498static void
4499metaslab_trace_add(zio_alloc_list_t *zal, metaslab_group_t *mg,
492f64e9
PD
4500 metaslab_t *msp, uint64_t psize, uint32_t dva_id, uint64_t offset,
4501 int allocator)
4e21fd06
DB
4502{
4503 metaslab_alloc_trace_t *mat;
4504
4505 if (!metaslab_trace_enabled)
4506 return;
4507
4508 /*
4509 * When the tracing list reaches its maximum we remove
4510 * the second element in the list before adding a new one.
4511 * By removing the second element we preserve the original
4512 * entry as a clue to what allocations steps have already been
4513 * performed.
4514 */
4515 if (zal->zal_size == metaslab_trace_max_entries) {
4516 metaslab_alloc_trace_t *mat_next;
6d8da841 4517#ifdef ZFS_DEBUG
4e21fd06
DB
4518 panic("too many entries in allocation list");
4519#endif
ca577779 4520 METASLABSTAT_BUMP(metaslabstat_trace_over_limit);
4e21fd06
DB
4521 zal->zal_size--;
4522 mat_next = list_next(&zal->zal_list, list_head(&zal->zal_list));
4523 list_remove(&zal->zal_list, mat_next);
4524 kmem_cache_free(metaslab_alloc_trace_cache, mat_next);
4525 }
4526
4527 mat = kmem_cache_alloc(metaslab_alloc_trace_cache, KM_SLEEP);
4528 list_link_init(&mat->mat_list_node);
4529 mat->mat_mg = mg;
4530 mat->mat_msp = msp;
4531 mat->mat_size = psize;
4532 mat->mat_dva_id = dva_id;
4533 mat->mat_offset = offset;
4534 mat->mat_weight = 0;
492f64e9 4535 mat->mat_allocator = allocator;
4e21fd06
DB
4536
4537 if (msp != NULL)
4538 mat->mat_weight = msp->ms_weight;
4539
4540 /*
4541 * The list is part of the zio so locking is not required. Only
4542 * a single thread will perform allocations for a given zio.
4543 */
4544 list_insert_tail(&zal->zal_list, mat);
4545 zal->zal_size++;
4546
4547 ASSERT3U(zal->zal_size, <=, metaslab_trace_max_entries);
4548}
4549
4550void
4551metaslab_trace_init(zio_alloc_list_t *zal)
4552{
4553 list_create(&zal->zal_list, sizeof (metaslab_alloc_trace_t),
4554 offsetof(metaslab_alloc_trace_t, mat_list_node));
4555 zal->zal_size = 0;
4556}
4557
4558void
4559metaslab_trace_fini(zio_alloc_list_t *zal)
4560{
4561 metaslab_alloc_trace_t *mat;
4562
4563 while ((mat = list_remove_head(&zal->zal_list)) != NULL)
4564 kmem_cache_free(metaslab_alloc_trace_cache, mat);
4565 list_destroy(&zal->zal_list);
4566 zal->zal_size = 0;
4567}
4e21fd06 4568
3dfb57a3
DB
4569/*
4570 * ==========================================================================
4571 * Metaslab block operations
4572 * ==========================================================================
4573 */
4574
4575static void
dd66857d
AZ
4576metaslab_group_alloc_increment(spa_t *spa, uint64_t vdev, const void *tag,
4577 int flags, int allocator)
3dfb57a3 4578{
3dfb57a3 4579 if (!(flags & METASLAB_ASYNC_ALLOC) ||
492f64e9 4580 (flags & METASLAB_DONT_THROTTLE))
3dfb57a3
DB
4581 return;
4582
1c27024e 4583 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
3dfb57a3
DB
4584 if (!mg->mg_class->mc_alloc_throttle_enabled)
4585 return;
4586
32d805c3
MA
4587 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4588 (void) zfs_refcount_add(&mga->mga_alloc_queue_depth, tag);
492f64e9
PD
4589}
4590
4591static void
4592metaslab_group_increment_qdepth(metaslab_group_t *mg, int allocator)
4593{
32d805c3 4594 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
f8020c93
AM
4595 metaslab_class_allocator_t *mca =
4596 &mg->mg_class->mc_allocator[allocator];
492f64e9 4597 uint64_t max = mg->mg_max_alloc_queue_depth;
32d805c3 4598 uint64_t cur = mga->mga_cur_max_alloc_queue_depth;
492f64e9 4599 while (cur < max) {
32d805c3 4600 if (atomic_cas_64(&mga->mga_cur_max_alloc_queue_depth,
492f64e9 4601 cur, cur + 1) == cur) {
f8020c93 4602 atomic_inc_64(&mca->mca_alloc_max_slots);
492f64e9
PD
4603 return;
4604 }
32d805c3 4605 cur = mga->mga_cur_max_alloc_queue_depth;
492f64e9 4606 }
3dfb57a3
DB
4607}
4608
4609void
dd66857d
AZ
4610metaslab_group_alloc_decrement(spa_t *spa, uint64_t vdev, const void *tag,
4611 int flags, int allocator, boolean_t io_complete)
3dfb57a3 4612{
3dfb57a3 4613 if (!(flags & METASLAB_ASYNC_ALLOC) ||
492f64e9 4614 (flags & METASLAB_DONT_THROTTLE))
3dfb57a3
DB
4615 return;
4616
1c27024e 4617 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
3dfb57a3
DB
4618 if (!mg->mg_class->mc_alloc_throttle_enabled)
4619 return;
4620
32d805c3
MA
4621 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4622 (void) zfs_refcount_remove(&mga->mga_alloc_queue_depth, tag);
492f64e9
PD
4623 if (io_complete)
4624 metaslab_group_increment_qdepth(mg, allocator);
3dfb57a3
DB
4625}
4626
4627void
dd66857d 4628metaslab_group_alloc_verify(spa_t *spa, const blkptr_t *bp, const void *tag,
492f64e9 4629 int allocator)
3dfb57a3
DB
4630{
4631#ifdef ZFS_DEBUG
4632 const dva_t *dva = bp->blk_dva;
4633 int ndvas = BP_GET_NDVAS(bp);
3dfb57a3 4634
1c27024e 4635 for (int d = 0; d < ndvas; d++) {
3dfb57a3
DB
4636 uint64_t vdev = DVA_GET_VDEV(&dva[d]);
4637 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
32d805c3
MA
4638 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4639 VERIFY(zfs_refcount_not_held(&mga->mga_alloc_queue_depth, tag));
3dfb57a3
DB
4640 }
4641#endif
4642}
4643
34dc7c2f 4644static uint64_t
4e21fd06
DB
4645metaslab_block_alloc(metaslab_t *msp, uint64_t size, uint64_t txg)
4646{
4647 uint64_t start;
d2734cce 4648 range_tree_t *rt = msp->ms_allocatable;
4e21fd06
DB
4649 metaslab_class_t *mc = msp->ms_group->mg_class;
4650
93e28d66 4651 ASSERT(MUTEX_HELD(&msp->ms_lock));
4e21fd06 4652 VERIFY(!msp->ms_condensing);
1b939560 4653 VERIFY0(msp->ms_disabled);
5caeef02 4654 VERIFY0(msp->ms_new);
4e21fd06
DB
4655
4656 start = mc->mc_ops->msop_alloc(msp, size);
4657 if (start != -1ULL) {
4658 metaslab_group_t *mg = msp->ms_group;
4659 vdev_t *vd = mg->mg_vd;
4660
4661 VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
4662 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
4663 VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
4664 range_tree_remove(rt, start, size);
1b939560 4665 range_tree_clear(msp->ms_trim, start, size);
4e21fd06 4666
d2734cce 4667 if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
4e21fd06
DB
4668 vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
4669
d2734cce 4670 range_tree_add(msp->ms_allocating[txg & TXG_MASK], start, size);
f09fda50 4671 msp->ms_allocating_total += size;
4e21fd06
DB
4672
4673 /* Track the last successful allocation */
4674 msp->ms_alloc_txg = txg;
4675 metaslab_verify_space(msp, txg);
4676 }
4677
4678 /*
4679 * Now that we've attempted the allocation we need to update the
4680 * metaslab's maximum block size since it may have changed.
4681 */
c81f1790 4682 msp->ms_max_size = metaslab_largest_allocatable(msp);
4e21fd06
DB
4683 return (start);
4684}
4685
492f64e9
PD
4686/*
4687 * Find the metaslab with the highest weight that is less than what we've
4688 * already tried. In the common case, this means that we will examine each
4689 * metaslab at most once. Note that concurrent callers could reorder metaslabs
4690 * by activation/passivation once we have dropped the mg_lock. If a metaslab is
4691 * activated by another thread, and we fail to allocate from the metaslab we
4692 * have selected, we may not try the newly-activated metaslab, and instead
4693 * activate another metaslab. This is not optimal, but generally does not cause
4694 * any problems (a possible exception being if every metaslab is completely full
e1cfd73f 4695 * except for the newly-activated metaslab which we fail to examine).
492f64e9
PD
4696 */
4697static metaslab_t *
4698find_valid_metaslab(metaslab_group_t *mg, uint64_t activation_weight,
cc99f275 4699 dva_t *dva, int d, boolean_t want_unique, uint64_t asize, int allocator,
c81f1790
PD
4700 boolean_t try_hard, zio_alloc_list_t *zal, metaslab_t *search,
4701 boolean_t *was_active)
492f64e9
PD
4702{
4703 avl_index_t idx;
4704 avl_tree_t *t = &mg->mg_metaslab_tree;
4705 metaslab_t *msp = avl_find(t, search, &idx);
4706 if (msp == NULL)
4707 msp = avl_nearest(t, idx, AVL_AFTER);
4708
fdc2d303 4709 uint_t tries = 0;
492f64e9
PD
4710 for (; msp != NULL; msp = AVL_NEXT(t, msp)) {
4711 int i;
be5c6d96
MA
4712
4713 if (!try_hard && tries > zfs_metaslab_find_max_tries) {
4714 METASLABSTAT_BUMP(metaslabstat_too_many_tries);
4715 return (NULL);
4716 }
4717 tries++;
4718
c81f1790 4719 if (!metaslab_should_allocate(msp, asize, try_hard)) {
492f64e9
PD
4720 metaslab_trace_add(zal, mg, msp, asize, d,
4721 TRACE_TOO_SMALL, allocator);
4722 continue;
4723 }
4724
4725 /*
5caeef02
DB
4726 * If the selected metaslab is condensing or disabled, or
4727 * hasn't gone through a metaslab_sync_done(), then skip it.
492f64e9 4728 */
5caeef02 4729 if (msp->ms_condensing || msp->ms_disabled > 0 || msp->ms_new)
492f64e9
PD
4730 continue;
4731
4732 *was_active = msp->ms_allocator != -1;
4733 /*
4734 * If we're activating as primary, this is our first allocation
4735 * from this disk, so we don't need to check how close we are.
4736 * If the metaslab under consideration was already active,
4737 * we're getting desperate enough to steal another allocator's
4738 * metaslab, so we still don't care about distances.
4739 */
4740 if (activation_weight == METASLAB_WEIGHT_PRIMARY || *was_active)
4741 break;
4742
492f64e9 4743 for (i = 0; i < d; i++) {
cc99f275
DB
4744 if (want_unique &&
4745 !metaslab_is_unique(msp, &dva[i]))
4746 break; /* try another metaslab */
492f64e9
PD
4747 }
4748 if (i == d)
4749 break;
4750 }
4751
4752 if (msp != NULL) {
4753 search->ms_weight = msp->ms_weight;
4754 search->ms_start = msp->ms_start + 1;
4755 search->ms_allocator = msp->ms_allocator;
4756 search->ms_primary = msp->ms_primary;
4757 }
4758 return (msp);
4759}
4760
65c7cc49 4761static void
679b0f2a
PD
4762metaslab_active_mask_verify(metaslab_t *msp)
4763{
4764 ASSERT(MUTEX_HELD(&msp->ms_lock));
4765
4766 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
4767 return;
4768
4769 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0)
4770 return;
4771
4772 if (msp->ms_weight & METASLAB_WEIGHT_PRIMARY) {
4773 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
4774 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_CLAIM);
4775 VERIFY3S(msp->ms_allocator, !=, -1);
4776 VERIFY(msp->ms_primary);
4777 return;
4778 }
4779
4780 if (msp->ms_weight & METASLAB_WEIGHT_SECONDARY) {
4781 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
4782 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_CLAIM);
4783 VERIFY3S(msp->ms_allocator, !=, -1);
4784 VERIFY(!msp->ms_primary);
4785 return;
4786 }
4787
4788 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
4789 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
4790 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
4791 VERIFY3S(msp->ms_allocator, ==, -1);
4792 return;
4793 }
4794}
4795
4e21fd06
DB
4796static uint64_t
4797metaslab_group_alloc_normal(metaslab_group_t *mg, zio_alloc_list_t *zal,
c81f1790
PD
4798 uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva, int d,
4799 int allocator, boolean_t try_hard)
34dc7c2f
BB
4800{
4801 metaslab_t *msp = NULL;
4802 uint64_t offset = -1ULL;
34dc7c2f 4803
679b0f2a 4804 uint64_t activation_weight = METASLAB_WEIGHT_PRIMARY;
492f64e9
PD
4805 for (int i = 0; i < d; i++) {
4806 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
4807 DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
34dc7c2f 4808 activation_weight = METASLAB_WEIGHT_SECONDARY;
492f64e9
PD
4809 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
4810 DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
e38afd34 4811 activation_weight = METASLAB_WEIGHT_CLAIM;
9babb374
BB
4812 break;
4813 }
4814 }
34dc7c2f 4815
492f64e9
PD
4816 /*
4817 * If we don't have enough metaslabs active to fill the entire array, we
4818 * just use the 0th slot.
4819 */
e38afd34 4820 if (mg->mg_ms_ready < mg->mg_allocators * 3)
492f64e9 4821 allocator = 0;
32d805c3 4822 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
492f64e9
PD
4823
4824 ASSERT3U(mg->mg_vd->vdev_ms_count, >=, 2);
4825
1c27024e 4826 metaslab_t *search = kmem_alloc(sizeof (*search), KM_SLEEP);
4e21fd06
DB
4827 search->ms_weight = UINT64_MAX;
4828 search->ms_start = 0;
492f64e9
PD
4829 /*
4830 * At the end of the metaslab tree are the already-active metaslabs,
4831 * first the primaries, then the secondaries. When we resume searching
4832 * through the tree, we need to consider ms_allocator and ms_primary so
4833 * we start in the location right after where we left off, and don't
4834 * accidentally loop forever considering the same metaslabs.
4835 */
4836 search->ms_allocator = -1;
4837 search->ms_primary = B_TRUE;
34dc7c2f 4838 for (;;) {
492f64e9 4839 boolean_t was_active = B_FALSE;
9babb374 4840
34dc7c2f 4841 mutex_enter(&mg->mg_lock);
4e21fd06 4842
492f64e9 4843 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
32d805c3
MA
4844 mga->mga_primary != NULL) {
4845 msp = mga->mga_primary;
679b0f2a
PD
4846
4847 /*
4848 * Even though we don't hold the ms_lock for the
4849 * primary metaslab, those fields should not
e1cfd73f 4850 * change while we hold the mg_lock. Thus it is
679b0f2a
PD
4851 * safe to make assertions on them.
4852 */
4853 ASSERT(msp->ms_primary);
4854 ASSERT3S(msp->ms_allocator, ==, allocator);
4855 ASSERT(msp->ms_loaded);
4856
492f64e9 4857 was_active = B_TRUE;
f09fda50 4858 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
492f64e9 4859 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
32d805c3
MA
4860 mga->mga_secondary != NULL) {
4861 msp = mga->mga_secondary;
679b0f2a
PD
4862
4863 /*
4864 * See comment above about the similar assertions
4865 * for the primary metaslab.
4866 */
4867 ASSERT(!msp->ms_primary);
4868 ASSERT3S(msp->ms_allocator, ==, allocator);
4869 ASSERT(msp->ms_loaded);
4870
492f64e9 4871 was_active = B_TRUE;
f09fda50 4872 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
492f64e9
PD
4873 } else {
4874 msp = find_valid_metaslab(mg, activation_weight, dva, d,
c81f1790
PD
4875 want_unique, asize, allocator, try_hard, zal,
4876 search, &was_active);
34dc7c2f 4877 }
492f64e9 4878
34dc7c2f 4879 mutex_exit(&mg->mg_lock);
4e21fd06
DB
4880 if (msp == NULL) {
4881 kmem_free(search, sizeof (*search));
34dc7c2f 4882 return (-1ULL);
4e21fd06 4883 }
ac72fac3 4884 mutex_enter(&msp->ms_lock);
679b0f2a
PD
4885
4886 metaslab_active_mask_verify(msp);
4887
4888 /*
4889 * This code is disabled out because of issues with
4890 * tracepoints in non-gpl kernel modules.
4891 */
4892#if 0
4893 DTRACE_PROBE3(ms__activation__attempt,
4894 metaslab_t *, msp, uint64_t, activation_weight,
4895 boolean_t, was_active);
4896#endif
4897
34dc7c2f
BB
4898 /*
4899 * Ensure that the metaslab we have selected is still
4900 * capable of handling our request. It's possible that
4901 * another thread may have changed the weight while we
4e21fd06 4902 * were blocked on the metaslab lock. We check the
f09fda50 4903 * active status first to see if we need to set_selected_txg
4e21fd06 4904 * a new metaslab.
34dc7c2f 4905 */
4e21fd06 4906 if (was_active && !(msp->ms_weight & METASLAB_ACTIVE_MASK)) {
679b0f2a 4907 ASSERT3S(msp->ms_allocator, ==, -1);
34dc7c2f
BB
4908 mutex_exit(&msp->ms_lock);
4909 continue;
4910 }
4911
492f64e9 4912 /*
679b0f2a
PD
4913 * If the metaslab was activated for another allocator
4914 * while we were waiting in the ms_lock above, or it's
4915 * a primary and we're seeking a secondary (or vice versa),
4916 * we go back and select a new metaslab.
492f64e9
PD
4917 */
4918 if (!was_active && (msp->ms_weight & METASLAB_ACTIVE_MASK) &&
4919 (msp->ms_allocator != -1) &&
4920 (msp->ms_allocator != allocator || ((activation_weight ==
4921 METASLAB_WEIGHT_PRIMARY) != msp->ms_primary))) {
679b0f2a
PD
4922 ASSERT(msp->ms_loaded);
4923 ASSERT((msp->ms_weight & METASLAB_WEIGHT_CLAIM) ||
4924 msp->ms_allocator != -1);
492f64e9
PD
4925 mutex_exit(&msp->ms_lock);
4926 continue;
4927 }
4928
679b0f2a
PD
4929 /*
4930 * This metaslab was used for claiming regions allocated
4931 * by the ZIL during pool import. Once these regions are
4932 * claimed we don't need to keep the CLAIM bit set
4933 * anymore. Passivate this metaslab to zero its activation
4934 * mask.
4935 */
e38afd34 4936 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM &&
4937 activation_weight != METASLAB_WEIGHT_CLAIM) {
679b0f2a
PD
4938 ASSERT(msp->ms_loaded);
4939 ASSERT3S(msp->ms_allocator, ==, -1);
492f64e9
PD
4940 metaslab_passivate(msp, msp->ms_weight &
4941 ~METASLAB_WEIGHT_CLAIM);
34dc7c2f
BB
4942 mutex_exit(&msp->ms_lock);
4943 continue;
4944 }
4945
f09fda50 4946 metaslab_set_selected_txg(msp, txg);
679b0f2a
PD
4947
4948 int activation_error =
4949 metaslab_activate(msp, allocator, activation_weight);
4950 metaslab_active_mask_verify(msp);
4951
4952 /*
4953 * If the metaslab was activated by another thread for
4954 * another allocator or activation_weight (EBUSY), or it
4955 * failed because another metaslab was assigned as primary
4956 * for this allocator (EEXIST) we continue using this
4957 * metaslab for our allocation, rather than going on to a
4958 * worse metaslab (we waited for that metaslab to be loaded
4959 * after all).
4960 *
fe0ea848
PD
4961 * If the activation failed due to an I/O error or ENOSPC we
4962 * skip to the next metaslab.
679b0f2a
PD
4963 */
4964 boolean_t activated;
4965 if (activation_error == 0) {
4966 activated = B_TRUE;
4967 } else if (activation_error == EBUSY ||
4968 activation_error == EEXIST) {
4969 activated = B_FALSE;
4970 } else {
34dc7c2f
BB
4971 mutex_exit(&msp->ms_lock);
4972 continue;
4973 }
679b0f2a 4974 ASSERT(msp->ms_loaded);
4e21fd06
DB
4975
4976 /*
4977 * Now that we have the lock, recheck to see if we should
4978 * continue to use this metaslab for this allocation. The
679b0f2a
PD
4979 * the metaslab is now loaded so metaslab_should_allocate()
4980 * can accurately determine if the allocation attempt should
4e21fd06
DB
4981 * proceed.
4982 */
c81f1790 4983 if (!metaslab_should_allocate(msp, asize, try_hard)) {
4e21fd06
DB
4984 /* Passivate this metaslab and select a new one. */
4985 metaslab_trace_add(zal, mg, msp, asize, d,
492f64e9 4986 TRACE_TOO_SMALL, allocator);
4e21fd06
DB
4987 goto next;
4988 }
4989
7a614407 4990 /*
679b0f2a
PD
4991 * If this metaslab is currently condensing then pick again
4992 * as we can't manipulate this metaslab until it's committed
619f0976
GW
4993 * to disk. If this metaslab is being initialized, we shouldn't
4994 * allocate from it since the allocated region might be
4995 * overwritten after allocation.
7a614407 4996 */
93cf2076 4997 if (msp->ms_condensing) {
4e21fd06 4998 metaslab_trace_add(zal, mg, msp, asize, d,
492f64e9 4999 TRACE_CONDENSING, allocator);
679b0f2a
PD
5000 if (activated) {
5001 metaslab_passivate(msp, msp->ms_weight &
5002 ~METASLAB_ACTIVE_MASK);
5003 }
7a614407
GW
5004 mutex_exit(&msp->ms_lock);
5005 continue;
1b939560 5006 } else if (msp->ms_disabled > 0) {
619f0976 5007 metaslab_trace_add(zal, mg, msp, asize, d,
1b939560 5008 TRACE_DISABLED, allocator);
679b0f2a
PD
5009 if (activated) {
5010 metaslab_passivate(msp, msp->ms_weight &
5011 ~METASLAB_ACTIVE_MASK);
5012 }
619f0976
GW
5013 mutex_exit(&msp->ms_lock);
5014 continue;
7a614407
GW
5015 }
5016
4e21fd06 5017 offset = metaslab_block_alloc(msp, asize, txg);
492f64e9 5018 metaslab_trace_add(zal, mg, msp, asize, d, offset, allocator);
4e21fd06
DB
5019
5020 if (offset != -1ULL) {
5021 /* Proactively passivate the metaslab, if needed */
679b0f2a
PD
5022 if (activated)
5023 metaslab_segment_may_passivate(msp);
34dc7c2f 5024 break;
4e21fd06
DB
5025 }
5026next:
5027 ASSERT(msp->ms_loaded);
5028
679b0f2a
PD
5029 /*
5030 * This code is disabled out because of issues with
5031 * tracepoints in non-gpl kernel modules.
5032 */
5033#if 0
5034 DTRACE_PROBE2(ms__alloc__failure, metaslab_t *, msp,
5035 uint64_t, asize);
5036#endif
5037
4e21fd06
DB
5038 /*
5039 * We were unable to allocate from this metaslab so determine
5040 * a new weight for this metaslab. Now that we have loaded
5041 * the metaslab we can provide a better hint to the metaslab
5042 * selector.
5043 *
5044 * For space-based metaslabs, we use the maximum block size.
5045 * This information is only available when the metaslab
5046 * is loaded and is more accurate than the generic free
5047 * space weight that was calculated by metaslab_weight().
5048 * This information allows us to quickly compare the maximum
5049 * available allocation in the metaslab to the allocation
5050 * size being requested.
5051 *
5052 * For segment-based metaslabs, determine the new weight
5053 * based on the highest bucket in the range tree. We
5054 * explicitly use the loaded segment weight (i.e. the range
5055 * tree histogram) since it contains the space that is
5056 * currently available for allocation and is accurate
5057 * even within a sync pass.
5058 */
679b0f2a 5059 uint64_t weight;
4e21fd06 5060 if (WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
c81f1790 5061 weight = metaslab_largest_allocatable(msp);
4e21fd06 5062 WEIGHT_SET_SPACEBASED(weight);
679b0f2a
PD
5063 } else {
5064 weight = metaslab_weight_from_range_tree(msp);
5065 }
5066
5067 if (activated) {
4e21fd06
DB
5068 metaslab_passivate(msp, weight);
5069 } else {
679b0f2a
PD
5070 /*
5071 * For the case where we use the metaslab that is
5072 * active for another allocator we want to make
5073 * sure that we retain the activation mask.
5074 *
5075 * Note that we could attempt to use something like
5076 * metaslab_recalculate_weight_and_sort() that
5077 * retains the activation mask here. That function
5078 * uses metaslab_weight() to set the weight though
5079 * which is not as accurate as the calculations
5080 * above.
5081 */
5082 weight |= msp->ms_weight & METASLAB_ACTIVE_MASK;
5083 metaslab_group_sort(mg, msp, weight);
4e21fd06 5084 }
679b0f2a 5085 metaslab_active_mask_verify(msp);
34dc7c2f 5086
4e21fd06
DB
5087 /*
5088 * We have just failed an allocation attempt, check
5089 * that metaslab_should_allocate() agrees. Otherwise,
5090 * we may end up in an infinite loop retrying the same
5091 * metaslab.
5092 */
c81f1790 5093 ASSERT(!metaslab_should_allocate(msp, asize, try_hard));
cc99f275 5094
34dc7c2f
BB
5095 mutex_exit(&msp->ms_lock);
5096 }
4e21fd06
DB
5097 mutex_exit(&msp->ms_lock);
5098 kmem_free(search, sizeof (*search));
5099 return (offset);
5100}
34dc7c2f 5101
4e21fd06
DB
5102static uint64_t
5103metaslab_group_alloc(metaslab_group_t *mg, zio_alloc_list_t *zal,
c81f1790
PD
5104 uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva, int d,
5105 int allocator, boolean_t try_hard)
4e21fd06
DB
5106{
5107 uint64_t offset;
34dc7c2f 5108
cc99f275 5109 offset = metaslab_group_alloc_normal(mg, zal, asize, txg, want_unique,
c81f1790 5110 dva, d, allocator, try_hard);
34dc7c2f 5111
4e21fd06
DB
5112 mutex_enter(&mg->mg_lock);
5113 if (offset == -1ULL) {
5114 mg->mg_failed_allocations++;
5115 metaslab_trace_add(zal, mg, NULL, asize, d,
492f64e9 5116 TRACE_GROUP_FAILURE, allocator);
4e21fd06
DB
5117 if (asize == SPA_GANGBLOCKSIZE) {
5118 /*
5119 * This metaslab group was unable to allocate
5120 * the minimum gang block size so it must be out of
5121 * space. We must notify the allocation throttle
5122 * to start skipping allocation attempts to this
5123 * metaslab group until more space becomes available.
5124 * Note: this failure cannot be caused by the
5125 * allocation throttle since the allocation throttle
5126 * is only responsible for skipping devices and
5127 * not failing block allocations.
5128 */
5129 mg->mg_no_free_space = B_TRUE;
5130 }
5131 }
5132 mg->mg_allocations++;
5133 mutex_exit(&mg->mg_lock);
34dc7c2f
BB
5134 return (offset);
5135}
5136
5137/*
5138 * Allocate a block for the specified i/o.
5139 */
a1d477c2 5140int
34dc7c2f 5141metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
4e21fd06 5142 dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags,
492f64e9 5143 zio_alloc_list_t *zal, int allocator)
34dc7c2f 5144{
f8020c93 5145 metaslab_class_allocator_t *mca = &mc->mc_allocator[allocator];
b22bab25 5146 metaslab_group_t *mg, *rotor;
34dc7c2f 5147 vdev_t *vd;
4e21fd06 5148 boolean_t try_hard = B_FALSE;
34dc7c2f
BB
5149
5150 ASSERT(!DVA_IS_VALID(&dva[d]));
5151
5152 /*
5153 * For testing, make some blocks above a certain size be gang blocks.
09b85f2d
BB
5154 * This will result in more split blocks when using device removal,
5155 * and a large number of split blocks coupled with ztest-induced
5156 * damage can result in extremely long reconstruction times. This
5157 * will also test spilling from special to normal.
34dc7c2f 5158 */
46adb282
RN
5159 if (psize >= metaslab_force_ganging &&
5160 metaslab_force_ganging_pct > 0 &&
5161 (random_in_range(100) < MIN(metaslab_force_ganging_pct, 100))) {
492f64e9
PD
5162 metaslab_trace_add(zal, NULL, NULL, psize, d, TRACE_FORCE_GANG,
5163 allocator);
2e528b49 5164 return (SET_ERROR(ENOSPC));
4e21fd06 5165 }
34dc7c2f
BB
5166
5167 /*
5168 * Start at the rotor and loop through all mgs until we find something.
f8020c93 5169 * Note that there's no locking on mca_rotor or mca_aliquot because
34dc7c2f
BB
5170 * nothing actually breaks if we miss a few updates -- we just won't
5171 * allocate quite as evenly. It all balances out over time.
5172 *
5173 * If we are doing ditto or log blocks, try to spread them across
5174 * consecutive vdevs. If we're forced to reuse a vdev before we've
5175 * allocated all of our ditto blocks, then try and spread them out on
5176 * that vdev as much as possible. If it turns out to not be possible,
5177 * gradually lower our standards until anything becomes acceptable.
5178 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
5179 * gives us hope of containing our fault domains to something we're
5180 * able to reason about. Otherwise, any two top-level vdev failures
5181 * will guarantee the loss of data. With consecutive allocation,
5182 * only two adjacent top-level vdev failures will result in data loss.
5183 *
5184 * If we are doing gang blocks (hintdva is non-NULL), try to keep
5185 * ourselves on the same vdev as our gang block header. That
5186 * way, we can hope for locality in vdev_cache, plus it makes our
5187 * fault domains something tractable.
5188 */
5189 if (hintdva) {
5190 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
428870ff
BB
5191
5192 /*
5193 * It's possible the vdev we're using as the hint no
a1d477c2
MA
5194 * longer exists or its mg has been closed (e.g. by
5195 * device removal). Consult the rotor when
428870ff
BB
5196 * all else fails.
5197 */
a1d477c2 5198 if (vd != NULL && vd->vdev_mg != NULL) {
aa755b35 5199 mg = vdev_get_mg(vd, mc);
428870ff 5200
ef55679a 5201 if (flags & METASLAB_HINTBP_AVOID)
428870ff
BB
5202 mg = mg->mg_next;
5203 } else {
f8020c93 5204 mg = mca->mca_rotor;
428870ff 5205 }
34dc7c2f
BB
5206 } else if (d != 0) {
5207 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
5208 mg = vd->vdev_mg->mg_next;
5209 } else {
f8020c93
AM
5210 ASSERT(mca->mca_rotor != NULL);
5211 mg = mca->mca_rotor;
34dc7c2f
BB
5212 }
5213
5214 /*
428870ff
BB
5215 * If the hint put us into the wrong metaslab class, or into a
5216 * metaslab group that has been passivated, just follow the rotor.
34dc7c2f 5217 */
428870ff 5218 if (mg->mg_class != mc || mg->mg_activation_count <= 0)
f8020c93 5219 mg = mca->mca_rotor;
34dc7c2f
BB
5220
5221 rotor = mg;
5222top:
34dc7c2f 5223 do {
4e21fd06 5224 boolean_t allocatable;
428870ff 5225
3dfb57a3 5226 ASSERT(mg->mg_activation_count == 1);
34dc7c2f 5227 vd = mg->mg_vd;
fb5f0bc8 5228
34dc7c2f 5229 /*
b128c09f 5230 * Don't allocate from faulted devices.
34dc7c2f 5231 */
4e21fd06 5232 if (try_hard) {
fb5f0bc8
BB
5233 spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
5234 allocatable = vdev_allocatable(vd);
5235 spa_config_exit(spa, SCL_ZIO, FTAG);
5236 } else {
5237 allocatable = vdev_allocatable(vd);
5238 }
ac72fac3
GW
5239
5240 /*
5241 * Determine if the selected metaslab group is eligible
3dfb57a3
DB
5242 * for allocations. If we're ganging then don't allow
5243 * this metaslab group to skip allocations since that would
5244 * inadvertently return ENOSPC and suspend the pool
ac72fac3
GW
5245 * even though space is still available.
5246 */
4e21fd06 5247 if (allocatable && !GANG_ALLOCATION(flags) && !try_hard) {
3dfb57a3 5248 allocatable = metaslab_group_allocatable(mg, rotor,
7bf4c97a 5249 flags, psize, allocator, d);
3dfb57a3 5250 }
ac72fac3 5251
4e21fd06
DB
5252 if (!allocatable) {
5253 metaslab_trace_add(zal, mg, NULL, psize, d,
492f64e9 5254 TRACE_NOT_ALLOCATABLE, allocator);
34dc7c2f 5255 goto next;
4e21fd06 5256 }
fb5f0bc8 5257
34dc7c2f 5258 /*
4dcc2bde 5259 * Avoid writing single-copy data to an unhealthy,
4e21fd06
DB
5260 * non-redundant vdev, unless we've already tried all
5261 * other vdevs.
34dc7c2f 5262 */
4dcc2bde 5263 if (vd->vdev_state < VDEV_STATE_HEALTHY &&
4e21fd06
DB
5264 d == 0 && !try_hard && vd->vdev_children == 0) {
5265 metaslab_trace_add(zal, mg, NULL, psize, d,
492f64e9 5266 TRACE_VDEV_ERROR, allocator);
34dc7c2f
BB
5267 goto next;
5268 }
5269
5270 ASSERT(mg->mg_class == mc);
5271
5caeef02 5272 uint64_t asize = vdev_psize_to_asize_txg(vd, psize, txg);
34dc7c2f
BB
5273 ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
5274
cc99f275
DB
5275 /*
5276 * If we don't need to try hard, then require that the
e1cfd73f 5277 * block be on a different metaslab from any other DVAs
cc99f275
DB
5278 * in this BP (unique=true). If we are trying hard, then
5279 * allow any metaslab to be used (unique=false).
5280 */
1c27024e 5281 uint64_t offset = metaslab_group_alloc(mg, zal, asize, txg,
c81f1790 5282 !try_hard, dva, d, allocator, try_hard);
3dfb57a3 5283
34dc7c2f
BB
5284 if (offset != -1ULL) {
5285 /*
5286 * If we've just selected this metaslab group,
5287 * figure out whether the corresponding vdev is
5288 * over- or under-used relative to the pool,
5289 * and set an allocation bias to even it out.
bb3250d0
ED
5290 *
5291 * Bias is also used to compensate for unequally
5292 * sized vdevs so that space is allocated fairly.
34dc7c2f 5293 */
f8020c93 5294 if (mca->mca_aliquot == 0 && metaslab_bias_enabled) {
34dc7c2f 5295 vdev_stat_t *vs = &vd->vdev_stat;
bb3250d0
ED
5296 int64_t vs_free = vs->vs_space - vs->vs_alloc;
5297 int64_t mc_free = mc->mc_space - mc->mc_alloc;
5298 int64_t ratio;
34dc7c2f
BB
5299
5300 /*
6d974228
GW
5301 * Calculate how much more or less we should
5302 * try to allocate from this device during
5303 * this iteration around the rotor.
6d974228 5304 *
bb3250d0
ED
5305 * This basically introduces a zero-centered
5306 * bias towards the devices with the most
5307 * free space, while compensating for vdev
5308 * size differences.
5309 *
5310 * Examples:
5311 * vdev V1 = 16M/128M
5312 * vdev V2 = 16M/128M
5313 * ratio(V1) = 100% ratio(V2) = 100%
5314 *
5315 * vdev V1 = 16M/128M
5316 * vdev V2 = 64M/128M
5317 * ratio(V1) = 127% ratio(V2) = 72%
6d974228 5318 *
bb3250d0
ED
5319 * vdev V1 = 16M/128M
5320 * vdev V2 = 64M/512M
5321 * ratio(V1) = 40% ratio(V2) = 160%
34dc7c2f 5322 */
bb3250d0
ED
5323 ratio = (vs_free * mc->mc_alloc_groups * 100) /
5324 (mc_free + 1);
5325 mg->mg_bias = ((ratio - 100) *
6d974228 5326 (int64_t)mg->mg_aliquot) / 100;
f3a7f661
GW
5327 } else if (!metaslab_bias_enabled) {
5328 mg->mg_bias = 0;
34dc7c2f
BB
5329 }
5330
b22bab25 5331 if ((flags & METASLAB_ZIL) ||
f8020c93 5332 atomic_add_64_nv(&mca->mca_aliquot, asize) >=
34dc7c2f 5333 mg->mg_aliquot + mg->mg_bias) {
f8020c93
AM
5334 mca->mca_rotor = mg->mg_next;
5335 mca->mca_aliquot = 0;
34dc7c2f
BB
5336 }
5337
5338 DVA_SET_VDEV(&dva[d], vd->vdev_id);
5339 DVA_SET_OFFSET(&dva[d], offset);
e3e7cf60
D
5340 DVA_SET_GANG(&dva[d],
5341 ((flags & METASLAB_GANG_HEADER) ? 1 : 0));
34dc7c2f
BB
5342 DVA_SET_ASIZE(&dva[d], asize);
5343
5344 return (0);
5345 }
5346next:
f8020c93
AM
5347 mca->mca_rotor = mg->mg_next;
5348 mca->mca_aliquot = 0;
34dc7c2f
BB
5349 } while ((mg = mg->mg_next) != rotor);
5350
4e21fd06 5351 /*
be5c6d96 5352 * If we haven't tried hard, perhaps do so now.
4e21fd06 5353 */
be5c6d96
MA
5354 if (!try_hard && (zfs_metaslab_try_hard_before_gang ||
5355 GANG_ALLOCATION(flags) || (flags & METASLAB_ZIL) != 0 ||
5356 psize <= 1 << spa->spa_min_ashift)) {
5357 METASLABSTAT_BUMP(metaslabstat_try_hard);
4e21fd06 5358 try_hard = B_TRUE;
fb5f0bc8
BB
5359 goto top;
5360 }
5361
861166b0 5362 memset(&dva[d], 0, sizeof (dva_t));
34dc7c2f 5363
492f64e9 5364 metaslab_trace_add(zal, rotor, NULL, psize, d, TRACE_ENOSPC, allocator);
2e528b49 5365 return (SET_ERROR(ENOSPC));
34dc7c2f
BB
5366}
5367
a1d477c2
MA
5368void
5369metaslab_free_concrete(vdev_t *vd, uint64_t offset, uint64_t asize,
d2734cce 5370 boolean_t checkpoint)
a1d477c2
MA
5371{
5372 metaslab_t *msp;
d2734cce 5373 spa_t *spa = vd->vdev_spa;
a1d477c2 5374
a1d477c2
MA
5375 ASSERT(vdev_is_concrete(vd));
5376 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5377 ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
5378
5379 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5380
5381 VERIFY(!msp->ms_condensing);
5382 VERIFY3U(offset, >=, msp->ms_start);
5383 VERIFY3U(offset + asize, <=, msp->ms_start + msp->ms_size);
5384 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5385 VERIFY0(P2PHASE(asize, 1ULL << vd->vdev_ashift));
5386
5387 metaslab_check_free_impl(vd, offset, asize);
d2734cce 5388
a1d477c2 5389 mutex_enter(&msp->ms_lock);
d2734cce
SD
5390 if (range_tree_is_empty(msp->ms_freeing) &&
5391 range_tree_is_empty(msp->ms_checkpointing)) {
5392 vdev_dirty(vd, VDD_METASLAB, msp, spa_syncing_txg(spa));
5393 }
5394
5395 if (checkpoint) {
5396 ASSERT(spa_has_checkpoint(spa));
5397 range_tree_add(msp->ms_checkpointing, offset, asize);
5398 } else {
5399 range_tree_add(msp->ms_freeing, offset, asize);
a1d477c2 5400 }
a1d477c2
MA
5401 mutex_exit(&msp->ms_lock);
5402}
5403
a1d477c2
MA
5404void
5405metaslab_free_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5406 uint64_t size, void *arg)
5407{
14e4e3cb 5408 (void) inner_offset;
d2734cce
SD
5409 boolean_t *checkpoint = arg;
5410
5411 ASSERT3P(checkpoint, !=, NULL);
a1d477c2
MA
5412
5413 if (vd->vdev_ops->vdev_op_remap != NULL)
d2734cce 5414 vdev_indirect_mark_obsolete(vd, offset, size);
a1d477c2 5415 else
d2734cce 5416 metaslab_free_impl(vd, offset, size, *checkpoint);
a1d477c2
MA
5417}
5418
5419static void
5420metaslab_free_impl(vdev_t *vd, uint64_t offset, uint64_t size,
d2734cce 5421 boolean_t checkpoint)
a1d477c2
MA
5422{
5423 spa_t *spa = vd->vdev_spa;
5424
5425 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5426
d2734cce 5427 if (spa_syncing_txg(spa) > spa_freeze_txg(spa))
a1d477c2
MA
5428 return;
5429
5430 if (spa->spa_vdev_removal != NULL &&
9e052db4 5431 spa->spa_vdev_removal->svr_vdev_id == vd->vdev_id &&
a1d477c2
MA
5432 vdev_is_concrete(vd)) {
5433 /*
5434 * Note: we check if the vdev is concrete because when
5435 * we complete the removal, we first change the vdev to be
5436 * an indirect vdev (in open context), and then (in syncing
5437 * context) clear spa_vdev_removal.
5438 */
d2734cce 5439 free_from_removing_vdev(vd, offset, size);
a1d477c2 5440 } else if (vd->vdev_ops->vdev_op_remap != NULL) {
d2734cce 5441 vdev_indirect_mark_obsolete(vd, offset, size);
a1d477c2 5442 vd->vdev_ops->vdev_op_remap(vd, offset, size,
d2734cce 5443 metaslab_free_impl_cb, &checkpoint);
a1d477c2 5444 } else {
d2734cce 5445 metaslab_free_concrete(vd, offset, size, checkpoint);
a1d477c2
MA
5446 }
5447}
5448
5449typedef struct remap_blkptr_cb_arg {
5450 blkptr_t *rbca_bp;
5451 spa_remap_cb_t rbca_cb;
5452 vdev_t *rbca_remap_vd;
5453 uint64_t rbca_remap_offset;
5454 void *rbca_cb_arg;
5455} remap_blkptr_cb_arg_t;
5456
65c7cc49 5457static void
a1d477c2
MA
5458remap_blkptr_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5459 uint64_t size, void *arg)
5460{
5461 remap_blkptr_cb_arg_t *rbca = arg;
5462 blkptr_t *bp = rbca->rbca_bp;
5463
5464 /* We can not remap split blocks. */
5465 if (size != DVA_GET_ASIZE(&bp->blk_dva[0]))
5466 return;
5467 ASSERT0(inner_offset);
5468
5469 if (rbca->rbca_cb != NULL) {
5470 /*
5471 * At this point we know that we are not handling split
5472 * blocks and we invoke the callback on the previous
5473 * vdev which must be indirect.
5474 */
5475 ASSERT3P(rbca->rbca_remap_vd->vdev_ops, ==, &vdev_indirect_ops);
5476
5477 rbca->rbca_cb(rbca->rbca_remap_vd->vdev_id,
5478 rbca->rbca_remap_offset, size, rbca->rbca_cb_arg);
5479
5480 /* set up remap_blkptr_cb_arg for the next call */
5481 rbca->rbca_remap_vd = vd;
5482 rbca->rbca_remap_offset = offset;
5483 }
5484
5485 /*
5486 * The phys birth time is that of dva[0]. This ensures that we know
5487 * when each dva was written, so that resilver can determine which
5488 * blocks need to be scrubbed (i.e. those written during the time
5489 * the vdev was offline). It also ensures that the key used in
5490 * the ARC hash table is unique (i.e. dva[0] + phys_birth). If
5491 * we didn't change the phys_birth, a lookup in the ARC for a
5492 * remapped BP could find the data that was previously stored at
5493 * this vdev + offset.
5494 */
5495 vdev_t *oldvd = vdev_lookup_top(vd->vdev_spa,
5496 DVA_GET_VDEV(&bp->blk_dva[0]));
5497 vdev_indirect_births_t *vib = oldvd->vdev_indirect_births;
493fcce9 5498 uint64_t physical_birth = vdev_indirect_births_physbirth(vib,
a1d477c2 5499 DVA_GET_OFFSET(&bp->blk_dva[0]), DVA_GET_ASIZE(&bp->blk_dva[0]));
493fcce9 5500 BP_SET_PHYSICAL_BIRTH(bp, physical_birth);
a1d477c2
MA
5501
5502 DVA_SET_VDEV(&bp->blk_dva[0], vd->vdev_id);
5503 DVA_SET_OFFSET(&bp->blk_dva[0], offset);
5504}
5505
34dc7c2f 5506/*
a1d477c2
MA
5507 * If the block pointer contains any indirect DVAs, modify them to refer to
5508 * concrete DVAs. Note that this will sometimes not be possible, leaving
5509 * the indirect DVA in place. This happens if the indirect DVA spans multiple
5510 * segments in the mapping (i.e. it is a "split block").
5511 *
5512 * If the BP was remapped, calls the callback on the original dva (note the
5513 * callback can be called multiple times if the original indirect DVA refers
5514 * to another indirect DVA, etc).
5515 *
5516 * Returns TRUE if the BP was remapped.
34dc7c2f 5517 */
a1d477c2
MA
5518boolean_t
5519spa_remap_blkptr(spa_t *spa, blkptr_t *bp, spa_remap_cb_t callback, void *arg)
34dc7c2f 5520{
a1d477c2
MA
5521 remap_blkptr_cb_arg_t rbca;
5522
5523 if (!zfs_remap_blkptr_enable)
5524 return (B_FALSE);
5525
5526 if (!spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS))
5527 return (B_FALSE);
5528
5529 /*
5530 * Dedup BP's can not be remapped, because ddt_phys_select() depends
5531 * on DVA[0] being the same in the BP as in the DDT (dedup table).
5532 */
5533 if (BP_GET_DEDUP(bp))
5534 return (B_FALSE);
5535
5536 /*
5537 * Gang blocks can not be remapped, because
5538 * zio_checksum_gang_verifier() depends on the DVA[0] that's in
5539 * the BP used to read the gang block header (GBH) being the same
5540 * as the DVA[0] that we allocated for the GBH.
5541 */
5542 if (BP_IS_GANG(bp))
5543 return (B_FALSE);
5544
5545 /*
5546 * Embedded BP's have no DVA to remap.
5547 */
5548 if (BP_GET_NDVAS(bp) < 1)
5549 return (B_FALSE);
5550
5551 /*
5552 * Note: we only remap dva[0]. If we remapped other dvas, we
5553 * would no longer know what their phys birth txg is.
5554 */
5555 dva_t *dva = &bp->blk_dva[0];
5556
34dc7c2f
BB
5557 uint64_t offset = DVA_GET_OFFSET(dva);
5558 uint64_t size = DVA_GET_ASIZE(dva);
a1d477c2
MA
5559 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
5560
5561 if (vd->vdev_ops->vdev_op_remap == NULL)
5562 return (B_FALSE);
5563
5564 rbca.rbca_bp = bp;
5565 rbca.rbca_cb = callback;
5566 rbca.rbca_remap_vd = vd;
5567 rbca.rbca_remap_offset = offset;
5568 rbca.rbca_cb_arg = arg;
5569
5570 /*
5571 * remap_blkptr_cb() will be called in order for each level of
5572 * indirection, until a concrete vdev is reached or a split block is
5573 * encountered. old_vd and old_offset are updated within the callback
5574 * as we go from the one indirect vdev to the next one (either concrete
5575 * or indirect again) in that order.
5576 */
5577 vd->vdev_ops->vdev_op_remap(vd, offset, size, remap_blkptr_cb, &rbca);
5578
5579 /* Check if the DVA wasn't remapped because it is a split block */
5580 if (DVA_GET_VDEV(&rbca.rbca_bp->blk_dva[0]) == vd->vdev_id)
5581 return (B_FALSE);
5582
5583 return (B_TRUE);
5584}
5585
5586/*
5587 * Undo the allocation of a DVA which happened in the given transaction group.
5588 */
5589void
5590metaslab_unalloc_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
5591{
34dc7c2f 5592 metaslab_t *msp;
a1d477c2
MA
5593 vdev_t *vd;
5594 uint64_t vdev = DVA_GET_VDEV(dva);
5595 uint64_t offset = DVA_GET_OFFSET(dva);
5596 uint64_t size = DVA_GET_ASIZE(dva);
5597
5598 ASSERT(DVA_IS_VALID(dva));
5599 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
34dc7c2f 5600
34dc7c2f
BB
5601 if (txg > spa_freeze_txg(spa))
5602 return;
5603
7d2868d5 5604 if ((vd = vdev_lookup_top(spa, vdev)) == NULL || !DVA_IS_VALID(dva) ||
34dc7c2f 5605 (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
7d2868d5
BB
5606 zfs_panic_recover("metaslab_free_dva(): bad DVA %llu:%llu:%llu",
5607 (u_longlong_t)vdev, (u_longlong_t)offset,
5608 (u_longlong_t)size);
34dc7c2f
BB
5609 return;
5610 }
5611
a1d477c2
MA
5612 ASSERT(!vd->vdev_removing);
5613 ASSERT(vdev_is_concrete(vd));
5614 ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
5615 ASSERT3P(vd->vdev_indirect_mapping, ==, NULL);
34dc7c2f
BB
5616
5617 if (DVA_GET_GANG(dva))
2b56a634 5618 size = vdev_gang_header_asize(vd);
34dc7c2f 5619
a1d477c2 5620 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
93cf2076 5621
a1d477c2 5622 mutex_enter(&msp->ms_lock);
d2734cce 5623 range_tree_remove(msp->ms_allocating[txg & TXG_MASK],
a1d477c2 5624 offset, size);
f09fda50 5625 msp->ms_allocating_total -= size;
34dc7c2f 5626
a1d477c2
MA
5627 VERIFY(!msp->ms_condensing);
5628 VERIFY3U(offset, >=, msp->ms_start);
5629 VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
d2734cce 5630 VERIFY3U(range_tree_space(msp->ms_allocatable) + size, <=,
a1d477c2
MA
5631 msp->ms_size);
5632 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5633 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
d2734cce 5634 range_tree_add(msp->ms_allocatable, offset, size);
34dc7c2f
BB
5635 mutex_exit(&msp->ms_lock);
5636}
5637
5638/*
d2734cce 5639 * Free the block represented by the given DVA.
34dc7c2f 5640 */
a1d477c2 5641void
d2734cce 5642metaslab_free_dva(spa_t *spa, const dva_t *dva, boolean_t checkpoint)
34dc7c2f
BB
5643{
5644 uint64_t vdev = DVA_GET_VDEV(dva);
5645 uint64_t offset = DVA_GET_OFFSET(dva);
5646 uint64_t size = DVA_GET_ASIZE(dva);
a1d477c2 5647 vdev_t *vd = vdev_lookup_top(spa, vdev);
34dc7c2f
BB
5648
5649 ASSERT(DVA_IS_VALID(dva));
a1d477c2 5650 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
34dc7c2f 5651
a1d477c2 5652 if (DVA_GET_GANG(dva)) {
2b56a634 5653 size = vdev_gang_header_asize(vd);
34dc7c2f
BB
5654 }
5655
d2734cce 5656 metaslab_free_impl(vd, offset, size, checkpoint);
34dc7c2f
BB
5657}
5658
3dfb57a3
DB
5659/*
5660 * Reserve some allocation slots. The reservation system must be called
5661 * before we call into the allocator. If there aren't any available slots
5662 * then the I/O will be throttled until an I/O completes and its slots are
5663 * freed up. The function returns true if it was successful in placing
5664 * the reservation.
5665 */
5666boolean_t
492f64e9
PD
5667metaslab_class_throttle_reserve(metaslab_class_t *mc, int slots, int allocator,
5668 zio_t *zio, int flags)
3dfb57a3 5669{
f8020c93 5670 metaslab_class_allocator_t *mca = &mc->mc_allocator[allocator];
f8020c93 5671 uint64_t max = mca->mca_alloc_max_slots;
3dfb57a3
DB
5672
5673 ASSERT(mc->mc_alloc_throttle_enabled);
1b50749c
AM
5674 if (GANG_ALLOCATION(flags) || (flags & METASLAB_MUST_RESERVE) ||
5675 zfs_refcount_count(&mca->mca_alloc_slots) + slots <= max) {
3dfb57a3 5676 /*
dd3bda39
AM
5677 * The potential race between _count() and _add() is covered
5678 * by the allocator lock in most cases, or irrelevant due to
5679 * GANG_ALLOCATION() or METASLAB_MUST_RESERVE set in others.
5680 * But even if we assume some other non-existing scenario, the
5681 * worst that can happen is few more I/Os get to allocation
5682 * earlier, that is not a problem.
5683 *
3dfb57a3
DB
5684 * We reserve the slots individually so that we can unreserve
5685 * them individually when an I/O completes.
5686 */
5ba4025a 5687 zfs_refcount_add_few(&mca->mca_alloc_slots, slots, zio);
3dfb57a3 5688 zio->io_flags |= ZIO_FLAG_IO_ALLOCATING;
1b50749c 5689 return (B_TRUE);
3dfb57a3 5690 }
1b50749c 5691 return (B_FALSE);
3dfb57a3
DB
5692}
5693
5694void
492f64e9
PD
5695metaslab_class_throttle_unreserve(metaslab_class_t *mc, int slots,
5696 int allocator, zio_t *zio)
3dfb57a3 5697{
f8020c93
AM
5698 metaslab_class_allocator_t *mca = &mc->mc_allocator[allocator];
5699
3dfb57a3 5700 ASSERT(mc->mc_alloc_throttle_enabled);
5ba4025a 5701 zfs_refcount_remove_few(&mca->mca_alloc_slots, slots, zio);
3dfb57a3
DB
5702}
5703
a1d477c2
MA
5704static int
5705metaslab_claim_concrete(vdev_t *vd, uint64_t offset, uint64_t size,
5706 uint64_t txg)
5707{
5708 metaslab_t *msp;
5709 spa_t *spa = vd->vdev_spa;
5710 int error = 0;
5711
5712 if (offset >> vd->vdev_ms_shift >= vd->vdev_ms_count)
7ab96299 5713 return (SET_ERROR(ENXIO));
a1d477c2
MA
5714
5715 ASSERT3P(vd->vdev_ms, !=, NULL);
5716 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5717
5718 mutex_enter(&msp->ms_lock);
5719
7ab96299 5720 if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded) {
492f64e9 5721 error = metaslab_activate(msp, 0, METASLAB_WEIGHT_CLAIM);
7ab96299
TC
5722 if (error == EBUSY) {
5723 ASSERT(msp->ms_loaded);
5724 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
5725 error = 0;
5726 }
5727 }
a1d477c2 5728
d2734cce
SD
5729 if (error == 0 &&
5730 !range_tree_contains(msp->ms_allocatable, offset, size))
a1d477c2
MA
5731 error = SET_ERROR(ENOENT);
5732
5733 if (error || txg == 0) { /* txg == 0 indicates dry run */
5734 mutex_exit(&msp->ms_lock);
5735 return (error);
5736 }
5737
5738 VERIFY(!msp->ms_condensing);
5739 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5740 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
d2734cce
SD
5741 VERIFY3U(range_tree_space(msp->ms_allocatable) - size, <=,
5742 msp->ms_size);
5743 range_tree_remove(msp->ms_allocatable, offset, size);
1b939560 5744 range_tree_clear(msp->ms_trim, offset, size);
a1d477c2 5745
76d04993 5746 if (spa_writeable(spa)) { /* don't dirty if we're zdb(8) */
f09fda50
PD
5747 metaslab_class_t *mc = msp->ms_group->mg_class;
5748 multilist_sublist_t *mls =
ffdf019c 5749 multilist_sublist_lock_obj(&mc->mc_metaslab_txg_list, msp);
f09fda50
PD
5750 if (!multilist_link_active(&msp->ms_class_txg_node)) {
5751 msp->ms_selected_txg = txg;
5752 multilist_sublist_insert_head(mls, msp);
5753 }
5754 multilist_sublist_unlock(mls);
5755
d2734cce 5756 if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
a1d477c2 5757 vdev_dirty(vd, VDD_METASLAB, msp, txg);
d2734cce
SD
5758 range_tree_add(msp->ms_allocating[txg & TXG_MASK],
5759 offset, size);
f09fda50 5760 msp->ms_allocating_total += size;
a1d477c2
MA
5761 }
5762
5763 mutex_exit(&msp->ms_lock);
5764
5765 return (0);
5766}
5767
5768typedef struct metaslab_claim_cb_arg_t {
5769 uint64_t mcca_txg;
5770 int mcca_error;
5771} metaslab_claim_cb_arg_t;
5772
a1d477c2
MA
5773static void
5774metaslab_claim_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5775 uint64_t size, void *arg)
5776{
14e4e3cb 5777 (void) inner_offset;
a1d477c2
MA
5778 metaslab_claim_cb_arg_t *mcca_arg = arg;
5779
5780 if (mcca_arg->mcca_error == 0) {
5781 mcca_arg->mcca_error = metaslab_claim_concrete(vd, offset,
5782 size, mcca_arg->mcca_txg);
5783 }
5784}
5785
5786int
5787metaslab_claim_impl(vdev_t *vd, uint64_t offset, uint64_t size, uint64_t txg)
5788{
5789 if (vd->vdev_ops->vdev_op_remap != NULL) {
5790 metaslab_claim_cb_arg_t arg;
5791
5792 /*
76d04993 5793 * Only zdb(8) can claim on indirect vdevs. This is used
a1d477c2
MA
5794 * to detect leaks of mapped space (that are not accounted
5795 * for in the obsolete counts, spacemap, or bpobj).
5796 */
5797 ASSERT(!spa_writeable(vd->vdev_spa));
5798 arg.mcca_error = 0;
5799 arg.mcca_txg = txg;
5800
5801 vd->vdev_ops->vdev_op_remap(vd, offset, size,
5802 metaslab_claim_impl_cb, &arg);
5803
5804 if (arg.mcca_error == 0) {
5805 arg.mcca_error = metaslab_claim_concrete(vd,
5806 offset, size, txg);
5807 }
5808 return (arg.mcca_error);
5809 } else {
5810 return (metaslab_claim_concrete(vd, offset, size, txg));
5811 }
5812}
5813
5814/*
5815 * Intent log support: upon opening the pool after a crash, notify the SPA
5816 * of blocks that the intent log has allocated for immediate write, but
5817 * which are still considered free by the SPA because the last transaction
5818 * group didn't commit yet.
5819 */
5820static int
5821metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
5822{
5823 uint64_t vdev = DVA_GET_VDEV(dva);
5824 uint64_t offset = DVA_GET_OFFSET(dva);
5825 uint64_t size = DVA_GET_ASIZE(dva);
5826 vdev_t *vd;
5827
5828 if ((vd = vdev_lookup_top(spa, vdev)) == NULL) {
5829 return (SET_ERROR(ENXIO));
5830 }
5831
5832 ASSERT(DVA_IS_VALID(dva));
5833
5834 if (DVA_GET_GANG(dva))
2b56a634 5835 size = vdev_gang_header_asize(vd);
a1d477c2
MA
5836
5837 return (metaslab_claim_impl(vd, offset, size, txg));
5838}
5839
34dc7c2f
BB
5840int
5841metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
4e21fd06 5842 int ndvas, uint64_t txg, blkptr_t *hintbp, int flags,
492f64e9 5843 zio_alloc_list_t *zal, zio_t *zio, int allocator)
34dc7c2f
BB
5844{
5845 dva_t *dva = bp->blk_dva;
928e8ad4 5846 dva_t *hintdva = (hintbp != NULL) ? hintbp->blk_dva : NULL;
1c27024e 5847 int error = 0;
34dc7c2f 5848
493fcce9
GW
5849 ASSERT0(BP_GET_LOGICAL_BIRTH(bp));
5850 ASSERT0(BP_GET_PHYSICAL_BIRTH(bp));
b128c09f
BB
5851
5852 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
5853
f8020c93
AM
5854 if (mc->mc_allocator[allocator].mca_rotor == NULL) {
5855 /* no vdevs in this class */
b128c09f 5856 spa_config_exit(spa, SCL_ALLOC, FTAG);
2e528b49 5857 return (SET_ERROR(ENOSPC));
b128c09f 5858 }
34dc7c2f
BB
5859
5860 ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
5861 ASSERT(BP_GET_NDVAS(bp) == 0);
5862 ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
4e21fd06 5863 ASSERT3P(zal, !=, NULL);
34dc7c2f 5864
1c27024e 5865 for (int d = 0; d < ndvas; d++) {
34dc7c2f 5866 error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
492f64e9 5867 txg, flags, zal, allocator);
93cf2076 5868 if (error != 0) {
34dc7c2f 5869 for (d--; d >= 0; d--) {
a1d477c2 5870 metaslab_unalloc_dva(spa, &dva[d], txg);
3dfb57a3 5871 metaslab_group_alloc_decrement(spa,
492f64e9
PD
5872 DVA_GET_VDEV(&dva[d]), zio, flags,
5873 allocator, B_FALSE);
861166b0 5874 memset(&dva[d], 0, sizeof (dva_t));
34dc7c2f 5875 }
b128c09f 5876 spa_config_exit(spa, SCL_ALLOC, FTAG);
34dc7c2f 5877 return (error);
3dfb57a3
DB
5878 } else {
5879 /*
5880 * Update the metaslab group's queue depth
5881 * based on the newly allocated dva.
5882 */
5883 metaslab_group_alloc_increment(spa,
492f64e9 5884 DVA_GET_VDEV(&dva[d]), zio, flags, allocator);
34dc7c2f
BB
5885 }
5886 }
5887 ASSERT(error == 0);
5888 ASSERT(BP_GET_NDVAS(bp) == ndvas);
5889
b128c09f
BB
5890 spa_config_exit(spa, SCL_ALLOC, FTAG);
5891
efe7978d 5892 BP_SET_BIRTH(bp, txg, 0);
b128c09f 5893
34dc7c2f
BB
5894 return (0);
5895}
5896
5897void
5898metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
5899{
5900 const dva_t *dva = bp->blk_dva;
1c27024e 5901 int ndvas = BP_GET_NDVAS(bp);
34dc7c2f
BB
5902
5903 ASSERT(!BP_IS_HOLE(bp));
493fcce9 5904 ASSERT(!now || BP_GET_LOGICAL_BIRTH(bp) >= spa_syncing_txg(spa));
b128c09f 5905
d2734cce
SD
5906 /*
5907 * If we have a checkpoint for the pool we need to make sure that
5908 * the blocks that we free that are part of the checkpoint won't be
5909 * reused until the checkpoint is discarded or we revert to it.
5910 *
5911 * The checkpoint flag is passed down the metaslab_free code path
5912 * and is set whenever we want to add a block to the checkpoint's
5913 * accounting. That is, we "checkpoint" blocks that existed at the
5914 * time the checkpoint was created and are therefore referenced by
5915 * the checkpointed uberblock.
5916 *
5917 * Note that, we don't checkpoint any blocks if the current
5918 * syncing txg <= spa_checkpoint_txg. We want these frees to sync
5919 * normally as they will be referenced by the checkpointed uberblock.
5920 */
5921 boolean_t checkpoint = B_FALSE;
493fcce9 5922 if (BP_GET_LOGICAL_BIRTH(bp) <= spa->spa_checkpoint_txg &&
d2734cce
SD
5923 spa_syncing_txg(spa) > spa->spa_checkpoint_txg) {
5924 /*
5925 * At this point, if the block is part of the checkpoint
5926 * there is no way it was created in the current txg.
5927 */
5928 ASSERT(!now);
5929 ASSERT3U(spa_syncing_txg(spa), ==, txg);
5930 checkpoint = B_TRUE;
5931 }
5932
b128c09f 5933 spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
34dc7c2f 5934
a1d477c2
MA
5935 for (int d = 0; d < ndvas; d++) {
5936 if (now) {
5937 metaslab_unalloc_dva(spa, &dva[d], txg);
5938 } else {
d2734cce
SD
5939 ASSERT3U(txg, ==, spa_syncing_txg(spa));
5940 metaslab_free_dva(spa, &dva[d], checkpoint);
a1d477c2
MA
5941 }
5942 }
b128c09f
BB
5943
5944 spa_config_exit(spa, SCL_FREE, FTAG);
34dc7c2f
BB
5945}
5946
5947int
5948metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
5949{
5950 const dva_t *dva = bp->blk_dva;
5951 int ndvas = BP_GET_NDVAS(bp);
1c27024e 5952 int error = 0;
34dc7c2f
BB
5953
5954 ASSERT(!BP_IS_HOLE(bp));
5955
b128c09f
BB
5956 if (txg != 0) {
5957 /*
5958 * First do a dry run to make sure all DVAs are claimable,
5959 * so we don't have to unwind from partial failures below.
5960 */
5961 if ((error = metaslab_claim(spa, bp, 0)) != 0)
5962 return (error);
5963 }
5964
5965 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
5966
cc99f275
DB
5967 for (int d = 0; d < ndvas; d++) {
5968 error = metaslab_claim_dva(spa, &dva[d], txg);
5969 if (error != 0)
b128c09f 5970 break;
cc99f275 5971 }
b128c09f
BB
5972
5973 spa_config_exit(spa, SCL_ALLOC, FTAG);
5974
5975 ASSERT(error == 0 || txg == 0);
34dc7c2f 5976
b128c09f 5977 return (error);
34dc7c2f 5978}
920dd524 5979
a1d477c2
MA
5980static void
5981metaslab_check_free_impl_cb(uint64_t inner, vdev_t *vd, uint64_t offset,
5982 uint64_t size, void *arg)
5983{
14e4e3cb
AZ
5984 (void) inner, (void) arg;
5985
a1d477c2
MA
5986 if (vd->vdev_ops == &vdev_indirect_ops)
5987 return;
5988
5989 metaslab_check_free_impl(vd, offset, size);
5990}
5991
5992static void
5993metaslab_check_free_impl(vdev_t *vd, uint64_t offset, uint64_t size)
5994{
5995 metaslab_t *msp;
2a8ba608 5996 spa_t *spa __maybe_unused = vd->vdev_spa;
a1d477c2
MA
5997
5998 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
5999 return;
6000
6001 if (vd->vdev_ops->vdev_op_remap != NULL) {
6002 vd->vdev_ops->vdev_op_remap(vd, offset, size,
6003 metaslab_check_free_impl_cb, NULL);
6004 return;
6005 }
6006
6007 ASSERT(vdev_is_concrete(vd));
6008 ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
6009 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
6010
6011 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6012
6013 mutex_enter(&msp->ms_lock);
df72b8be
SD
6014 if (msp->ms_loaded) {
6015 range_tree_verify_not_present(msp->ms_allocatable,
6016 offset, size);
6017 }
a1d477c2 6018
93e28d66
SD
6019 /*
6020 * Check all segments that currently exist in the freeing pipeline.
6021 *
6022 * It would intuitively make sense to also check the current allocating
6023 * tree since metaslab_unalloc_dva() exists for extents that are
e1cfd73f 6024 * allocated and freed in the same sync pass within the same txg.
93e28d66
SD
6025 * Unfortunately there are places (e.g. the ZIL) where we allocate a
6026 * segment but then we free part of it within the same txg
6027 * [see zil_sync()]. Thus, we don't call range_tree_verify() in the
6028 * current allocating tree.
6029 */
df72b8be
SD
6030 range_tree_verify_not_present(msp->ms_freeing, offset, size);
6031 range_tree_verify_not_present(msp->ms_checkpointing, offset, size);
6032 range_tree_verify_not_present(msp->ms_freed, offset, size);
a1d477c2 6033 for (int j = 0; j < TXG_DEFER_SIZE; j++)
df72b8be 6034 range_tree_verify_not_present(msp->ms_defer[j], offset, size);
93e28d66 6035 range_tree_verify_not_present(msp->ms_trim, offset, size);
a1d477c2
MA
6036 mutex_exit(&msp->ms_lock);
6037}
6038
13fe0198
MA
6039void
6040metaslab_check_free(spa_t *spa, const blkptr_t *bp)
6041{
13fe0198
MA
6042 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
6043 return;
6044
6045 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1c27024e 6046 for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
93cf2076
GW
6047 uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
6048 vdev_t *vd = vdev_lookup_top(spa, vdev);
6049 uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
13fe0198 6050 uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
13fe0198 6051
a1d477c2 6052 if (DVA_GET_GANG(&bp->blk_dva[i]))
2b56a634 6053 size = vdev_gang_header_asize(vd);
a1d477c2
MA
6054
6055 ASSERT3P(vd, !=, NULL);
13fe0198 6056
a1d477c2 6057 metaslab_check_free_impl(vd, offset, size);
13fe0198
MA
6058 }
6059 spa_config_exit(spa, SCL_VDEV, FTAG);
6060}
6061
1b939560
BB
6062static void
6063metaslab_group_disable_wait(metaslab_group_t *mg)
6064{
6065 ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
6066 while (mg->mg_disabled_updating) {
6067 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
6068 }
6069}
6070
6071static void
6072metaslab_group_disabled_increment(metaslab_group_t *mg)
6073{
6074 ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
6075 ASSERT(mg->mg_disabled_updating);
6076
6077 while (mg->mg_ms_disabled >= max_disabled_ms) {
6078 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
6079 }
6080 mg->mg_ms_disabled++;
6081 ASSERT3U(mg->mg_ms_disabled, <=, max_disabled_ms);
6082}
6083
6084/*
6085 * Mark the metaslab as disabled to prevent any allocations on this metaslab.
6086 * We must also track how many metaslabs are currently disabled within a
6087 * metaslab group and limit them to prevent allocation failures from
6088 * occurring because all metaslabs are disabled.
6089 */
6090void
6091metaslab_disable(metaslab_t *msp)
6092{
6093 ASSERT(!MUTEX_HELD(&msp->ms_lock));
6094 metaslab_group_t *mg = msp->ms_group;
6095
6096 mutex_enter(&mg->mg_ms_disabled_lock);
6097
6098 /*
6099 * To keep an accurate count of how many threads have disabled
6100 * a specific metaslab group, we only allow one thread to mark
6101 * the metaslab group at a time. This ensures that the value of
6102 * ms_disabled will be accurate when we decide to mark a metaslab
6103 * group as disabled. To do this we force all other threads
6104 * to wait till the metaslab's mg_disabled_updating flag is no
6105 * longer set.
6106 */
6107 metaslab_group_disable_wait(mg);
6108 mg->mg_disabled_updating = B_TRUE;
6109 if (msp->ms_disabled == 0) {
6110 metaslab_group_disabled_increment(mg);
6111 }
6112 mutex_enter(&msp->ms_lock);
6113 msp->ms_disabled++;
6114 mutex_exit(&msp->ms_lock);
6115
6116 mg->mg_disabled_updating = B_FALSE;
6117 cv_broadcast(&mg->mg_ms_disabled_cv);
6118 mutex_exit(&mg->mg_ms_disabled_lock);
6119}
6120
6121void
f09fda50 6122metaslab_enable(metaslab_t *msp, boolean_t sync, boolean_t unload)
1b939560
BB
6123{
6124 metaslab_group_t *mg = msp->ms_group;
6125 spa_t *spa = mg->mg_vd->vdev_spa;
6126
6127 /*
6128 * Wait for the outstanding IO to be synced to prevent newly
6129 * allocated blocks from being overwritten. This used by
6130 * initialize and TRIM which are modifying unallocated space.
6131 */
6132 if (sync)
6133 txg_wait_synced(spa_get_dsl(spa), 0);
6134
6135 mutex_enter(&mg->mg_ms_disabled_lock);
6136 mutex_enter(&msp->ms_lock);
6137 if (--msp->ms_disabled == 0) {
6138 mg->mg_ms_disabled--;
6139 cv_broadcast(&mg->mg_ms_disabled_cv);
f09fda50
PD
6140 if (unload)
6141 metaslab_unload(msp);
1b939560
BB
6142 }
6143 mutex_exit(&msp->ms_lock);
6144 mutex_exit(&mg->mg_ms_disabled_lock);
6145}
6146
600a02b8
AM
6147void
6148metaslab_set_unflushed_dirty(metaslab_t *ms, boolean_t dirty)
6149{
6150 ms->ms_unflushed_dirty = dirty;
6151}
6152
93e28d66
SD
6153static void
6154metaslab_update_ondisk_flush_data(metaslab_t *ms, dmu_tx_t *tx)
6155{
6156 vdev_t *vd = ms->ms_group->mg_vd;
6157 spa_t *spa = vd->vdev_spa;
6158 objset_t *mos = spa_meta_objset(spa);
6159
6160 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
6161
6162 metaslab_unflushed_phys_t entry = {
6163 .msp_unflushed_txg = metaslab_unflushed_txg(ms),
6164 };
6165 uint64_t entry_size = sizeof (entry);
6166 uint64_t entry_offset = ms->ms_id * entry_size;
6167
6168 uint64_t object = 0;
6169 int err = zap_lookup(mos, vd->vdev_top_zap,
6170 VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1,
6171 &object);
6172 if (err == ENOENT) {
6173 object = dmu_object_alloc(mos, DMU_OTN_UINT64_METADATA,
6174 SPA_OLD_MAXBLOCKSIZE, DMU_OT_NONE, 0, tx);
6175 VERIFY0(zap_add(mos, vd->vdev_top_zap,
6176 VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1,
6177 &object, tx));
6178 } else {
6179 VERIFY0(err);
6180 }
6181
6182 dmu_write(spa_meta_objset(spa), object, entry_offset, entry_size,
6183 &entry, tx);
6184}
6185
6186void
6187metaslab_set_unflushed_txg(metaslab_t *ms, uint64_t txg, dmu_tx_t *tx)
6188{
93e28d66
SD
6189 ms->ms_unflushed_txg = txg;
6190 metaslab_update_ondisk_flush_data(ms, tx);
6191}
6192
600a02b8
AM
6193boolean_t
6194metaslab_unflushed_dirty(metaslab_t *ms)
6195{
6196 return (ms->ms_unflushed_dirty);
6197}
6198
93e28d66
SD
6199uint64_t
6200metaslab_unflushed_txg(metaslab_t *ms)
6201{
6202 return (ms->ms_unflushed_txg);
6203}
6204
ab8d9c17 6205ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, aliquot, U64, ZMOD_RW,
03fdcb9a 6206 "Allocation granularity (a.k.a. stripe size)");
02730c33 6207
03fdcb9a
MM
6208ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, debug_load, INT, ZMOD_RW,
6209 "Load all metaslabs when pool is first opened");
02730c33 6210
03fdcb9a
MM
6211ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, debug_unload, INT, ZMOD_RW,
6212 "Prevent metaslabs from being unloaded");
f4a4046b 6213
03fdcb9a
MM
6214ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, preload_enabled, INT, ZMOD_RW,
6215 "Preload potential metaslabs during reassessment");
eef0f4d8 6216
342357cd
AM
6217ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, preload_limit, UINT, ZMOD_RW,
6218 "Max number of metaslabs per group to preload");
6219
fdc2d303 6220ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, unload_delay, UINT, ZMOD_RW,
03fdcb9a 6221 "Delay in txgs after metaslab was last used before unloading");
eef0f4d8 6222
fdc2d303 6223ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, unload_delay_ms, UINT, ZMOD_RW,
03fdcb9a 6224 "Delay in milliseconds after metaslab was last used before unloading");
02730c33 6225
03fdcb9a 6226/* BEGIN CSTYLED */
fdc2d303 6227ZFS_MODULE_PARAM(zfs_mg, zfs_mg_, noalloc_threshold, UINT, ZMOD_RW,
03fdcb9a
MM
6228 "Percentage of metaslab group size that should be free to make it "
6229 "eligible for allocation");
f3a7f661 6230
fdc2d303 6231ZFS_MODULE_PARAM(zfs_mg, zfs_mg_, fragmentation_threshold, UINT, ZMOD_RW,
03fdcb9a
MM
6232 "Percentage of metaslab group size that should be considered eligible "
6233 "for allocations unless all metaslab groups within the metaslab class "
6234 "have also crossed this threshold");
02730c33 6235
7ada752a
AZ
6236ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, fragmentation_factor_enabled, INT,
6237 ZMOD_RW,
03fdcb9a
MM
6238 "Use the fragmentation metric to prefer less fragmented metaslabs");
6239/* END CSTYLED */
02730c33 6240
fdc2d303 6241ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, fragmentation_threshold, UINT,
7ada752a
AZ
6242 ZMOD_RW, "Fragmentation for metaslab to allow allocation");
6243
03fdcb9a
MM
6244ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, lba_weighting_enabled, INT, ZMOD_RW,
6245 "Prefer metaslabs with lower LBAs");
4e21fd06 6246
03fdcb9a
MM
6247ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, bias_enabled, INT, ZMOD_RW,
6248 "Enable metaslab group biasing");
4e21fd06 6249
03fdcb9a
MM
6250ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, segment_weight_enabled, INT,
6251 ZMOD_RW, "Enable segment-based metaslab selection");
a1d477c2 6252
03fdcb9a
MM
6253ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, switch_threshold, INT, ZMOD_RW,
6254 "Segment-based metaslab selection maximum buckets before switching");
d3230d76 6255
ab8d9c17 6256ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, force_ganging, U64, ZMOD_RW,
46adb282
RN
6257 "Blocks larger than this size are sometimes forced to be gang blocks");
6258
6259ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, force_ganging_pct, UINT, ZMOD_RW,
6260 "Percentage of large blocks that will be forced to be gang blocks");
d3230d76 6261
fdc2d303 6262ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_max_search, UINT, ZMOD_RW,
03fdcb9a 6263 "Max distance (bytes) to search forward before using size tree");
c81f1790 6264
03fdcb9a
MM
6265ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_use_largest_segment, INT, ZMOD_RW,
6266 "When looking in size tree, use largest segment instead of exact fit");
f09fda50 6267
ab8d9c17 6268ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, max_size_cache_sec, U64,
03fdcb9a 6269 ZMOD_RW, "How long to trust the cached max chunk size of a metaslab");
cc99f275 6270
fdc2d303 6271ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, mem_limit, UINT, ZMOD_RW,
03fdcb9a 6272 "Percentage of memory that can be used to store metaslab range trees");
be5c6d96
MA
6273
6274ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, try_hard_before_gang, INT,
6275 ZMOD_RW, "Try hard to allocate before ganging");
6276
fdc2d303 6277ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, find_max_tries, UINT, ZMOD_RW,
be5c6d96 6278 "Normally only consider this many of the best metaslabs in each vdev");
95f71c01
EN
6279
6280/* BEGIN CSTYLED */
6281ZFS_MODULE_PARAM_CALL(zfs, zfs_, active_allocator,
6282 param_set_active_allocator, param_get_charp, ZMOD_RW,
6283 "SPA active allocator");
6284/* END CSTYLED */