]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/metaslab.c
Fix typo/etc in module/zfs/zfs_ctldir.c
[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
9 * or http://www.opensolaris.org/os/licensing.
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.
cc99f275 23 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
2e528b49 24 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
cc99f275 25 * Copyright (c) 2017, Intel Corporation.
34dc7c2f
BB
26 */
27
34dc7c2f 28#include <sys/zfs_context.h>
34dc7c2f
BB
29#include <sys/dmu.h>
30#include <sys/dmu_tx.h>
31#include <sys/space_map.h>
32#include <sys/metaslab_impl.h>
33#include <sys/vdev_impl.h>
34#include <sys/zio.h>
93cf2076 35#include <sys/spa_impl.h>
f3a7f661 36#include <sys/zfeature.h>
a1d477c2 37#include <sys/vdev_indirect_mapping.h>
d2734cce 38#include <sys/zap.h>
34dc7c2f 39
d1d7e268 40#define WITH_DF_BLOCK_ALLOCATOR
6d974228 41
3dfb57a3
DB
42#define GANG_ALLOCATION(flags) \
43 ((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER))
22c81dd8 44
e8fe6684
ED
45/*
46 * Metaslab granularity, in bytes. This is roughly similar to what would be
47 * referred to as the "stripe size" in traditional RAID arrays. In normal
48 * operation, we will try to write this amount of data to a top-level vdev
49 * before moving on to the next one.
50 */
99b14de4 51unsigned long metaslab_aliquot = 512 << 10;
e8fe6684 52
d830d479
MA
53/*
54 * For testing, make some blocks above a certain size be gang blocks.
55 */
56unsigned long metaslab_force_ganging = SPA_MAXBLOCKSIZE + 1;
34dc7c2f 57
d2734cce
SD
58/*
59 * Since we can touch multiple metaslabs (and their respective space maps)
60 * with each transaction group, we benefit from having a smaller space map
61 * block size since it allows us to issue more I/O operations scattered
62 * around the disk.
63 */
64int zfs_metaslab_sm_blksz = (1 << 12);
65
e51be066
GW
66/*
67 * The in-core space map representation is more compact than its on-disk form.
68 * The zfs_condense_pct determines how much more compact the in-core
4e21fd06 69 * space map representation must be before we compact it on-disk.
e51be066
GW
70 * Values should be greater than or equal to 100.
71 */
72int zfs_condense_pct = 200;
73
b02fe35d
AR
74/*
75 * Condensing a metaslab is not guaranteed to actually reduce the amount of
76 * space used on disk. In particular, a space map uses data in increments of
96358617 77 * MAX(1 << ashift, space_map_blksz), so a metaslab might use the
b02fe35d
AR
78 * same number of blocks after condensing. Since the goal of condensing is to
79 * reduce the number of IOPs required to read the space map, we only want to
80 * condense when we can be sure we will reduce the number of blocks used by the
81 * space map. Unfortunately, we cannot precisely compute whether or not this is
82 * the case in metaslab_should_condense since we are holding ms_lock. Instead,
83 * we apply the following heuristic: do not condense a spacemap unless the
84 * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
85 * blocks.
86 */
87int zfs_metaslab_condense_block_threshold = 4;
88
ac72fac3
GW
89/*
90 * The zfs_mg_noalloc_threshold defines which metaslab groups should
91 * be eligible for allocation. The value is defined as a percentage of
f3a7f661 92 * free space. Metaslab groups that have more free space than
ac72fac3
GW
93 * zfs_mg_noalloc_threshold are always eligible for allocations. Once
94 * a metaslab group's free space is less than or equal to the
95 * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
96 * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
97 * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
98 * groups are allowed to accept allocations. Gang blocks are always
99 * eligible to allocate on any metaslab group. The default value of 0 means
100 * no metaslab group will be excluded based on this criterion.
101 */
102int zfs_mg_noalloc_threshold = 0;
6d974228 103
f3a7f661
GW
104/*
105 * Metaslab groups are considered eligible for allocations if their
106 * fragmenation metric (measured as a percentage) is less than or equal to
107 * zfs_mg_fragmentation_threshold. If a metaslab group exceeds this threshold
108 * then it will be skipped unless all metaslab groups within the metaslab
109 * class have also crossed this threshold.
110 */
111int zfs_mg_fragmentation_threshold = 85;
112
113/*
114 * Allow metaslabs to keep their active state as long as their fragmentation
115 * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
116 * active metaslab that exceeds this threshold will no longer keep its active
117 * status allowing better metaslabs to be selected.
118 */
119int zfs_metaslab_fragmentation_threshold = 70;
120
428870ff 121/*
aa7d06a9 122 * When set will load all metaslabs when pool is first opened.
428870ff 123 */
aa7d06a9
GW
124int metaslab_debug_load = 0;
125
126/*
127 * When set will prevent metaslabs from being unloaded.
128 */
129int metaslab_debug_unload = 0;
428870ff 130
9babb374
BB
131/*
132 * Minimum size which forces the dynamic allocator to change
428870ff 133 * it's allocation strategy. Once the space map cannot satisfy
9babb374
BB
134 * an allocation of this size then it switches to using more
135 * aggressive strategy (i.e search by size rather than offset).
136 */
4e21fd06 137uint64_t metaslab_df_alloc_threshold = SPA_OLD_MAXBLOCKSIZE;
9babb374
BB
138
139/*
140 * The minimum free space, in percent, which must be available
141 * in a space map to continue allocations in a first-fit fashion.
4e21fd06 142 * Once the space map's free space drops below this level we dynamically
9babb374
BB
143 * switch to using best-fit allocations.
144 */
428870ff
BB
145int metaslab_df_free_pct = 4;
146
428870ff 147/*
93cf2076 148 * Percentage of all cpus that can be used by the metaslab taskq.
428870ff 149 */
93cf2076 150int metaslab_load_pct = 50;
428870ff
BB
151
152/*
93cf2076
GW
153 * Determines how many txgs a metaslab may remain loaded without having any
154 * allocations from it. As long as a metaslab continues to be used we will
155 * keep it loaded.
428870ff 156 */
93cf2076 157int metaslab_unload_delay = TXG_SIZE * 2;
9babb374 158
93cf2076
GW
159/*
160 * Max number of metaslabs per group to preload.
161 */
162int metaslab_preload_limit = SPA_DVAS_PER_BP;
163
164/*
165 * Enable/disable preloading of metaslab.
166 */
f3a7f661 167int metaslab_preload_enabled = B_TRUE;
93cf2076
GW
168
169/*
f3a7f661 170 * Enable/disable fragmentation weighting on metaslabs.
93cf2076 171 */
f3a7f661 172int metaslab_fragmentation_factor_enabled = B_TRUE;
93cf2076 173
f3a7f661
GW
174/*
175 * Enable/disable lba weighting (i.e. outer tracks are given preference).
176 */
177int metaslab_lba_weighting_enabled = B_TRUE;
178
179/*
180 * Enable/disable metaslab group biasing.
181 */
182int metaslab_bias_enabled = B_TRUE;
183
a1d477c2
MA
184/*
185 * Enable/disable remapping of indirect DVAs to their concrete vdevs.
186 */
187boolean_t zfs_remap_blkptr_enable = B_TRUE;
188
4e21fd06
DB
189/*
190 * Enable/disable segment-based metaslab selection.
191 */
192int zfs_metaslab_segment_weight_enabled = B_TRUE;
193
194/*
195 * When using segment-based metaslab selection, we will continue
196 * allocating from the active metaslab until we have exhausted
197 * zfs_metaslab_switch_threshold of its buckets.
198 */
199int zfs_metaslab_switch_threshold = 2;
200
201/*
202 * Internal switch to enable/disable the metaslab allocation tracing
203 * facility.
204 */
205#ifdef _METASLAB_TRACING
206boolean_t metaslab_trace_enabled = B_TRUE;
207#endif
208
209/*
210 * Maximum entries that the metaslab allocation tracing facility will keep
211 * in a given list when running in non-debug mode. We limit the number
212 * of entries in non-debug mode to prevent us from using up too much memory.
213 * The limit should be sufficiently large that we don't expect any allocation
214 * to every exceed this value. In debug mode, the system will panic if this
215 * limit is ever reached allowing for further investigation.
216 */
217#ifdef _METASLAB_TRACING
218uint64_t metaslab_trace_max_entries = 5000;
219#endif
220
1b939560
BB
221/*
222 * Maximum number of metaslabs per group that can be disabled
223 * simultaneously.
224 */
225int max_disabled_ms = 3;
226
4e21fd06
DB
227static uint64_t metaslab_weight(metaslab_t *);
228static void metaslab_set_fragmentation(metaslab_t *);
d2734cce 229static void metaslab_free_impl(vdev_t *, uint64_t, uint64_t, boolean_t);
a1d477c2 230static void metaslab_check_free_impl(vdev_t *, uint64_t, uint64_t);
4e21fd06 231
492f64e9
PD
232static void metaslab_passivate(metaslab_t *msp, uint64_t weight);
233static uint64_t metaslab_weight_from_range_tree(metaslab_t *msp);
4e21fd06
DB
234#ifdef _METASLAB_TRACING
235kmem_cache_t *metaslab_alloc_trace_cache;
236#endif
93cf2076 237
34dc7c2f
BB
238/*
239 * ==========================================================================
240 * Metaslab classes
241 * ==========================================================================
242 */
243metaslab_class_t *
93cf2076 244metaslab_class_create(spa_t *spa, metaslab_ops_t *ops)
34dc7c2f
BB
245{
246 metaslab_class_t *mc;
247
79c76d5b 248 mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
34dc7c2f 249
428870ff 250 mc->mc_spa = spa;
34dc7c2f 251 mc->mc_rotor = NULL;
9babb374 252 mc->mc_ops = ops;
3dfb57a3 253 mutex_init(&mc->mc_lock, NULL, MUTEX_DEFAULT, NULL);
492f64e9 254 mc->mc_alloc_slots = kmem_zalloc(spa->spa_alloc_count *
c13060e4 255 sizeof (zfs_refcount_t), KM_SLEEP);
492f64e9
PD
256 mc->mc_alloc_max_slots = kmem_zalloc(spa->spa_alloc_count *
257 sizeof (uint64_t), KM_SLEEP);
258 for (int i = 0; i < spa->spa_alloc_count; i++)
424fd7c3 259 zfs_refcount_create_tracked(&mc->mc_alloc_slots[i]);
34dc7c2f
BB
260
261 return (mc);
262}
263
264void
265metaslab_class_destroy(metaslab_class_t *mc)
266{
428870ff
BB
267 ASSERT(mc->mc_rotor == NULL);
268 ASSERT(mc->mc_alloc == 0);
269 ASSERT(mc->mc_deferred == 0);
270 ASSERT(mc->mc_space == 0);
271 ASSERT(mc->mc_dspace == 0);
34dc7c2f 272
492f64e9 273 for (int i = 0; i < mc->mc_spa->spa_alloc_count; i++)
424fd7c3 274 zfs_refcount_destroy(&mc->mc_alloc_slots[i]);
492f64e9 275 kmem_free(mc->mc_alloc_slots, mc->mc_spa->spa_alloc_count *
c13060e4 276 sizeof (zfs_refcount_t));
492f64e9
PD
277 kmem_free(mc->mc_alloc_max_slots, mc->mc_spa->spa_alloc_count *
278 sizeof (uint64_t));
3dfb57a3 279 mutex_destroy(&mc->mc_lock);
34dc7c2f
BB
280 kmem_free(mc, sizeof (metaslab_class_t));
281}
282
428870ff
BB
283int
284metaslab_class_validate(metaslab_class_t *mc)
34dc7c2f 285{
428870ff
BB
286 metaslab_group_t *mg;
287 vdev_t *vd;
34dc7c2f 288
428870ff
BB
289 /*
290 * Must hold one of the spa_config locks.
291 */
292 ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
293 spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
34dc7c2f 294
428870ff
BB
295 if ((mg = mc->mc_rotor) == NULL)
296 return (0);
297
298 do {
299 vd = mg->mg_vd;
300 ASSERT(vd->vdev_mg != NULL);
301 ASSERT3P(vd->vdev_top, ==, vd);
302 ASSERT3P(mg->mg_class, ==, mc);
303 ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
304 } while ((mg = mg->mg_next) != mc->mc_rotor);
305
306 return (0);
34dc7c2f
BB
307}
308
cc99f275 309static void
428870ff
BB
310metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
311 int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
34dc7c2f 312{
428870ff
BB
313 atomic_add_64(&mc->mc_alloc, alloc_delta);
314 atomic_add_64(&mc->mc_deferred, defer_delta);
315 atomic_add_64(&mc->mc_space, space_delta);
316 atomic_add_64(&mc->mc_dspace, dspace_delta);
317}
34dc7c2f 318
428870ff
BB
319uint64_t
320metaslab_class_get_alloc(metaslab_class_t *mc)
321{
322 return (mc->mc_alloc);
323}
34dc7c2f 324
428870ff
BB
325uint64_t
326metaslab_class_get_deferred(metaslab_class_t *mc)
327{
328 return (mc->mc_deferred);
329}
34dc7c2f 330
428870ff
BB
331uint64_t
332metaslab_class_get_space(metaslab_class_t *mc)
333{
334 return (mc->mc_space);
335}
34dc7c2f 336
428870ff
BB
337uint64_t
338metaslab_class_get_dspace(metaslab_class_t *mc)
339{
340 return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
34dc7c2f
BB
341}
342
f3a7f661
GW
343void
344metaslab_class_histogram_verify(metaslab_class_t *mc)
345{
cc99f275
DB
346 spa_t *spa = mc->mc_spa;
347 vdev_t *rvd = spa->spa_root_vdev;
f3a7f661 348 uint64_t *mc_hist;
1c27024e 349 int i;
f3a7f661
GW
350
351 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
352 return;
353
354 mc_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
79c76d5b 355 KM_SLEEP);
f3a7f661 356
1c27024e 357 for (int c = 0; c < rvd->vdev_children; c++) {
f3a7f661
GW
358 vdev_t *tvd = rvd->vdev_child[c];
359 metaslab_group_t *mg = tvd->vdev_mg;
360
361 /*
362 * Skip any holes, uninitialized top-levels, or
363 * vdevs that are not in this metalab class.
364 */
a1d477c2 365 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
f3a7f661
GW
366 mg->mg_class != mc) {
367 continue;
368 }
369
370 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
371 mc_hist[i] += mg->mg_histogram[i];
372 }
373
374 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
375 VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
376
377 kmem_free(mc_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
378}
379
380/*
381 * Calculate the metaslab class's fragmentation metric. The metric
382 * is weighted based on the space contribution of each metaslab group.
383 * The return value will be a number between 0 and 100 (inclusive), or
384 * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
385 * zfs_frag_table for more information about the metric.
386 */
387uint64_t
388metaslab_class_fragmentation(metaslab_class_t *mc)
389{
390 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
391 uint64_t fragmentation = 0;
f3a7f661
GW
392
393 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
394
1c27024e 395 for (int c = 0; c < rvd->vdev_children; c++) {
f3a7f661
GW
396 vdev_t *tvd = rvd->vdev_child[c];
397 metaslab_group_t *mg = tvd->vdev_mg;
398
399 /*
a1d477c2
MA
400 * Skip any holes, uninitialized top-levels,
401 * or vdevs that are not in this metalab class.
f3a7f661 402 */
a1d477c2 403 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
f3a7f661
GW
404 mg->mg_class != mc) {
405 continue;
406 }
407
408 /*
409 * If a metaslab group does not contain a fragmentation
410 * metric then just bail out.
411 */
412 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
413 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
414 return (ZFS_FRAG_INVALID);
415 }
416
417 /*
418 * Determine how much this metaslab_group is contributing
419 * to the overall pool fragmentation metric.
420 */
421 fragmentation += mg->mg_fragmentation *
422 metaslab_group_get_space(mg);
423 }
424 fragmentation /= metaslab_class_get_space(mc);
425
426 ASSERT3U(fragmentation, <=, 100);
427 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
428 return (fragmentation);
429}
430
431/*
432 * Calculate the amount of expandable space that is available in
433 * this metaslab class. If a device is expanded then its expandable
434 * space will be the amount of allocatable space that is currently not
435 * part of this metaslab class.
436 */
437uint64_t
438metaslab_class_expandable_space(metaslab_class_t *mc)
439{
440 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
441 uint64_t space = 0;
f3a7f661
GW
442
443 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
1c27024e 444 for (int c = 0; c < rvd->vdev_children; c++) {
f3a7f661
GW
445 vdev_t *tvd = rvd->vdev_child[c];
446 metaslab_group_t *mg = tvd->vdev_mg;
447
a1d477c2 448 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
f3a7f661
GW
449 mg->mg_class != mc) {
450 continue;
451 }
452
0f676dc2
GM
453 /*
454 * Calculate if we have enough space to add additional
455 * metaslabs. We report the expandable space in terms
456 * of the metaslab size since that's the unit of expansion.
457 */
458 space += P2ALIGN(tvd->vdev_max_asize - tvd->vdev_asize,
459 1ULL << tvd->vdev_ms_shift);
f3a7f661
GW
460 }
461 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
462 return (space);
463}
464
34dc7c2f
BB
465static int
466metaslab_compare(const void *x1, const void *x2)
467{
ee36c709
GN
468 const metaslab_t *m1 = (const metaslab_t *)x1;
469 const metaslab_t *m2 = (const metaslab_t *)x2;
34dc7c2f 470
492f64e9
PD
471 int sort1 = 0;
472 int sort2 = 0;
473 if (m1->ms_allocator != -1 && m1->ms_primary)
474 sort1 = 1;
475 else if (m1->ms_allocator != -1 && !m1->ms_primary)
476 sort1 = 2;
477 if (m2->ms_allocator != -1 && m2->ms_primary)
478 sort2 = 1;
479 else if (m2->ms_allocator != -1 && !m2->ms_primary)
480 sort2 = 2;
481
482 /*
483 * Sort inactive metaslabs first, then primaries, then secondaries. When
484 * selecting a metaslab to allocate from, an allocator first tries its
485 * primary, then secondary active metaslab. If it doesn't have active
486 * metaslabs, or can't allocate from them, it searches for an inactive
487 * metaslab to activate. If it can't find a suitable one, it will steal
488 * a primary or secondary metaslab from another allocator.
489 */
490 if (sort1 < sort2)
491 return (-1);
492 if (sort1 > sort2)
493 return (1);
494
ee36c709
GN
495 int cmp = AVL_CMP(m2->ms_weight, m1->ms_weight);
496 if (likely(cmp))
497 return (cmp);
34dc7c2f 498
ee36c709 499 IMPLY(AVL_CMP(m1->ms_start, m2->ms_start) == 0, m1 == m2);
34dc7c2f 500
ee36c709 501 return (AVL_CMP(m1->ms_start, m2->ms_start));
34dc7c2f
BB
502}
503
425d3237
SD
504uint64_t
505metaslab_allocated_space(metaslab_t *msp)
506{
507 return (msp->ms_allocated_space);
508}
509
4e21fd06
DB
510/*
511 * Verify that the space accounting on disk matches the in-core range_trees.
512 */
425d3237 513static void
4e21fd06
DB
514metaslab_verify_space(metaslab_t *msp, uint64_t txg)
515{
516 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
425d3237 517 uint64_t allocating = 0;
4e21fd06 518 uint64_t sm_free_space, msp_free_space;
4e21fd06
DB
519
520 ASSERT(MUTEX_HELD(&msp->ms_lock));
425d3237 521 ASSERT(!msp->ms_condensing);
4e21fd06
DB
522
523 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
524 return;
525
526 /*
527 * We can only verify the metaslab space when we're called
425d3237
SD
528 * from syncing context with a loaded metaslab that has an
529 * allocated space map. Calling this in non-syncing context
530 * does not provide a consistent view of the metaslab since
531 * we're performing allocations in the future.
4e21fd06
DB
532 */
533 if (txg != spa_syncing_txg(spa) || msp->ms_sm == NULL ||
534 !msp->ms_loaded)
535 return;
536
425d3237
SD
537 /*
538 * Even though the smp_alloc field can get negative (e.g.
539 * see vdev_checkpoint_sm), that should never be the case
540 * when it come's to a metaslab's space map.
541 */
542 ASSERT3S(space_map_allocated(msp->ms_sm), >=, 0);
543
544 sm_free_space = msp->ms_size - metaslab_allocated_space(msp);
4e21fd06
DB
545
546 /*
425d3237
SD
547 * Account for future allocations since we would have
548 * already deducted that space from the ms_allocatable.
4e21fd06 549 */
1c27024e 550 for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
425d3237 551 allocating +=
d2734cce 552 range_tree_space(msp->ms_allocating[(txg + t) & TXG_MASK]);
4e21fd06 553 }
4e21fd06 554
425d3237
SD
555 ASSERT3U(msp->ms_deferspace, ==,
556 range_tree_space(msp->ms_defer[0]) +
557 range_tree_space(msp->ms_defer[1]));
558
559 msp_free_space = range_tree_space(msp->ms_allocatable) + allocating +
d2734cce 560 msp->ms_deferspace + range_tree_space(msp->ms_freed);
4e21fd06
DB
561
562 VERIFY3U(sm_free_space, ==, msp_free_space);
563}
564
565/*
566 * ==========================================================================
567 * Metaslab groups
568 * ==========================================================================
569 */
ac72fac3
GW
570/*
571 * Update the allocatable flag and the metaslab group's capacity.
572 * The allocatable flag is set to true if the capacity is below
3dfb57a3
DB
573 * the zfs_mg_noalloc_threshold or has a fragmentation value that is
574 * greater than zfs_mg_fragmentation_threshold. If a metaslab group
575 * transitions from allocatable to non-allocatable or vice versa then the
576 * metaslab group's class is updated to reflect the transition.
ac72fac3
GW
577 */
578static void
579metaslab_group_alloc_update(metaslab_group_t *mg)
580{
581 vdev_t *vd = mg->mg_vd;
582 metaslab_class_t *mc = mg->mg_class;
583 vdev_stat_t *vs = &vd->vdev_stat;
584 boolean_t was_allocatable;
3dfb57a3 585 boolean_t was_initialized;
ac72fac3
GW
586
587 ASSERT(vd == vd->vdev_top);
a1d477c2
MA
588 ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_READER), ==,
589 SCL_ALLOC);
ac72fac3
GW
590
591 mutex_enter(&mg->mg_lock);
592 was_allocatable = mg->mg_allocatable;
3dfb57a3 593 was_initialized = mg->mg_initialized;
ac72fac3
GW
594
595 mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
596 (vs->vs_space + 1);
597
3dfb57a3
DB
598 mutex_enter(&mc->mc_lock);
599
600 /*
601 * If the metaslab group was just added then it won't
602 * have any space until we finish syncing out this txg.
603 * At that point we will consider it initialized and available
604 * for allocations. We also don't consider non-activated
605 * metaslab groups (e.g. vdevs that are in the middle of being removed)
606 * to be initialized, because they can't be used for allocation.
607 */
608 mg->mg_initialized = metaslab_group_initialized(mg);
609 if (!was_initialized && mg->mg_initialized) {
610 mc->mc_groups++;
611 } else if (was_initialized && !mg->mg_initialized) {
612 ASSERT3U(mc->mc_groups, >, 0);
613 mc->mc_groups--;
614 }
615 if (mg->mg_initialized)
616 mg->mg_no_free_space = B_FALSE;
617
f3a7f661
GW
618 /*
619 * A metaslab group is considered allocatable if it has plenty
620 * of free space or is not heavily fragmented. We only take
621 * fragmentation into account if the metaslab group has a valid
622 * fragmentation metric (i.e. a value between 0 and 100).
623 */
3dfb57a3
DB
624 mg->mg_allocatable = (mg->mg_activation_count > 0 &&
625 mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
f3a7f661
GW
626 (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
627 mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
ac72fac3
GW
628
629 /*
630 * The mc_alloc_groups maintains a count of the number of
631 * groups in this metaslab class that are still above the
632 * zfs_mg_noalloc_threshold. This is used by the allocating
633 * threads to determine if they should avoid allocations to
634 * a given group. The allocator will avoid allocations to a group
635 * if that group has reached or is below the zfs_mg_noalloc_threshold
636 * and there are still other groups that are above the threshold.
637 * When a group transitions from allocatable to non-allocatable or
638 * vice versa we update the metaslab class to reflect that change.
639 * When the mc_alloc_groups value drops to 0 that means that all
640 * groups have reached the zfs_mg_noalloc_threshold making all groups
641 * eligible for allocations. This effectively means that all devices
642 * are balanced again.
643 */
644 if (was_allocatable && !mg->mg_allocatable)
645 mc->mc_alloc_groups--;
646 else if (!was_allocatable && mg->mg_allocatable)
647 mc->mc_alloc_groups++;
3dfb57a3 648 mutex_exit(&mc->mc_lock);
f3a7f661 649
ac72fac3
GW
650 mutex_exit(&mg->mg_lock);
651}
652
34dc7c2f 653metaslab_group_t *
492f64e9 654metaslab_group_create(metaslab_class_t *mc, vdev_t *vd, int allocators)
34dc7c2f
BB
655{
656 metaslab_group_t *mg;
657
79c76d5b 658 mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
34dc7c2f 659 mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
1b939560
BB
660 mutex_init(&mg->mg_ms_disabled_lock, NULL, MUTEX_DEFAULT, NULL);
661 cv_init(&mg->mg_ms_disabled_cv, NULL, CV_DEFAULT, NULL);
492f64e9
PD
662 mg->mg_primaries = kmem_zalloc(allocators * sizeof (metaslab_t *),
663 KM_SLEEP);
664 mg->mg_secondaries = kmem_zalloc(allocators * sizeof (metaslab_t *),
665 KM_SLEEP);
34dc7c2f
BB
666 avl_create(&mg->mg_metaslab_tree, metaslab_compare,
667 sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
34dc7c2f 668 mg->mg_vd = vd;
428870ff
BB
669 mg->mg_class = mc;
670 mg->mg_activation_count = 0;
3dfb57a3
DB
671 mg->mg_initialized = B_FALSE;
672 mg->mg_no_free_space = B_TRUE;
492f64e9
PD
673 mg->mg_allocators = allocators;
674
c13060e4
TS
675 mg->mg_alloc_queue_depth = kmem_zalloc(allocators *
676 sizeof (zfs_refcount_t), KM_SLEEP);
492f64e9
PD
677 mg->mg_cur_max_alloc_queue_depth = kmem_zalloc(allocators *
678 sizeof (uint64_t), KM_SLEEP);
679 for (int i = 0; i < allocators; i++) {
424fd7c3 680 zfs_refcount_create_tracked(&mg->mg_alloc_queue_depth[i]);
492f64e9
PD
681 mg->mg_cur_max_alloc_queue_depth[i] = 0;
682 }
34dc7c2f 683
3c51c5cb 684 mg->mg_taskq = taskq_create("metaslab_group_taskq", metaslab_load_pct,
1229323d 685 maxclsyspri, 10, INT_MAX, TASKQ_THREADS_CPU_PCT | TASKQ_DYNAMIC);
93cf2076 686
34dc7c2f
BB
687 return (mg);
688}
689
690void
691metaslab_group_destroy(metaslab_group_t *mg)
692{
428870ff
BB
693 ASSERT(mg->mg_prev == NULL);
694 ASSERT(mg->mg_next == NULL);
695 /*
696 * We may have gone below zero with the activation count
697 * either because we never activated in the first place or
698 * because we're done, and possibly removing the vdev.
699 */
700 ASSERT(mg->mg_activation_count <= 0);
701
3c51c5cb 702 taskq_destroy(mg->mg_taskq);
34dc7c2f 703 avl_destroy(&mg->mg_metaslab_tree);
492f64e9
PD
704 kmem_free(mg->mg_primaries, mg->mg_allocators * sizeof (metaslab_t *));
705 kmem_free(mg->mg_secondaries, mg->mg_allocators *
706 sizeof (metaslab_t *));
34dc7c2f 707 mutex_destroy(&mg->mg_lock);
1b939560
BB
708 mutex_destroy(&mg->mg_ms_disabled_lock);
709 cv_destroy(&mg->mg_ms_disabled_cv);
492f64e9
PD
710
711 for (int i = 0; i < mg->mg_allocators; i++) {
424fd7c3 712 zfs_refcount_destroy(&mg->mg_alloc_queue_depth[i]);
492f64e9
PD
713 mg->mg_cur_max_alloc_queue_depth[i] = 0;
714 }
715 kmem_free(mg->mg_alloc_queue_depth, mg->mg_allocators *
c13060e4 716 sizeof (zfs_refcount_t));
492f64e9
PD
717 kmem_free(mg->mg_cur_max_alloc_queue_depth, mg->mg_allocators *
718 sizeof (uint64_t));
719
34dc7c2f
BB
720 kmem_free(mg, sizeof (metaslab_group_t));
721}
722
428870ff
BB
723void
724metaslab_group_activate(metaslab_group_t *mg)
725{
726 metaslab_class_t *mc = mg->mg_class;
727 metaslab_group_t *mgprev, *mgnext;
728
a1d477c2 729 ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER), !=, 0);
428870ff
BB
730
731 ASSERT(mc->mc_rotor != mg);
732 ASSERT(mg->mg_prev == NULL);
733 ASSERT(mg->mg_next == NULL);
734 ASSERT(mg->mg_activation_count <= 0);
735
736 if (++mg->mg_activation_count <= 0)
737 return;
738
739 mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
ac72fac3 740 metaslab_group_alloc_update(mg);
428870ff
BB
741
742 if ((mgprev = mc->mc_rotor) == NULL) {
743 mg->mg_prev = mg;
744 mg->mg_next = mg;
745 } else {
746 mgnext = mgprev->mg_next;
747 mg->mg_prev = mgprev;
748 mg->mg_next = mgnext;
749 mgprev->mg_next = mg;
750 mgnext->mg_prev = mg;
751 }
752 mc->mc_rotor = mg;
753}
754
a1d477c2
MA
755/*
756 * Passivate a metaslab group and remove it from the allocation rotor.
757 * Callers must hold both the SCL_ALLOC and SCL_ZIO lock prior to passivating
758 * a metaslab group. This function will momentarily drop spa_config_locks
759 * that are lower than the SCL_ALLOC lock (see comment below).
760 */
428870ff
BB
761void
762metaslab_group_passivate(metaslab_group_t *mg)
763{
764 metaslab_class_t *mc = mg->mg_class;
a1d477c2 765 spa_t *spa = mc->mc_spa;
428870ff 766 metaslab_group_t *mgprev, *mgnext;
a1d477c2 767 int locks = spa_config_held(spa, SCL_ALL, RW_WRITER);
428870ff 768
a1d477c2
MA
769 ASSERT3U(spa_config_held(spa, SCL_ALLOC | SCL_ZIO, RW_WRITER), ==,
770 (SCL_ALLOC | SCL_ZIO));
428870ff
BB
771
772 if (--mg->mg_activation_count != 0) {
773 ASSERT(mc->mc_rotor != mg);
774 ASSERT(mg->mg_prev == NULL);
775 ASSERT(mg->mg_next == NULL);
776 ASSERT(mg->mg_activation_count < 0);
777 return;
778 }
779
a1d477c2
MA
780 /*
781 * The spa_config_lock is an array of rwlocks, ordered as
782 * follows (from highest to lowest):
783 * SCL_CONFIG > SCL_STATE > SCL_L2ARC > SCL_ALLOC >
784 * SCL_ZIO > SCL_FREE > SCL_VDEV
785 * (For more information about the spa_config_lock see spa_misc.c)
786 * The higher the lock, the broader its coverage. When we passivate
787 * a metaslab group, we must hold both the SCL_ALLOC and the SCL_ZIO
788 * config locks. However, the metaslab group's taskq might be trying
789 * to preload metaslabs so we must drop the SCL_ZIO lock and any
790 * lower locks to allow the I/O to complete. At a minimum,
791 * we continue to hold the SCL_ALLOC lock, which prevents any future
792 * allocations from taking place and any changes to the vdev tree.
793 */
794 spa_config_exit(spa, locks & ~(SCL_ZIO - 1), spa);
c5528b9b 795 taskq_wait_outstanding(mg->mg_taskq, 0);
a1d477c2 796 spa_config_enter(spa, locks & ~(SCL_ZIO - 1), spa, RW_WRITER);
f3a7f661 797 metaslab_group_alloc_update(mg);
492f64e9
PD
798 for (int i = 0; i < mg->mg_allocators; i++) {
799 metaslab_t *msp = mg->mg_primaries[i];
800 if (msp != NULL) {
801 mutex_enter(&msp->ms_lock);
802 metaslab_passivate(msp,
803 metaslab_weight_from_range_tree(msp));
804 mutex_exit(&msp->ms_lock);
805 }
806 msp = mg->mg_secondaries[i];
807 if (msp != NULL) {
808 mutex_enter(&msp->ms_lock);
809 metaslab_passivate(msp,
810 metaslab_weight_from_range_tree(msp));
811 mutex_exit(&msp->ms_lock);
812 }
813 }
93cf2076 814
428870ff
BB
815 mgprev = mg->mg_prev;
816 mgnext = mg->mg_next;
817
818 if (mg == mgnext) {
819 mc->mc_rotor = NULL;
820 } else {
821 mc->mc_rotor = mgnext;
822 mgprev->mg_next = mgnext;
823 mgnext->mg_prev = mgprev;
824 }
825
826 mg->mg_prev = NULL;
827 mg->mg_next = NULL;
828}
829
3dfb57a3
DB
830boolean_t
831metaslab_group_initialized(metaslab_group_t *mg)
832{
833 vdev_t *vd = mg->mg_vd;
834 vdev_stat_t *vs = &vd->vdev_stat;
835
836 return (vs->vs_space != 0 && mg->mg_activation_count > 0);
837}
838
f3a7f661
GW
839uint64_t
840metaslab_group_get_space(metaslab_group_t *mg)
841{
842 return ((1ULL << mg->mg_vd->vdev_ms_shift) * mg->mg_vd->vdev_ms_count);
843}
844
845void
846metaslab_group_histogram_verify(metaslab_group_t *mg)
847{
848 uint64_t *mg_hist;
849 vdev_t *vd = mg->mg_vd;
850 uint64_t ashift = vd->vdev_ashift;
1c27024e 851 int i;
f3a7f661
GW
852
853 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
854 return;
855
856 mg_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
79c76d5b 857 KM_SLEEP);
f3a7f661
GW
858
859 ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE, >=,
860 SPACE_MAP_HISTOGRAM_SIZE + ashift);
861
1c27024e 862 for (int m = 0; m < vd->vdev_ms_count; m++) {
f3a7f661 863 metaslab_t *msp = vd->vdev_ms[m];
928e8ad4 864 ASSERT(msp != NULL);
f3a7f661 865
cc99f275
DB
866 /* skip if not active or not a member */
867 if (msp->ms_sm == NULL || msp->ms_group != mg)
f3a7f661
GW
868 continue;
869
870 for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
871 mg_hist[i + ashift] +=
872 msp->ms_sm->sm_phys->smp_histogram[i];
873 }
874
875 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i ++)
876 VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
877
878 kmem_free(mg_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
879}
880
34dc7c2f 881static void
f3a7f661 882metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
34dc7c2f 883{
f3a7f661
GW
884 metaslab_class_t *mc = mg->mg_class;
885 uint64_t ashift = mg->mg_vd->vdev_ashift;
f3a7f661
GW
886
887 ASSERT(MUTEX_HELD(&msp->ms_lock));
888 if (msp->ms_sm == NULL)
889 return;
890
34dc7c2f 891 mutex_enter(&mg->mg_lock);
1c27024e 892 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
f3a7f661
GW
893 mg->mg_histogram[i + ashift] +=
894 msp->ms_sm->sm_phys->smp_histogram[i];
895 mc->mc_histogram[i + ashift] +=
896 msp->ms_sm->sm_phys->smp_histogram[i];
897 }
898 mutex_exit(&mg->mg_lock);
899}
900
901void
902metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
903{
904 metaslab_class_t *mc = mg->mg_class;
905 uint64_t ashift = mg->mg_vd->vdev_ashift;
f3a7f661
GW
906
907 ASSERT(MUTEX_HELD(&msp->ms_lock));
908 if (msp->ms_sm == NULL)
909 return;
910
911 mutex_enter(&mg->mg_lock);
1c27024e 912 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
f3a7f661
GW
913 ASSERT3U(mg->mg_histogram[i + ashift], >=,
914 msp->ms_sm->sm_phys->smp_histogram[i]);
915 ASSERT3U(mc->mc_histogram[i + ashift], >=,
916 msp->ms_sm->sm_phys->smp_histogram[i]);
917
918 mg->mg_histogram[i + ashift] -=
919 msp->ms_sm->sm_phys->smp_histogram[i];
920 mc->mc_histogram[i + ashift] -=
921 msp->ms_sm->sm_phys->smp_histogram[i];
922 }
923 mutex_exit(&mg->mg_lock);
924}
925
926static void
927metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
928{
34dc7c2f 929 ASSERT(msp->ms_group == NULL);
f3a7f661 930 mutex_enter(&mg->mg_lock);
34dc7c2f
BB
931 msp->ms_group = mg;
932 msp->ms_weight = 0;
933 avl_add(&mg->mg_metaslab_tree, msp);
934 mutex_exit(&mg->mg_lock);
f3a7f661
GW
935
936 mutex_enter(&msp->ms_lock);
937 metaslab_group_histogram_add(mg, msp);
938 mutex_exit(&msp->ms_lock);
34dc7c2f
BB
939}
940
941static void
942metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
943{
f3a7f661
GW
944 mutex_enter(&msp->ms_lock);
945 metaslab_group_histogram_remove(mg, msp);
946 mutex_exit(&msp->ms_lock);
947
34dc7c2f
BB
948 mutex_enter(&mg->mg_lock);
949 ASSERT(msp->ms_group == mg);
950 avl_remove(&mg->mg_metaslab_tree, msp);
951 msp->ms_group = NULL;
952 mutex_exit(&mg->mg_lock);
953}
954
492f64e9
PD
955static void
956metaslab_group_sort_impl(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
957{
958 ASSERT(MUTEX_HELD(&mg->mg_lock));
959 ASSERT(msp->ms_group == mg);
960 avl_remove(&mg->mg_metaslab_tree, msp);
961 msp->ms_weight = weight;
962 avl_add(&mg->mg_metaslab_tree, msp);
963
964}
965
34dc7c2f
BB
966static void
967metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
968{
969 /*
970 * Although in principle the weight can be any value, in
f3a7f661 971 * practice we do not use values in the range [1, 511].
34dc7c2f 972 */
f3a7f661 973 ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
34dc7c2f
BB
974 ASSERT(MUTEX_HELD(&msp->ms_lock));
975
976 mutex_enter(&mg->mg_lock);
492f64e9 977 metaslab_group_sort_impl(mg, msp, weight);
34dc7c2f
BB
978 mutex_exit(&mg->mg_lock);
979}
980
f3a7f661
GW
981/*
982 * Calculate the fragmentation for a given metaslab group. We can use
983 * a simple average here since all metaslabs within the group must have
984 * the same size. The return value will be a value between 0 and 100
985 * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
986 * group have a fragmentation metric.
987 */
988uint64_t
989metaslab_group_fragmentation(metaslab_group_t *mg)
990{
991 vdev_t *vd = mg->mg_vd;
992 uint64_t fragmentation = 0;
993 uint64_t valid_ms = 0;
f3a7f661 994
1c27024e 995 for (int m = 0; m < vd->vdev_ms_count; m++) {
f3a7f661
GW
996 metaslab_t *msp = vd->vdev_ms[m];
997
998 if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
999 continue;
cc99f275
DB
1000 if (msp->ms_group != mg)
1001 continue;
f3a7f661
GW
1002
1003 valid_ms++;
1004 fragmentation += msp->ms_fragmentation;
1005 }
1006
cc99f275 1007 if (valid_ms <= mg->mg_vd->vdev_ms_count / 2)
f3a7f661
GW
1008 return (ZFS_FRAG_INVALID);
1009
1010 fragmentation /= valid_ms;
1011 ASSERT3U(fragmentation, <=, 100);
1012 return (fragmentation);
1013}
1014
ac72fac3
GW
1015/*
1016 * Determine if a given metaslab group should skip allocations. A metaslab
f3a7f661
GW
1017 * group should avoid allocations if its free capacity is less than the
1018 * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
1019 * zfs_mg_fragmentation_threshold and there is at least one metaslab group
3dfb57a3
DB
1020 * that can still handle allocations. If the allocation throttle is enabled
1021 * then we skip allocations to devices that have reached their maximum
1022 * allocation queue depth unless the selected metaslab group is the only
1023 * eligible group remaining.
ac72fac3
GW
1024 */
1025static boolean_t
3dfb57a3 1026metaslab_group_allocatable(metaslab_group_t *mg, metaslab_group_t *rotor,
c197a77c 1027 uint64_t psize, int allocator, int d)
ac72fac3 1028{
3dfb57a3 1029 spa_t *spa = mg->mg_vd->vdev_spa;
ac72fac3
GW
1030 metaslab_class_t *mc = mg->mg_class;
1031
1032 /*
3dfb57a3
DB
1033 * We can only consider skipping this metaslab group if it's
1034 * in the normal metaslab class and there are other metaslab
1035 * groups to select from. Otherwise, we always consider it eligible
f3a7f661 1036 * for allocations.
ac72fac3 1037 */
cc99f275
DB
1038 if ((mc != spa_normal_class(spa) &&
1039 mc != spa_special_class(spa) &&
1040 mc != spa_dedup_class(spa)) ||
1041 mc->mc_groups <= 1)
3dfb57a3
DB
1042 return (B_TRUE);
1043
1044 /*
1045 * If the metaslab group's mg_allocatable flag is set (see comments
1046 * in metaslab_group_alloc_update() for more information) and
1047 * the allocation throttle is disabled then allow allocations to this
1048 * device. However, if the allocation throttle is enabled then
1049 * check if we have reached our allocation limit (mg_alloc_queue_depth)
1050 * to determine if we should allow allocations to this metaslab group.
1051 * If all metaslab groups are no longer considered allocatable
1052 * (mc_alloc_groups == 0) or we're trying to allocate the smallest
1053 * gang block size then we allow allocations on this metaslab group
1054 * regardless of the mg_allocatable or throttle settings.
1055 */
1056 if (mg->mg_allocatable) {
1057 metaslab_group_t *mgp;
1058 int64_t qdepth;
492f64e9 1059 uint64_t qmax = mg->mg_cur_max_alloc_queue_depth[allocator];
3dfb57a3
DB
1060
1061 if (!mc->mc_alloc_throttle_enabled)
1062 return (B_TRUE);
1063
1064 /*
1065 * If this metaslab group does not have any free space, then
1066 * there is no point in looking further.
1067 */
1068 if (mg->mg_no_free_space)
1069 return (B_FALSE);
1070
c197a77c 1071 /*
1072 * Relax allocation throttling for ditto blocks. Due to
1073 * random imbalances in allocation it tends to push copies
1074 * to one vdev, that looks a bit better at the moment.
1075 */
1076 qmax = qmax * (4 + d) / 4;
1077
424fd7c3
TS
1078 qdepth = zfs_refcount_count(
1079 &mg->mg_alloc_queue_depth[allocator]);
3dfb57a3
DB
1080
1081 /*
1082 * If this metaslab group is below its qmax or it's
1083 * the only allocatable metasable group, then attempt
1084 * to allocate from it.
1085 */
1086 if (qdepth < qmax || mc->mc_alloc_groups == 1)
1087 return (B_TRUE);
1088 ASSERT3U(mc->mc_alloc_groups, >, 1);
1089
1090 /*
1091 * Since this metaslab group is at or over its qmax, we
1092 * need to determine if there are metaslab groups after this
1093 * one that might be able to handle this allocation. This is
1094 * racy since we can't hold the locks for all metaslab
1095 * groups at the same time when we make this check.
1096 */
1097 for (mgp = mg->mg_next; mgp != rotor; mgp = mgp->mg_next) {
492f64e9 1098 qmax = mgp->mg_cur_max_alloc_queue_depth[allocator];
c197a77c 1099 qmax = qmax * (4 + d) / 4;
424fd7c3 1100 qdepth = zfs_refcount_count(
492f64e9 1101 &mgp->mg_alloc_queue_depth[allocator]);
3dfb57a3
DB
1102
1103 /*
1104 * If there is another metaslab group that
1105 * might be able to handle the allocation, then
1106 * we return false so that we skip this group.
1107 */
1108 if (qdepth < qmax && !mgp->mg_no_free_space)
1109 return (B_FALSE);
1110 }
1111
1112 /*
1113 * We didn't find another group to handle the allocation
1114 * so we can't skip this metaslab group even though
1115 * we are at or over our qmax.
1116 */
1117 return (B_TRUE);
1118
1119 } else if (mc->mc_alloc_groups == 0 || psize == SPA_MINBLOCKSIZE) {
1120 return (B_TRUE);
1121 }
1122 return (B_FALSE);
ac72fac3
GW
1123}
1124
428870ff
BB
1125/*
1126 * ==========================================================================
93cf2076 1127 * Range tree callbacks
428870ff
BB
1128 * ==========================================================================
1129 */
93cf2076
GW
1130
1131/*
1132 * Comparison function for the private size-ordered tree. Tree is sorted
1133 * by size, larger sizes at the end of the tree.
1134 */
428870ff 1135static int
93cf2076 1136metaslab_rangesize_compare(const void *x1, const void *x2)
428870ff 1137{
93cf2076
GW
1138 const range_seg_t *r1 = x1;
1139 const range_seg_t *r2 = x2;
1140 uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1141 uint64_t rs_size2 = r2->rs_end - r2->rs_start;
428870ff 1142
ee36c709
GN
1143 int cmp = AVL_CMP(rs_size1, rs_size2);
1144 if (likely(cmp))
1145 return (cmp);
428870ff 1146
ee36c709 1147 return (AVL_CMP(r1->rs_start, r2->rs_start));
428870ff
BB
1148}
1149
93cf2076
GW
1150/*
1151 * ==========================================================================
4e21fd06 1152 * Common allocator routines
93cf2076
GW
1153 * ==========================================================================
1154 */
1155
9babb374 1156/*
428870ff 1157 * Return the maximum contiguous segment within the metaslab.
9babb374 1158 */
9babb374 1159uint64_t
93cf2076 1160metaslab_block_maxsize(metaslab_t *msp)
9babb374 1161{
d2734cce 1162 avl_tree_t *t = &msp->ms_allocatable_by_size;
93cf2076 1163 range_seg_t *rs;
9babb374 1164
93cf2076 1165 if (t == NULL || (rs = avl_last(t)) == NULL)
9babb374
BB
1166 return (0ULL);
1167
93cf2076
GW
1168 return (rs->rs_end - rs->rs_start);
1169}
1170
4e21fd06
DB
1171static range_seg_t *
1172metaslab_block_find(avl_tree_t *t, uint64_t start, uint64_t size)
93cf2076 1173{
4e21fd06
DB
1174 range_seg_t *rs, rsearch;
1175 avl_index_t where;
93cf2076 1176
4e21fd06
DB
1177 rsearch.rs_start = start;
1178 rsearch.rs_end = start + size;
93cf2076 1179
4e21fd06
DB
1180 rs = avl_find(t, &rsearch, &where);
1181 if (rs == NULL) {
1182 rs = avl_nearest(t, where, AVL_AFTER);
93cf2076 1183 }
93cf2076 1184
4e21fd06
DB
1185 return (rs);
1186}
93cf2076
GW
1187
1188#if defined(WITH_FF_BLOCK_ALLOCATOR) || \
1189 defined(WITH_DF_BLOCK_ALLOCATOR) || \
1190 defined(WITH_CF_BLOCK_ALLOCATOR)
1191/*
1192 * This is a helper function that can be used by the allocator to find
1193 * a suitable block to allocate. This will search the specified AVL
1194 * tree looking for a block that matches the specified criteria.
1195 */
1196static uint64_t
1197metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
1198 uint64_t align)
1199{
4e21fd06 1200 range_seg_t *rs = metaslab_block_find(t, *cursor, size);
93cf2076
GW
1201
1202 while (rs != NULL) {
1203 uint64_t offset = P2ROUNDUP(rs->rs_start, align);
1204
1205 if (offset + size <= rs->rs_end) {
1206 *cursor = offset + size;
1207 return (offset);
1208 }
1209 rs = AVL_NEXT(t, rs);
1210 }
1211
1212 /*
1213 * If we know we've searched the whole map (*cursor == 0), give up.
1214 * Otherwise, reset the cursor to the beginning and try again.
1215 */
1216 if (*cursor == 0)
1217 return (-1ULL);
1218
1219 *cursor = 0;
1220 return (metaslab_block_picker(t, cursor, size, align));
9babb374 1221}
93cf2076 1222#endif /* WITH_FF/DF/CF_BLOCK_ALLOCATOR */
9babb374 1223
22c81dd8 1224#if defined(WITH_FF_BLOCK_ALLOCATOR)
428870ff
BB
1225/*
1226 * ==========================================================================
1227 * The first-fit block allocator
1228 * ==========================================================================
1229 */
1230static uint64_t
93cf2076 1231metaslab_ff_alloc(metaslab_t *msp, uint64_t size)
9babb374 1232{
93cf2076
GW
1233 /*
1234 * Find the largest power of 2 block size that evenly divides the
1235 * requested size. This is used to try to allocate blocks with similar
1236 * alignment from the same area of the metaslab (i.e. same cursor
1237 * bucket) but it does not guarantee that other allocations sizes
1238 * may exist in the same region.
1239 */
428870ff 1240 uint64_t align = size & -size;
9bd274dd 1241 uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
d2734cce 1242 avl_tree_t *t = &msp->ms_allocatable->rt_root;
9babb374 1243
428870ff 1244 return (metaslab_block_picker(t, cursor, size, align));
9babb374
BB
1245}
1246
93cf2076 1247static metaslab_ops_t metaslab_ff_ops = {
f3a7f661 1248 metaslab_ff_alloc
428870ff 1249};
9babb374 1250
93cf2076 1251metaslab_ops_t *zfs_metaslab_ops = &metaslab_ff_ops;
22c81dd8
BB
1252#endif /* WITH_FF_BLOCK_ALLOCATOR */
1253
1254#if defined(WITH_DF_BLOCK_ALLOCATOR)
428870ff
BB
1255/*
1256 * ==========================================================================
1257 * Dynamic block allocator -
1258 * Uses the first fit allocation scheme until space get low and then
1259 * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
1260 * and metaslab_df_free_pct to determine when to switch the allocation scheme.
1261 * ==========================================================================
1262 */
9babb374 1263static uint64_t
93cf2076 1264metaslab_df_alloc(metaslab_t *msp, uint64_t size)
9babb374 1265{
93cf2076
GW
1266 /*
1267 * Find the largest power of 2 block size that evenly divides the
1268 * requested size. This is used to try to allocate blocks with similar
1269 * alignment from the same area of the metaslab (i.e. same cursor
1270 * bucket) but it does not guarantee that other allocations sizes
1271 * may exist in the same region.
1272 */
9babb374 1273 uint64_t align = size & -size;
9bd274dd 1274 uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
d2734cce 1275 range_tree_t *rt = msp->ms_allocatable;
93cf2076
GW
1276 avl_tree_t *t = &rt->rt_root;
1277 uint64_t max_size = metaslab_block_maxsize(msp);
1278 int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
9babb374 1279
93cf2076 1280 ASSERT(MUTEX_HELD(&msp->ms_lock));
d2734cce
SD
1281 ASSERT3U(avl_numnodes(t), ==,
1282 avl_numnodes(&msp->ms_allocatable_by_size));
9babb374
BB
1283
1284 if (max_size < size)
1285 return (-1ULL);
1286
1287 /*
1288 * If we're running low on space switch to using the size
1289 * sorted AVL tree (best-fit).
1290 */
1291 if (max_size < metaslab_df_alloc_threshold ||
1292 free_pct < metaslab_df_free_pct) {
d2734cce 1293 t = &msp->ms_allocatable_by_size;
9babb374
BB
1294 *cursor = 0;
1295 }
1296
1297 return (metaslab_block_picker(t, cursor, size, 1ULL));
1298}
1299
93cf2076 1300static metaslab_ops_t metaslab_df_ops = {
f3a7f661 1301 metaslab_df_alloc
34dc7c2f
BB
1302};
1303
93cf2076 1304metaslab_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
22c81dd8
BB
1305#endif /* WITH_DF_BLOCK_ALLOCATOR */
1306
93cf2076 1307#if defined(WITH_CF_BLOCK_ALLOCATOR)
428870ff
BB
1308/*
1309 * ==========================================================================
93cf2076
GW
1310 * Cursor fit block allocator -
1311 * Select the largest region in the metaslab, set the cursor to the beginning
1312 * of the range and the cursor_end to the end of the range. As allocations
1313 * are made advance the cursor. Continue allocating from the cursor until
1314 * the range is exhausted and then find a new range.
428870ff
BB
1315 * ==========================================================================
1316 */
1317static uint64_t
93cf2076 1318metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
428870ff 1319{
d2734cce
SD
1320 range_tree_t *rt = msp->ms_allocatable;
1321 avl_tree_t *t = &msp->ms_allocatable_by_size;
93cf2076
GW
1322 uint64_t *cursor = &msp->ms_lbas[0];
1323 uint64_t *cursor_end = &msp->ms_lbas[1];
428870ff
BB
1324 uint64_t offset = 0;
1325
93cf2076
GW
1326 ASSERT(MUTEX_HELD(&msp->ms_lock));
1327 ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&rt->rt_root));
428870ff 1328
93cf2076 1329 ASSERT3U(*cursor_end, >=, *cursor);
428870ff 1330
93cf2076
GW
1331 if ((*cursor + size) > *cursor_end) {
1332 range_seg_t *rs;
428870ff 1333
d2734cce 1334 rs = avl_last(&msp->ms_allocatable_by_size);
93cf2076
GW
1335 if (rs == NULL || (rs->rs_end - rs->rs_start) < size)
1336 return (-1ULL);
428870ff 1337
93cf2076
GW
1338 *cursor = rs->rs_start;
1339 *cursor_end = rs->rs_end;
428870ff 1340 }
93cf2076
GW
1341
1342 offset = *cursor;
1343 *cursor += size;
1344
428870ff
BB
1345 return (offset);
1346}
1347
93cf2076 1348static metaslab_ops_t metaslab_cf_ops = {
f3a7f661 1349 metaslab_cf_alloc
428870ff
BB
1350};
1351
93cf2076
GW
1352metaslab_ops_t *zfs_metaslab_ops = &metaslab_cf_ops;
1353#endif /* WITH_CF_BLOCK_ALLOCATOR */
22c81dd8
BB
1354
1355#if defined(WITH_NDF_BLOCK_ALLOCATOR)
93cf2076
GW
1356/*
1357 * ==========================================================================
1358 * New dynamic fit allocator -
1359 * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1360 * contiguous blocks. If no region is found then just use the largest segment
1361 * that remains.
1362 * ==========================================================================
1363 */
1364
1365/*
1366 * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1367 * to request from the allocator.
1368 */
428870ff
BB
1369uint64_t metaslab_ndf_clump_shift = 4;
1370
1371static uint64_t
93cf2076 1372metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
428870ff 1373{
d2734cce 1374 avl_tree_t *t = &msp->ms_allocatable->rt_root;
428870ff 1375 avl_index_t where;
93cf2076 1376 range_seg_t *rs, rsearch;
9bd274dd 1377 uint64_t hbit = highbit64(size);
93cf2076
GW
1378 uint64_t *cursor = &msp->ms_lbas[hbit - 1];
1379 uint64_t max_size = metaslab_block_maxsize(msp);
428870ff 1380
93cf2076 1381 ASSERT(MUTEX_HELD(&msp->ms_lock));
d2734cce
SD
1382 ASSERT3U(avl_numnodes(t), ==,
1383 avl_numnodes(&msp->ms_allocatable_by_size));
428870ff
BB
1384
1385 if (max_size < size)
1386 return (-1ULL);
1387
93cf2076
GW
1388 rsearch.rs_start = *cursor;
1389 rsearch.rs_end = *cursor + size;
428870ff 1390
93cf2076
GW
1391 rs = avl_find(t, &rsearch, &where);
1392 if (rs == NULL || (rs->rs_end - rs->rs_start) < size) {
d2734cce 1393 t = &msp->ms_allocatable_by_size;
428870ff 1394
93cf2076
GW
1395 rsearch.rs_start = 0;
1396 rsearch.rs_end = MIN(max_size,
428870ff 1397 1ULL << (hbit + metaslab_ndf_clump_shift));
93cf2076
GW
1398 rs = avl_find(t, &rsearch, &where);
1399 if (rs == NULL)
1400 rs = avl_nearest(t, where, AVL_AFTER);
1401 ASSERT(rs != NULL);
428870ff
BB
1402 }
1403
93cf2076
GW
1404 if ((rs->rs_end - rs->rs_start) >= size) {
1405 *cursor = rs->rs_start + size;
1406 return (rs->rs_start);
428870ff
BB
1407 }
1408 return (-1ULL);
1409}
1410
93cf2076 1411static metaslab_ops_t metaslab_ndf_ops = {
f3a7f661 1412 metaslab_ndf_alloc
428870ff
BB
1413};
1414
93cf2076 1415metaslab_ops_t *zfs_metaslab_ops = &metaslab_ndf_ops;
22c81dd8 1416#endif /* WITH_NDF_BLOCK_ALLOCATOR */
9babb374 1417
93cf2076 1418
34dc7c2f
BB
1419/*
1420 * ==========================================================================
1421 * Metaslabs
1422 * ==========================================================================
1423 */
93cf2076 1424
928e8ad4
SD
1425static void
1426metaslab_aux_histograms_clear(metaslab_t *msp)
1427{
1428 /*
1429 * Auxiliary histograms are only cleared when resetting them,
1430 * which can only happen while the metaslab is loaded.
1431 */
1432 ASSERT(msp->ms_loaded);
1433
1434 bzero(msp->ms_synchist, sizeof (msp->ms_synchist));
1435 for (int t = 0; t < TXG_DEFER_SIZE; t++)
1436 bzero(msp->ms_deferhist[t], sizeof (msp->ms_deferhist[t]));
1437}
1438
1439static void
1440metaslab_aux_histogram_add(uint64_t *histogram, uint64_t shift,
1441 range_tree_t *rt)
1442{
1443 /*
1444 * This is modeled after space_map_histogram_add(), so refer to that
1445 * function for implementation details. We want this to work like
1446 * the space map histogram, and not the range tree histogram, as we
1447 * are essentially constructing a delta that will be later subtracted
1448 * from the space map histogram.
1449 */
1450 int idx = 0;
1451 for (int i = shift; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
1452 ASSERT3U(i, >=, idx + shift);
1453 histogram[idx] += rt->rt_histogram[i] << (i - idx - shift);
1454
1455 if (idx < SPACE_MAP_HISTOGRAM_SIZE - 1) {
1456 ASSERT3U(idx + shift, ==, i);
1457 idx++;
1458 ASSERT3U(idx, <, SPACE_MAP_HISTOGRAM_SIZE);
1459 }
1460 }
1461}
1462
1463/*
1464 * Called at every sync pass that the metaslab gets synced.
1465 *
1466 * The reason is that we want our auxiliary histograms to be updated
1467 * wherever the metaslab's space map histogram is updated. This way
1468 * we stay consistent on which parts of the metaslab space map's
1469 * histogram are currently not available for allocations (e.g because
1470 * they are in the defer, freed, and freeing trees).
1471 */
1472static void
1473metaslab_aux_histograms_update(metaslab_t *msp)
1474{
1475 space_map_t *sm = msp->ms_sm;
1476 ASSERT(sm != NULL);
1477
1478 /*
1479 * This is similar to the metaslab's space map histogram updates
1480 * that take place in metaslab_sync(). The only difference is that
1481 * we only care about segments that haven't made it into the
1482 * ms_allocatable tree yet.
1483 */
1484 if (msp->ms_loaded) {
1485 metaslab_aux_histograms_clear(msp);
1486
1487 metaslab_aux_histogram_add(msp->ms_synchist,
1488 sm->sm_shift, msp->ms_freed);
1489
1490 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1491 metaslab_aux_histogram_add(msp->ms_deferhist[t],
1492 sm->sm_shift, msp->ms_defer[t]);
1493 }
1494 }
1495
1496 metaslab_aux_histogram_add(msp->ms_synchist,
1497 sm->sm_shift, msp->ms_freeing);
1498}
1499
1500/*
1501 * Called every time we are done syncing (writing to) the metaslab,
1502 * i.e. at the end of each sync pass.
1503 * [see the comment in metaslab_impl.h for ms_synchist, ms_deferhist]
1504 */
1505static void
1506metaslab_aux_histograms_update_done(metaslab_t *msp, boolean_t defer_allowed)
1507{
1508 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1509 space_map_t *sm = msp->ms_sm;
1510
1511 if (sm == NULL) {
1512 /*
1513 * We came here from metaslab_init() when creating/opening a
1514 * pool, looking at a metaslab that hasn't had any allocations
1515 * yet.
1516 */
1517 return;
1518 }
1519
1520 /*
1521 * This is similar to the actions that we take for the ms_freed
1522 * and ms_defer trees in metaslab_sync_done().
1523 */
1524 uint64_t hist_index = spa_syncing_txg(spa) % TXG_DEFER_SIZE;
1525 if (defer_allowed) {
1526 bcopy(msp->ms_synchist, msp->ms_deferhist[hist_index],
1527 sizeof (msp->ms_synchist));
1528 } else {
1529 bzero(msp->ms_deferhist[hist_index],
1530 sizeof (msp->ms_deferhist[hist_index]));
1531 }
1532 bzero(msp->ms_synchist, sizeof (msp->ms_synchist));
1533}
1534
1535/*
1536 * Ensure that the metaslab's weight and fragmentation are consistent
1537 * with the contents of the histogram (either the range tree's histogram
1538 * or the space map's depending whether the metaslab is loaded).
1539 */
1540static void
1541metaslab_verify_weight_and_frag(metaslab_t *msp)
1542{
1543 ASSERT(MUTEX_HELD(&msp->ms_lock));
1544
1545 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
1546 return;
1547
1548 /* see comment in metaslab_verify_unflushed_changes() */
1549 if (msp->ms_group == NULL)
1550 return;
1551
1552 /*
1553 * Devices being removed always return a weight of 0 and leave
1554 * fragmentation and ms_max_size as is - there is nothing for
1555 * us to verify here.
1556 */
1557 vdev_t *vd = msp->ms_group->mg_vd;
1558 if (vd->vdev_removing)
1559 return;
1560
1561 /*
1562 * If the metaslab is dirty it probably means that we've done
1563 * some allocations or frees that have changed our histograms
1564 * and thus the weight.
1565 */
1566 for (int t = 0; t < TXG_SIZE; t++) {
1567 if (txg_list_member(&vd->vdev_ms_list, msp, t))
1568 return;
1569 }
1570
1571 /*
1572 * This verification checks that our in-memory state is consistent
1573 * with what's on disk. If the pool is read-only then there aren't
1574 * any changes and we just have the initially-loaded state.
1575 */
1576 if (!spa_writeable(msp->ms_group->mg_vd->vdev_spa))
1577 return;
1578
1579 /* some extra verification for in-core tree if you can */
1580 if (msp->ms_loaded) {
1581 range_tree_stat_verify(msp->ms_allocatable);
1582 VERIFY(space_map_histogram_verify(msp->ms_sm,
1583 msp->ms_allocatable));
1584 }
1585
1586 uint64_t weight = msp->ms_weight;
1587 uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
1588 boolean_t space_based = WEIGHT_IS_SPACEBASED(msp->ms_weight);
1589 uint64_t frag = msp->ms_fragmentation;
1590 uint64_t max_segsize = msp->ms_max_size;
1591
1592 msp->ms_weight = 0;
1593 msp->ms_fragmentation = 0;
1594 msp->ms_max_size = 0;
1595
1596 /*
1597 * This function is used for verification purposes. Regardless of
1598 * whether metaslab_weight() thinks this metaslab should be active or
1599 * not, we want to ensure that the actual weight (and therefore the
1600 * value of ms_weight) would be the same if it was to be recalculated
1601 * at this point.
1602 */
1603 msp->ms_weight = metaslab_weight(msp) | was_active;
1604
1605 VERIFY3U(max_segsize, ==, msp->ms_max_size);
1606
1607 /*
1608 * If the weight type changed then there is no point in doing
1609 * verification. Revert fields to their original values.
1610 */
1611 if ((space_based && !WEIGHT_IS_SPACEBASED(msp->ms_weight)) ||
1612 (!space_based && WEIGHT_IS_SPACEBASED(msp->ms_weight))) {
1613 msp->ms_fragmentation = frag;
1614 msp->ms_weight = weight;
1615 return;
1616 }
1617
1618 VERIFY3U(msp->ms_fragmentation, ==, frag);
1619 VERIFY3U(msp->ms_weight, ==, weight);
1620}
1621
93cf2076
GW
1622/*
1623 * Wait for any in-progress metaslab loads to complete.
1624 */
b194fab0 1625static void
93cf2076
GW
1626metaslab_load_wait(metaslab_t *msp)
1627{
1628 ASSERT(MUTEX_HELD(&msp->ms_lock));
1629
1630 while (msp->ms_loading) {
1631 ASSERT(!msp->ms_loaded);
1632 cv_wait(&msp->ms_load_cv, &msp->ms_lock);
1633 }
1634}
1635
b194fab0
SD
1636static int
1637metaslab_load_impl(metaslab_t *msp)
93cf2076
GW
1638{
1639 int error = 0;
93cf2076
GW
1640
1641 ASSERT(MUTEX_HELD(&msp->ms_lock));
b194fab0 1642 ASSERT(msp->ms_loading);
425d3237 1643 ASSERT(!msp->ms_condensing);
93cf2076 1644
a1d477c2 1645 /*
425d3237
SD
1646 * We temporarily drop the lock to unblock other operations while we
1647 * are reading the space map. Therefore, metaslab_sync() and
1648 * metaslab_sync_done() can run at the same time as we do.
1649 *
1650 * metaslab_sync() can append to the space map while we are loading.
1651 * Therefore we load only entries that existed when we started the
1652 * load. Additionally, metaslab_sync_done() has to wait for the load
1653 * to complete because there are potential races like metaslab_load()
1654 * loading parts of the space map that are currently being appended
1655 * by metaslab_sync(). If we didn't, the ms_allocatable would have
1656 * entries that metaslab_sync_done() would try to re-add later.
1657 *
1658 * That's why before dropping the lock we remember the synced length
1659 * of the metaslab and read up to that point of the space map,
1660 * ignoring entries appended by metaslab_sync() that happen after we
1661 * drop the lock.
a1d477c2 1662 */
425d3237 1663 uint64_t length = msp->ms_synced_length;
a1d477c2 1664 mutex_exit(&msp->ms_lock);
93cf2076 1665
d2734cce 1666 if (msp->ms_sm != NULL) {
425d3237
SD
1667 error = space_map_load_length(msp->ms_sm, msp->ms_allocatable,
1668 SM_FREE, length);
d2734cce 1669 } else {
425d3237
SD
1670 /*
1671 * The space map has not been allocated yet, so treat
1672 * all the space in the metaslab as free and add it to the
1673 * ms_allocatable tree.
1674 */
d2734cce
SD
1675 range_tree_add(msp->ms_allocatable,
1676 msp->ms_start, msp->ms_size);
1677 }
93cf2076 1678
425d3237
SD
1679 /*
1680 * We need to grab the ms_sync_lock to prevent metaslab_sync() from
1681 * changing the ms_sm and the metaslab's range trees while we are
1682 * about to use them and populate the ms_allocatable. The ms_lock
1683 * is insufficient for this because metaslab_sync() doesn't hold
1684 * the ms_lock while writing the ms_checkpointing tree to disk.
1685 */
1686 mutex_enter(&msp->ms_sync_lock);
a1d477c2 1687 mutex_enter(&msp->ms_lock);
425d3237 1688 ASSERT(!msp->ms_condensing);
93cf2076 1689
8eef9976
SD
1690 if (error != 0) {
1691 mutex_exit(&msp->ms_sync_lock);
b194fab0 1692 return (error);
8eef9976 1693 }
4e21fd06 1694
b194fab0
SD
1695 ASSERT3P(msp->ms_group, !=, NULL);
1696 msp->ms_loaded = B_TRUE;
1697
1698 /*
425d3237
SD
1699 * The ms_allocatable contains the segments that exist in the
1700 * ms_defer trees [see ms_synced_length]. Thus we need to remove
1701 * them from ms_allocatable as they will be added again in
1702 * metaslab_sync_done().
b194fab0 1703 */
425d3237
SD
1704 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1705 range_tree_walk(msp->ms_defer[t],
1706 range_tree_remove, msp->ms_allocatable);
93cf2076 1707 }
425d3237 1708
928e8ad4
SD
1709 /*
1710 * Call metaslab_recalculate_weight_and_sort() now that the
1711 * metaslab is loaded so we get the metaslab's real weight.
1712 *
1713 * Unless this metaslab was created with older software and
1714 * has not yet been converted to use segment-based weight, we
1715 * expect the new weight to be better or equal to the weight
1716 * that the metaslab had while it was not loaded. This is
1717 * because the old weight does not take into account the
1718 * consolidation of adjacent segments between TXGs. [see
1719 * comment for ms_synchist and ms_deferhist[] for more info]
1720 */
1721 uint64_t weight = msp->ms_weight;
1722 metaslab_recalculate_weight_and_sort(msp);
1723 if (!WEIGHT_IS_SPACEBASED(weight))
1724 ASSERT3U(weight, <=, msp->ms_weight);
b194fab0
SD
1725 msp->ms_max_size = metaslab_block_maxsize(msp);
1726
425d3237
SD
1727 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1728 metaslab_verify_space(msp, spa_syncing_txg(spa));
1729 mutex_exit(&msp->ms_sync_lock);
1730
b194fab0
SD
1731 return (0);
1732}
1733
1734int
1735metaslab_load(metaslab_t *msp)
1736{
1737 ASSERT(MUTEX_HELD(&msp->ms_lock));
1738
1739 /*
1740 * There may be another thread loading the same metaslab, if that's
1741 * the case just wait until the other thread is done and return.
1742 */
1743 metaslab_load_wait(msp);
1744 if (msp->ms_loaded)
1745 return (0);
1746 VERIFY(!msp->ms_loading);
425d3237 1747 ASSERT(!msp->ms_condensing);
b194fab0
SD
1748
1749 msp->ms_loading = B_TRUE;
1750 int error = metaslab_load_impl(msp);
1751 msp->ms_loading = B_FALSE;
93cf2076 1752 cv_broadcast(&msp->ms_load_cv);
b194fab0 1753
93cf2076
GW
1754 return (error);
1755}
1756
1757void
1758metaslab_unload(metaslab_t *msp)
1759{
1760 ASSERT(MUTEX_HELD(&msp->ms_lock));
928e8ad4
SD
1761
1762 metaslab_verify_weight_and_frag(msp);
1763
d2734cce 1764 range_tree_vacate(msp->ms_allocatable, NULL, NULL);
93cf2076 1765 msp->ms_loaded = B_FALSE;
928e8ad4 1766
93cf2076 1767 msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
4e21fd06 1768 msp->ms_max_size = 0;
928e8ad4
SD
1769
1770 /*
1771 * We explicitly recalculate the metaslab's weight based on its space
1772 * map (as it is now not loaded). We want unload metaslabs to always
1773 * have their weights calculated from the space map histograms, while
1774 * loaded ones have it calculated from their in-core range tree
1775 * [see metaslab_load()]. This way, the weight reflects the information
1776 * available in-core, whether it is loaded or not
1777 *
1778 * If ms_group == NULL means that we came here from metaslab_fini(),
1779 * at which point it doesn't make sense for us to do the recalculation
1780 * and the sorting.
1781 */
1782 if (msp->ms_group != NULL)
1783 metaslab_recalculate_weight_and_sort(msp);
93cf2076
GW
1784}
1785
cc99f275
DB
1786static void
1787metaslab_space_update(vdev_t *vd, metaslab_class_t *mc, int64_t alloc_delta,
1788 int64_t defer_delta, int64_t space_delta)
1789{
1790 vdev_space_update(vd, alloc_delta, defer_delta, space_delta);
1791
1792 ASSERT3P(vd->vdev_spa->spa_root_vdev, ==, vd->vdev_parent);
1793 ASSERT(vd->vdev_ms_count != 0);
1794
1795 metaslab_class_space_update(mc, alloc_delta, defer_delta, space_delta,
1796 vdev_deflated_space(vd, space_delta));
1797}
1798
fb42a493
PS
1799int
1800metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object, uint64_t txg,
1801 metaslab_t **msp)
34dc7c2f
BB
1802{
1803 vdev_t *vd = mg->mg_vd;
cc99f275
DB
1804 spa_t *spa = vd->vdev_spa;
1805 objset_t *mos = spa->spa_meta_objset;
fb42a493
PS
1806 metaslab_t *ms;
1807 int error;
34dc7c2f 1808
79c76d5b 1809 ms = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
fb42a493 1810 mutex_init(&ms->ms_lock, NULL, MUTEX_DEFAULT, NULL);
a1d477c2 1811 mutex_init(&ms->ms_sync_lock, NULL, MUTEX_DEFAULT, NULL);
fb42a493 1812 cv_init(&ms->ms_load_cv, NULL, CV_DEFAULT, NULL);
619f0976 1813
fb42a493
PS
1814 ms->ms_id = id;
1815 ms->ms_start = id << vd->vdev_ms_shift;
1816 ms->ms_size = 1ULL << vd->vdev_ms_shift;
492f64e9
PD
1817 ms->ms_allocator = -1;
1818 ms->ms_new = B_TRUE;
34dc7c2f 1819
93cf2076
GW
1820 /*
1821 * We only open space map objects that already exist. All others
afe37326 1822 * will be opened when we finally allocate an object for it.
425d3237
SD
1823 *
1824 * Note:
1825 * When called from vdev_expand(), we can't call into the DMU as
1826 * we are holding the spa_config_lock as a writer and we would
1827 * deadlock [see relevant comment in vdev_metaslab_init()]. in
1828 * that case, the object parameter is zero though, so we won't
1829 * call into the DMU.
93cf2076 1830 */
afe37326 1831 if (object != 0) {
fb42a493 1832 error = space_map_open(&ms->ms_sm, mos, object, ms->ms_start,
a1d477c2 1833 ms->ms_size, vd->vdev_ashift);
fb42a493
PS
1834
1835 if (error != 0) {
1836 kmem_free(ms, sizeof (metaslab_t));
1837 return (error);
1838 }
1839
1840 ASSERT(ms->ms_sm != NULL);
425d3237 1841 ms->ms_allocated_space = space_map_allocated(ms->ms_sm);
93cf2076 1842 }
34dc7c2f
BB
1843
1844 /*
425d3237 1845 * We create the ms_allocatable here, but we don't create the
258553d3 1846 * other range trees until metaslab_sync_done(). This serves
34dc7c2f 1847 * two purposes: it allows metaslab_sync_done() to detect the
425d3237
SD
1848 * addition of new space; and for debugging, it ensures that
1849 * we'd data fault on any attempt to use this metaslab before
1850 * it's ready.
34dc7c2f 1851 */
d2734cce
SD
1852 ms->ms_allocatable = range_tree_create_impl(&rt_avl_ops,
1853 &ms->ms_allocatable_by_size, metaslab_rangesize_compare, 0);
34dc7c2f 1854
1b939560
BB
1855 ms->ms_trim = range_tree_create(NULL, NULL);
1856
1857 metaslab_group_add(mg, ms);
4e21fd06 1858 metaslab_set_fragmentation(ms);
428870ff 1859
34dc7c2f
BB
1860 /*
1861 * If we're opening an existing pool (txg == 0) or creating
1862 * a new one (txg == TXG_INITIAL), all space is available now.
1863 * If we're adding space to an existing pool, the new space
1864 * does not become available until after this txg has synced.
4e21fd06
DB
1865 * The metaslab's weight will also be initialized when we sync
1866 * out this txg. This ensures that we don't attempt to allocate
1867 * from it before we have initialized it completely.
34dc7c2f 1868 */
425d3237 1869 if (txg <= TXG_INITIAL) {
fb42a493 1870 metaslab_sync_done(ms, 0);
425d3237
SD
1871 metaslab_space_update(vd, mg->mg_class,
1872 metaslab_allocated_space(ms), 0, 0);
1873 }
34dc7c2f 1874
93cf2076
GW
1875 /*
1876 * If metaslab_debug_load is set and we're initializing a metaslab
cc99f275
DB
1877 * that has an allocated space map object then load the space map
1878 * so that we can verify frees.
93cf2076 1879 */
fb42a493
PS
1880 if (metaslab_debug_load && ms->ms_sm != NULL) {
1881 mutex_enter(&ms->ms_lock);
1882 VERIFY0(metaslab_load(ms));
1883 mutex_exit(&ms->ms_lock);
93cf2076
GW
1884 }
1885
34dc7c2f 1886 if (txg != 0) {
34dc7c2f 1887 vdev_dirty(vd, 0, NULL, txg);
fb42a493 1888 vdev_dirty(vd, VDD_METASLAB, ms, txg);
34dc7c2f
BB
1889 }
1890
fb42a493
PS
1891 *msp = ms;
1892
1893 return (0);
34dc7c2f
BB
1894}
1895
1896void
1897metaslab_fini(metaslab_t *msp)
1898{
93cf2076 1899 metaslab_group_t *mg = msp->ms_group;
cc99f275 1900 vdev_t *vd = mg->mg_vd;
34dc7c2f
BB
1901
1902 metaslab_group_remove(mg, msp);
1903
1904 mutex_enter(&msp->ms_lock);
93cf2076 1905 VERIFY(msp->ms_group == NULL);
cc99f275 1906 metaslab_space_update(vd, mg->mg_class,
425d3237 1907 -metaslab_allocated_space(msp), 0, -msp->ms_size);
cc99f275 1908
93cf2076
GW
1909 space_map_close(msp->ms_sm);
1910
1911 metaslab_unload(msp);
cc99f275 1912
d2734cce
SD
1913 range_tree_destroy(msp->ms_allocatable);
1914 range_tree_destroy(msp->ms_freeing);
1915 range_tree_destroy(msp->ms_freed);
34dc7c2f 1916
1c27024e 1917 for (int t = 0; t < TXG_SIZE; t++) {
d2734cce 1918 range_tree_destroy(msp->ms_allocating[t]);
34dc7c2f
BB
1919 }
1920
1c27024e 1921 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
d2734cce 1922 range_tree_destroy(msp->ms_defer[t]);
e51be066 1923 }
c99c9001 1924 ASSERT0(msp->ms_deferspace);
428870ff 1925
d2734cce
SD
1926 range_tree_destroy(msp->ms_checkpointing);
1927
928e8ad4
SD
1928 for (int t = 0; t < TXG_SIZE; t++)
1929 ASSERT(!txg_list_member(&vd->vdev_ms_list, msp, t));
1930
1b939560
BB
1931 range_tree_vacate(msp->ms_trim, NULL, NULL);
1932 range_tree_destroy(msp->ms_trim);
1933
34dc7c2f 1934 mutex_exit(&msp->ms_lock);
93cf2076 1935 cv_destroy(&msp->ms_load_cv);
34dc7c2f 1936 mutex_destroy(&msp->ms_lock);
a1d477c2 1937 mutex_destroy(&msp->ms_sync_lock);
492f64e9 1938 ASSERT3U(msp->ms_allocator, ==, -1);
34dc7c2f
BB
1939
1940 kmem_free(msp, sizeof (metaslab_t));
1941}
1942
f3a7f661
GW
1943#define FRAGMENTATION_TABLE_SIZE 17
1944
93cf2076 1945/*
f3a7f661
GW
1946 * This table defines a segment size based fragmentation metric that will
1947 * allow each metaslab to derive its own fragmentation value. This is done
1948 * by calculating the space in each bucket of the spacemap histogram and
928e8ad4 1949 * multiplying that by the fragmentation metric in this table. Doing
f3a7f661
GW
1950 * this for all buckets and dividing it by the total amount of free
1951 * space in this metaslab (i.e. the total free space in all buckets) gives
1952 * us the fragmentation metric. This means that a high fragmentation metric
1953 * equates to most of the free space being comprised of small segments.
1954 * Conversely, if the metric is low, then most of the free space is in
1955 * large segments. A 10% change in fragmentation equates to approximately
1956 * double the number of segments.
93cf2076 1957 *
f3a7f661
GW
1958 * This table defines 0% fragmented space using 16MB segments. Testing has
1959 * shown that segments that are greater than or equal to 16MB do not suffer
1960 * from drastic performance problems. Using this value, we derive the rest
1961 * of the table. Since the fragmentation value is never stored on disk, it
1962 * is possible to change these calculations in the future.
1963 */
1964int zfs_frag_table[FRAGMENTATION_TABLE_SIZE] = {
1965 100, /* 512B */
1966 100, /* 1K */
1967 98, /* 2K */
1968 95, /* 4K */
1969 90, /* 8K */
1970 80, /* 16K */
1971 70, /* 32K */
1972 60, /* 64K */
1973 50, /* 128K */
1974 40, /* 256K */
1975 30, /* 512K */
1976 20, /* 1M */
1977 15, /* 2M */
1978 10, /* 4M */
1979 5, /* 8M */
1980 0 /* 16M */
1981};
1982
1983/*
425d3237
SD
1984 * Calculate the metaslab's fragmentation metric and set ms_fragmentation.
1985 * Setting this value to ZFS_FRAG_INVALID means that the metaslab has not
1986 * been upgraded and does not support this metric. Otherwise, the return
1987 * value should be in the range [0, 100].
93cf2076 1988 */
4e21fd06
DB
1989static void
1990metaslab_set_fragmentation(metaslab_t *msp)
93cf2076 1991{
f3a7f661
GW
1992 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1993 uint64_t fragmentation = 0;
1994 uint64_t total = 0;
1995 boolean_t feature_enabled = spa_feature_is_enabled(spa,
1996 SPA_FEATURE_SPACEMAP_HISTOGRAM);
93cf2076 1997
4e21fd06
DB
1998 if (!feature_enabled) {
1999 msp->ms_fragmentation = ZFS_FRAG_INVALID;
2000 return;
2001 }
f3a7f661 2002
93cf2076 2003 /*
f3a7f661
GW
2004 * A null space map means that the entire metaslab is free
2005 * and thus is not fragmented.
93cf2076 2006 */
4e21fd06
DB
2007 if (msp->ms_sm == NULL) {
2008 msp->ms_fragmentation = 0;
2009 return;
2010 }
f3a7f661
GW
2011
2012 /*
4e21fd06 2013 * If this metaslab's space map has not been upgraded, flag it
f3a7f661
GW
2014 * so that we upgrade next time we encounter it.
2015 */
2016 if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
3b7f360c 2017 uint64_t txg = spa_syncing_txg(spa);
93cf2076
GW
2018 vdev_t *vd = msp->ms_group->mg_vd;
2019
3b7f360c
GW
2020 /*
2021 * If we've reached the final dirty txg, then we must
2022 * be shutting down the pool. We don't want to dirty
2023 * any data past this point so skip setting the condense
2024 * flag. We can retry this action the next time the pool
2025 * is imported.
2026 */
2027 if (spa_writeable(spa) && txg < spa_final_dirty_txg(spa)) {
8b0a0840
TC
2028 msp->ms_condense_wanted = B_TRUE;
2029 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
964c2d69 2030 zfs_dbgmsg("txg %llu, requesting force condense: "
3b7f360c
GW
2031 "ms_id %llu, vdev_id %llu", txg, msp->ms_id,
2032 vd->vdev_id);
8b0a0840 2033 }
4e21fd06
DB
2034 msp->ms_fragmentation = ZFS_FRAG_INVALID;
2035 return;
93cf2076
GW
2036 }
2037
1c27024e 2038 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
f3a7f661
GW
2039 uint64_t space = 0;
2040 uint8_t shift = msp->ms_sm->sm_shift;
4e21fd06 2041
f3a7f661
GW
2042 int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
2043 FRAGMENTATION_TABLE_SIZE - 1);
93cf2076 2044
93cf2076
GW
2045 if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
2046 continue;
2047
f3a7f661
GW
2048 space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
2049 total += space;
2050
2051 ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
2052 fragmentation += space * zfs_frag_table[idx];
93cf2076 2053 }
f3a7f661
GW
2054
2055 if (total > 0)
2056 fragmentation /= total;
2057 ASSERT3U(fragmentation, <=, 100);
4e21fd06
DB
2058
2059 msp->ms_fragmentation = fragmentation;
93cf2076 2060}
34dc7c2f 2061
f3a7f661
GW
2062/*
2063 * Compute a weight -- a selection preference value -- for the given metaslab.
2064 * This is based on the amount of free space, the level of fragmentation,
2065 * the LBA range, and whether the metaslab is loaded.
2066 */
34dc7c2f 2067static uint64_t
4e21fd06 2068metaslab_space_weight(metaslab_t *msp)
34dc7c2f
BB
2069{
2070 metaslab_group_t *mg = msp->ms_group;
34dc7c2f
BB
2071 vdev_t *vd = mg->mg_vd;
2072 uint64_t weight, space;
2073
2074 ASSERT(MUTEX_HELD(&msp->ms_lock));
4e21fd06 2075 ASSERT(!vd->vdev_removing);
c2e42f9d 2076
34dc7c2f
BB
2077 /*
2078 * The baseline weight is the metaslab's free space.
2079 */
425d3237 2080 space = msp->ms_size - metaslab_allocated_space(msp);
f3a7f661 2081
f3a7f661
GW
2082 if (metaslab_fragmentation_factor_enabled &&
2083 msp->ms_fragmentation != ZFS_FRAG_INVALID) {
2084 /*
2085 * Use the fragmentation information to inversely scale
2086 * down the baseline weight. We need to ensure that we
2087 * don't exclude this metaslab completely when it's 100%
2088 * fragmented. To avoid this we reduce the fragmented value
2089 * by 1.
2090 */
2091 space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
2092
2093 /*
2094 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
2095 * this metaslab again. The fragmentation metric may have
2096 * decreased the space to something smaller than
2097 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
2098 * so that we can consume any remaining space.
2099 */
2100 if (space > 0 && space < SPA_MINBLOCKSIZE)
2101 space = SPA_MINBLOCKSIZE;
2102 }
34dc7c2f
BB
2103 weight = space;
2104
2105 /*
2106 * Modern disks have uniform bit density and constant angular velocity.
2107 * Therefore, the outer recording zones are faster (higher bandwidth)
2108 * than the inner zones by the ratio of outer to inner track diameter,
2109 * which is typically around 2:1. We account for this by assigning
2110 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
2111 * In effect, this means that we'll select the metaslab with the most
2112 * free bandwidth rather than simply the one with the most free space.
2113 */
fb40095f 2114 if (!vd->vdev_nonrot && metaslab_lba_weighting_enabled) {
f3a7f661
GW
2115 weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
2116 ASSERT(weight >= space && weight <= 2 * space);
2117 }
428870ff 2118
f3a7f661
GW
2119 /*
2120 * If this metaslab is one we're actively using, adjust its
2121 * weight to make it preferable to any inactive metaslab so
2122 * we'll polish it off. If the fragmentation on this metaslab
2123 * has exceed our threshold, then don't mark it active.
2124 */
2125 if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
2126 msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
428870ff
BB
2127 weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
2128 }
34dc7c2f 2129
4e21fd06
DB
2130 WEIGHT_SET_SPACEBASED(weight);
2131 return (weight);
2132}
2133
2134/*
2135 * Return the weight of the specified metaslab, according to the segment-based
2136 * weighting algorithm. The metaslab must be loaded. This function can
2137 * be called within a sync pass since it relies only on the metaslab's
2138 * range tree which is always accurate when the metaslab is loaded.
2139 */
2140static uint64_t
2141metaslab_weight_from_range_tree(metaslab_t *msp)
2142{
2143 uint64_t weight = 0;
2144 uint32_t segments = 0;
4e21fd06
DB
2145
2146 ASSERT(msp->ms_loaded);
2147
1c27024e
DB
2148 for (int i = RANGE_TREE_HISTOGRAM_SIZE - 1; i >= SPA_MINBLOCKSHIFT;
2149 i--) {
4e21fd06
DB
2150 uint8_t shift = msp->ms_group->mg_vd->vdev_ashift;
2151 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
2152
2153 segments <<= 1;
d2734cce 2154 segments += msp->ms_allocatable->rt_histogram[i];
4e21fd06
DB
2155
2156 /*
2157 * The range tree provides more precision than the space map
2158 * and must be downgraded so that all values fit within the
2159 * space map's histogram. This allows us to compare loaded
2160 * vs. unloaded metaslabs to determine which metaslab is
2161 * considered "best".
2162 */
2163 if (i > max_idx)
2164 continue;
2165
2166 if (segments != 0) {
2167 WEIGHT_SET_COUNT(weight, segments);
2168 WEIGHT_SET_INDEX(weight, i);
2169 WEIGHT_SET_ACTIVE(weight, 0);
2170 break;
2171 }
2172 }
2173 return (weight);
2174}
2175
2176/*
2177 * Calculate the weight based on the on-disk histogram. This should only
2178 * be called after a sync pass has completely finished since the on-disk
2179 * information is updated in metaslab_sync().
2180 */
2181static uint64_t
2182metaslab_weight_from_spacemap(metaslab_t *msp)
2183{
928e8ad4
SD
2184 space_map_t *sm = msp->ms_sm;
2185 ASSERT(!msp->ms_loaded);
2186 ASSERT(sm != NULL);
2187 ASSERT3U(space_map_object(sm), !=, 0);
2188 ASSERT3U(sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
4e21fd06 2189
928e8ad4
SD
2190 /*
2191 * Create a joint histogram from all the segments that have made
2192 * it to the metaslab's space map histogram, that are not yet
2193 * available for allocation because they are still in the freeing
2194 * pipeline (e.g. freeing, freed, and defer trees). Then subtract
2195 * these segments from the space map's histogram to get a more
2196 * accurate weight.
2197 */
2198 uint64_t deferspace_histogram[SPACE_MAP_HISTOGRAM_SIZE] = {0};
2199 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
2200 deferspace_histogram[i] += msp->ms_synchist[i];
2201 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2202 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
2203 deferspace_histogram[i] += msp->ms_deferhist[t][i];
2204 }
2205 }
2206
2207 uint64_t weight = 0;
1c27024e 2208 for (int i = SPACE_MAP_HISTOGRAM_SIZE - 1; i >= 0; i--) {
928e8ad4
SD
2209 ASSERT3U(sm->sm_phys->smp_histogram[i], >=,
2210 deferspace_histogram[i]);
2211 uint64_t count =
2212 sm->sm_phys->smp_histogram[i] - deferspace_histogram[i];
2213 if (count != 0) {
2214 WEIGHT_SET_COUNT(weight, count);
2215 WEIGHT_SET_INDEX(weight, i + sm->sm_shift);
4e21fd06
DB
2216 WEIGHT_SET_ACTIVE(weight, 0);
2217 break;
2218 }
2219 }
2220 return (weight);
2221}
2222
2223/*
2224 * Compute a segment-based weight for the specified metaslab. The weight
2225 * is determined by highest bucket in the histogram. The information
2226 * for the highest bucket is encoded into the weight value.
2227 */
2228static uint64_t
2229metaslab_segment_weight(metaslab_t *msp)
2230{
2231 metaslab_group_t *mg = msp->ms_group;
2232 uint64_t weight = 0;
2233 uint8_t shift = mg->mg_vd->vdev_ashift;
2234
2235 ASSERT(MUTEX_HELD(&msp->ms_lock));
2236
2237 /*
2238 * The metaslab is completely free.
2239 */
425d3237 2240 if (metaslab_allocated_space(msp) == 0) {
4e21fd06
DB
2241 int idx = highbit64(msp->ms_size) - 1;
2242 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
2243
2244 if (idx < max_idx) {
2245 WEIGHT_SET_COUNT(weight, 1ULL);
2246 WEIGHT_SET_INDEX(weight, idx);
2247 } else {
2248 WEIGHT_SET_COUNT(weight, 1ULL << (idx - max_idx));
2249 WEIGHT_SET_INDEX(weight, max_idx);
2250 }
2251 WEIGHT_SET_ACTIVE(weight, 0);
2252 ASSERT(!WEIGHT_IS_SPACEBASED(weight));
2253
2254 return (weight);
2255 }
2256
2257 ASSERT3U(msp->ms_sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
2258
2259 /*
2260 * If the metaslab is fully allocated then just make the weight 0.
2261 */
425d3237 2262 if (metaslab_allocated_space(msp) == msp->ms_size)
4e21fd06
DB
2263 return (0);
2264 /*
2265 * If the metaslab is already loaded, then use the range tree to
2266 * determine the weight. Otherwise, we rely on the space map information
2267 * to generate the weight.
2268 */
2269 if (msp->ms_loaded) {
2270 weight = metaslab_weight_from_range_tree(msp);
2271 } else {
2272 weight = metaslab_weight_from_spacemap(msp);
2273 }
2274
2275 /*
2276 * If the metaslab was active the last time we calculated its weight
2277 * then keep it active. We want to consume the entire region that
2278 * is associated with this weight.
2279 */
2280 if (msp->ms_activation_weight != 0 && weight != 0)
2281 WEIGHT_SET_ACTIVE(weight, WEIGHT_GET_ACTIVE(msp->ms_weight));
2282 return (weight);
2283}
2284
2285/*
2286 * Determine if we should attempt to allocate from this metaslab. If the
2287 * metaslab has a maximum size then we can quickly determine if the desired
2288 * allocation size can be satisfied. Otherwise, if we're using segment-based
2289 * weighting then we can determine the maximum allocation that this metaslab
2290 * can accommodate based on the index encoded in the weight. If we're using
2291 * space-based weights then rely on the entire weight (excluding the weight
2292 * type bit).
2293 */
2294boolean_t
2295metaslab_should_allocate(metaslab_t *msp, uint64_t asize)
2296{
2297 boolean_t should_allocate;
2298
2299 if (msp->ms_max_size != 0)
2300 return (msp->ms_max_size >= asize);
2301
2302 if (!WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
2303 /*
2304 * The metaslab segment weight indicates segments in the
2305 * range [2^i, 2^(i+1)), where i is the index in the weight.
2306 * Since the asize might be in the middle of the range, we
2307 * should attempt the allocation if asize < 2^(i+1).
2308 */
2309 should_allocate = (asize <
2310 1ULL << (WEIGHT_GET_INDEX(msp->ms_weight) + 1));
2311 } else {
2312 should_allocate = (asize <=
2313 (msp->ms_weight & ~METASLAB_WEIGHT_TYPE));
2314 }
2315 return (should_allocate);
2316}
2317static uint64_t
2318metaslab_weight(metaslab_t *msp)
2319{
2320 vdev_t *vd = msp->ms_group->mg_vd;
2321 spa_t *spa = vd->vdev_spa;
2322 uint64_t weight;
2323
2324 ASSERT(MUTEX_HELD(&msp->ms_lock));
2325
2326 /*
a1d477c2 2327 * If this vdev is in the process of being removed, there is nothing
4e21fd06
DB
2328 * for us to do here.
2329 */
a1d477c2 2330 if (vd->vdev_removing)
4e21fd06 2331 return (0);
4e21fd06
DB
2332
2333 metaslab_set_fragmentation(msp);
2334
2335 /*
2336 * Update the maximum size if the metaslab is loaded. This will
2337 * ensure that we get an accurate maximum size if newly freed space
2338 * has been added back into the free tree.
2339 */
2340 if (msp->ms_loaded)
2341 msp->ms_max_size = metaslab_block_maxsize(msp);
425d3237
SD
2342 else
2343 ASSERT0(msp->ms_max_size);
4e21fd06
DB
2344
2345 /*
2346 * Segment-based weighting requires space map histogram support.
2347 */
2348 if (zfs_metaslab_segment_weight_enabled &&
2349 spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM) &&
2350 (msp->ms_sm == NULL || msp->ms_sm->sm_dbuf->db_size ==
2351 sizeof (space_map_phys_t))) {
2352 weight = metaslab_segment_weight(msp);
2353 } else {
2354 weight = metaslab_space_weight(msp);
2355 }
93cf2076 2356 return (weight);
34dc7c2f
BB
2357}
2358
928e8ad4
SD
2359void
2360metaslab_recalculate_weight_and_sort(metaslab_t *msp)
2361{
2362 /* note: we preserve the mask (e.g. indication of primary, etc..) */
2363 uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
2364 metaslab_group_sort(msp->ms_group, msp,
2365 metaslab_weight(msp) | was_active);
2366}
2367
34dc7c2f 2368static int
492f64e9
PD
2369metaslab_activate_allocator(metaslab_group_t *mg, metaslab_t *msp,
2370 int allocator, uint64_t activation_weight)
2371{
2372 /*
2373 * If we're activating for the claim code, we don't want to actually
2374 * set the metaslab up for a specific allocator.
2375 */
2376 if (activation_weight == METASLAB_WEIGHT_CLAIM)
2377 return (0);
2378 metaslab_t **arr = (activation_weight == METASLAB_WEIGHT_PRIMARY ?
2379 mg->mg_primaries : mg->mg_secondaries);
2380
2381 ASSERT(MUTEX_HELD(&msp->ms_lock));
2382 mutex_enter(&mg->mg_lock);
2383 if (arr[allocator] != NULL) {
2384 mutex_exit(&mg->mg_lock);
2385 return (EEXIST);
2386 }
2387
2388 arr[allocator] = msp;
2389 ASSERT3S(msp->ms_allocator, ==, -1);
2390 msp->ms_allocator = allocator;
2391 msp->ms_primary = (activation_weight == METASLAB_WEIGHT_PRIMARY);
2392 mutex_exit(&mg->mg_lock);
2393
2394 return (0);
2395}
2396
2397static int
2398metaslab_activate(metaslab_t *msp, int allocator, uint64_t activation_weight)
34dc7c2f 2399{
34dc7c2f
BB
2400 ASSERT(MUTEX_HELD(&msp->ms_lock));
2401
2402 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
b194fab0
SD
2403 int error = metaslab_load(msp);
2404 if (error != 0) {
2405 metaslab_group_sort(msp->ms_group, msp, 0);
2406 return (error);
34dc7c2f 2407 }
492f64e9
PD
2408 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
2409 /*
2410 * The metaslab was activated for another allocator
2411 * while we were waiting, we should reselect.
2412 */
7ab96299 2413 return (SET_ERROR(EBUSY));
492f64e9
PD
2414 }
2415 if ((error = metaslab_activate_allocator(msp->ms_group, msp,
2416 allocator, activation_weight)) != 0) {
2417 return (error);
2418 }
9babb374 2419
4e21fd06 2420 msp->ms_activation_weight = msp->ms_weight;
34dc7c2f
BB
2421 metaslab_group_sort(msp->ms_group, msp,
2422 msp->ms_weight | activation_weight);
2423 }
93cf2076 2424 ASSERT(msp->ms_loaded);
34dc7c2f
BB
2425 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
2426
2427 return (0);
2428}
2429
492f64e9
PD
2430static void
2431metaslab_passivate_allocator(metaslab_group_t *mg, metaslab_t *msp,
2432 uint64_t weight)
2433{
2434 ASSERT(MUTEX_HELD(&msp->ms_lock));
2435 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
2436 metaslab_group_sort(mg, msp, weight);
2437 return;
2438 }
2439
2440 mutex_enter(&mg->mg_lock);
2441 ASSERT3P(msp->ms_group, ==, mg);
2442 if (msp->ms_primary) {
2443 ASSERT3U(0, <=, msp->ms_allocator);
2444 ASSERT3U(msp->ms_allocator, <, mg->mg_allocators);
2445 ASSERT3P(mg->mg_primaries[msp->ms_allocator], ==, msp);
2446 ASSERT(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
2447 mg->mg_primaries[msp->ms_allocator] = NULL;
2448 } else {
2449 ASSERT(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
2450 ASSERT3P(mg->mg_secondaries[msp->ms_allocator], ==, msp);
2451 mg->mg_secondaries[msp->ms_allocator] = NULL;
2452 }
2453 msp->ms_allocator = -1;
2454 metaslab_group_sort_impl(mg, msp, weight);
2455 mutex_exit(&mg->mg_lock);
2456}
2457
34dc7c2f 2458static void
4e21fd06 2459metaslab_passivate(metaslab_t *msp, uint64_t weight)
34dc7c2f 2460{
4e21fd06
DB
2461 ASSERTV(uint64_t size = weight & ~METASLAB_WEIGHT_TYPE);
2462
34dc7c2f
BB
2463 /*
2464 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
2465 * this metaslab again. In that case, it had better be empty,
2466 * or we would be leaving space on the table.
2467 */
94d49e8f
TC
2468 ASSERT(!WEIGHT_IS_SPACEBASED(msp->ms_weight) ||
2469 size >= SPA_MINBLOCKSIZE ||
d2734cce 2470 range_tree_space(msp->ms_allocatable) == 0);
4e21fd06
DB
2471 ASSERT0(weight & METASLAB_ACTIVE_MASK);
2472
2473 msp->ms_activation_weight = 0;
492f64e9 2474 metaslab_passivate_allocator(msp->ms_group, msp, weight);
34dc7c2f
BB
2475 ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
2476}
2477
4e21fd06
DB
2478/*
2479 * Segment-based metaslabs are activated once and remain active until
2480 * we either fail an allocation attempt (similar to space-based metaslabs)
2481 * or have exhausted the free space in zfs_metaslab_switch_threshold
2482 * buckets since the metaslab was activated. This function checks to see
2483 * if we've exhaused the zfs_metaslab_switch_threshold buckets in the
2484 * metaslab and passivates it proactively. This will allow us to select a
2485 * metaslab with a larger contiguous region, if any, remaining within this
2486 * metaslab group. If we're in sync pass > 1, then we continue using this
2487 * metaslab so that we don't dirty more block and cause more sync passes.
2488 */
2489void
2490metaslab_segment_may_passivate(metaslab_t *msp)
2491{
2492 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
4e21fd06
DB
2493
2494 if (WEIGHT_IS_SPACEBASED(msp->ms_weight) || spa_sync_pass(spa) > 1)
2495 return;
2496
2497 /*
2498 * Since we are in the middle of a sync pass, the most accurate
2499 * information that is accessible to us is the in-core range tree
2500 * histogram; calculate the new weight based on that information.
2501 */
1c27024e
DB
2502 uint64_t weight = metaslab_weight_from_range_tree(msp);
2503 int activation_idx = WEIGHT_GET_INDEX(msp->ms_activation_weight);
2504 int current_idx = WEIGHT_GET_INDEX(weight);
4e21fd06
DB
2505
2506 if (current_idx <= activation_idx - zfs_metaslab_switch_threshold)
2507 metaslab_passivate(msp, weight);
2508}
2509
93cf2076
GW
2510static void
2511metaslab_preload(void *arg)
2512{
2513 metaslab_t *msp = arg;
2514 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1cd77734 2515 fstrans_cookie_t cookie = spl_fstrans_mark();
93cf2076 2516
080b3100
GW
2517 ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
2518
93cf2076 2519 mutex_enter(&msp->ms_lock);
b194fab0 2520 (void) metaslab_load(msp);
4e21fd06 2521 msp->ms_selected_txg = spa_syncing_txg(spa);
93cf2076 2522 mutex_exit(&msp->ms_lock);
1cd77734 2523 spl_fstrans_unmark(cookie);
93cf2076
GW
2524}
2525
2526static void
2527metaslab_group_preload(metaslab_group_t *mg)
2528{
2529 spa_t *spa = mg->mg_vd->vdev_spa;
2530 metaslab_t *msp;
2531 avl_tree_t *t = &mg->mg_metaslab_tree;
2532 int m = 0;
2533
2534 if (spa_shutting_down(spa) || !metaslab_preload_enabled) {
c5528b9b 2535 taskq_wait_outstanding(mg->mg_taskq, 0);
93cf2076
GW
2536 return;
2537 }
93cf2076 2538
080b3100 2539 mutex_enter(&mg->mg_lock);
a1d477c2 2540
93cf2076 2541 /*
080b3100 2542 * Load the next potential metaslabs
93cf2076 2543 */
4e21fd06 2544 for (msp = avl_first(t); msp != NULL; msp = AVL_NEXT(t, msp)) {
a1d477c2
MA
2545 ASSERT3P(msp->ms_group, ==, mg);
2546
f3a7f661
GW
2547 /*
2548 * We preload only the maximum number of metaslabs specified
2549 * by metaslab_preload_limit. If a metaslab is being forced
2550 * to condense then we preload it too. This will ensure
2551 * that force condensing happens in the next txg.
2552 */
2553 if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
f3a7f661
GW
2554 continue;
2555 }
93cf2076
GW
2556
2557 VERIFY(taskq_dispatch(mg->mg_taskq, metaslab_preload,
48d3eb40 2558 msp, TQ_SLEEP) != TASKQID_INVALID);
93cf2076
GW
2559 }
2560 mutex_exit(&mg->mg_lock);
2561}
2562
e51be066 2563/*
93cf2076
GW
2564 * Determine if the space map's on-disk footprint is past our tolerance
2565 * for inefficiency. We would like to use the following criteria to make
2566 * our decision:
e51be066
GW
2567 *
2568 * 1. The size of the space map object should not dramatically increase as a
93cf2076 2569 * result of writing out the free space range tree.
e51be066
GW
2570 *
2571 * 2. The minimal on-disk space map representation is zfs_condense_pct/100
93cf2076 2572 * times the size than the free space range tree representation
a1d477c2 2573 * (i.e. zfs_condense_pct = 110 and in-core = 1MB, minimal = 1.1MB).
e51be066 2574 *
b02fe35d
AR
2575 * 3. The on-disk size of the space map should actually decrease.
2576 *
b02fe35d
AR
2577 * Unfortunately, we cannot compute the on-disk size of the space map in this
2578 * context because we cannot accurately compute the effects of compression, etc.
2579 * Instead, we apply the heuristic described in the block comment for
2580 * zfs_metaslab_condense_block_threshold - we only condense if the space used
2581 * is greater than a threshold number of blocks.
e51be066
GW
2582 */
2583static boolean_t
2584metaslab_should_condense(metaslab_t *msp)
2585{
93cf2076 2586 space_map_t *sm = msp->ms_sm;
d2734cce
SD
2587 vdev_t *vd = msp->ms_group->mg_vd;
2588 uint64_t vdev_blocksize = 1 << vd->vdev_ashift;
2589 uint64_t current_txg = spa_syncing_txg(vd->vdev_spa);
e51be066
GW
2590
2591 ASSERT(MUTEX_HELD(&msp->ms_lock));
93cf2076 2592 ASSERT(msp->ms_loaded);
e51be066
GW
2593
2594 /*
d2734cce
SD
2595 * Allocations and frees in early passes are generally more space
2596 * efficient (in terms of blocks described in space map entries)
2597 * than the ones in later passes (e.g. we don't compress after
2598 * sync pass 5) and condensing a metaslab multiple times in a txg
2599 * could degrade performance.
2600 *
2601 * Thus we prefer condensing each metaslab at most once every txg at
2602 * the earliest sync pass possible. If a metaslab is eligible for
2603 * condensing again after being considered for condensing within the
2604 * same txg, it will hopefully be dirty in the next txg where it will
2605 * be condensed at an earlier pass.
2606 */
2607 if (msp->ms_condense_checked_txg == current_txg)
2608 return (B_FALSE);
2609 msp->ms_condense_checked_txg = current_txg;
2610
2611 /*
4d044c4c
SD
2612 * We always condense metaslabs that are empty and metaslabs for
2613 * which a condense request has been made.
e51be066 2614 */
4d044c4c
SD
2615 if (avl_is_empty(&msp->ms_allocatable_by_size) ||
2616 msp->ms_condense_wanted)
e51be066
GW
2617 return (B_TRUE);
2618
4d044c4c
SD
2619 uint64_t object_size = space_map_length(msp->ms_sm);
2620 uint64_t optimal_size = space_map_estimate_optimal_size(sm,
2621 msp->ms_allocatable, SM_NO_VDEVID);
b02fe35d 2622
4d044c4c 2623 dmu_object_info_t doi;
b02fe35d 2624 dmu_object_info_from_db(sm->sm_dbuf, &doi);
4d044c4c 2625 uint64_t record_size = MAX(doi.doi_data_block_size, vdev_blocksize);
b02fe35d 2626
4d044c4c 2627 return (object_size >= (optimal_size * zfs_condense_pct / 100) &&
b02fe35d 2628 object_size > zfs_metaslab_condense_block_threshold * record_size);
e51be066
GW
2629}
2630
2631/*
2632 * Condense the on-disk space map representation to its minimized form.
2633 * The minimized form consists of a small number of allocations followed by
93cf2076 2634 * the entries of the free range tree.
e51be066
GW
2635 */
2636static void
2637metaslab_condense(metaslab_t *msp, uint64_t txg, dmu_tx_t *tx)
2638{
93cf2076
GW
2639 range_tree_t *condense_tree;
2640 space_map_t *sm = msp->ms_sm;
e51be066
GW
2641
2642 ASSERT(MUTEX_HELD(&msp->ms_lock));
93cf2076 2643 ASSERT(msp->ms_loaded);
e51be066 2644
f3a7f661 2645
a887d653 2646 zfs_dbgmsg("condensing: txg %llu, msp[%llu] %px, vdev id %llu, "
5f3d9c69
JS
2647 "spa %s, smp size %llu, segments %lu, forcing condense=%s", txg,
2648 msp->ms_id, msp, msp->ms_group->mg_vd->vdev_id,
2649 msp->ms_group->mg_vd->vdev_spa->spa_name,
d2734cce
SD
2650 space_map_length(msp->ms_sm),
2651 avl_numnodes(&msp->ms_allocatable->rt_root),
f3a7f661
GW
2652 msp->ms_condense_wanted ? "TRUE" : "FALSE");
2653
2654 msp->ms_condense_wanted = B_FALSE;
e51be066
GW
2655
2656 /*
93cf2076 2657 * Create an range tree that is 100% allocated. We remove segments
e51be066
GW
2658 * that have been freed in this txg, any deferred frees that exist,
2659 * and any allocation in the future. Removing segments should be
93cf2076
GW
2660 * a relatively inexpensive operation since we expect these trees to
2661 * have a small number of nodes.
e51be066 2662 */
a1d477c2 2663 condense_tree = range_tree_create(NULL, NULL);
93cf2076 2664 range_tree_add(condense_tree, msp->ms_start, msp->ms_size);
e51be066 2665
d2734cce
SD
2666 range_tree_walk(msp->ms_freeing, range_tree_remove, condense_tree);
2667 range_tree_walk(msp->ms_freed, range_tree_remove, condense_tree);
e51be066 2668
1c27024e 2669 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
d2734cce 2670 range_tree_walk(msp->ms_defer[t],
93cf2076
GW
2671 range_tree_remove, condense_tree);
2672 }
e51be066 2673
1c27024e 2674 for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
d2734cce 2675 range_tree_walk(msp->ms_allocating[(txg + t) & TXG_MASK],
93cf2076
GW
2676 range_tree_remove, condense_tree);
2677 }
e51be066
GW
2678
2679 /*
2680 * We're about to drop the metaslab's lock thus allowing
2681 * other consumers to change it's content. Set the
93cf2076 2682 * metaslab's ms_condensing flag to ensure that
e51be066
GW
2683 * allocations on this metaslab do not occur while we're
2684 * in the middle of committing it to disk. This is only critical
d2734cce 2685 * for ms_allocatable as all other range trees use per txg
e51be066
GW
2686 * views of their content.
2687 */
93cf2076 2688 msp->ms_condensing = B_TRUE;
e51be066
GW
2689
2690 mutex_exit(&msp->ms_lock);
d2734cce 2691 space_map_truncate(sm, zfs_metaslab_sm_blksz, tx);
e51be066
GW
2692
2693 /*
4e21fd06 2694 * While we would ideally like to create a space map representation
e51be066 2695 * that consists only of allocation records, doing so can be
93cf2076 2696 * prohibitively expensive because the in-core free tree can be
e51be066 2697 * large, and therefore computationally expensive to subtract
93cf2076
GW
2698 * from the condense_tree. Instead we sync out two trees, a cheap
2699 * allocation only tree followed by the in-core free tree. While not
e51be066
GW
2700 * optimal, this is typically close to optimal, and much cheaper to
2701 * compute.
2702 */
4d044c4c 2703 space_map_write(sm, condense_tree, SM_ALLOC, SM_NO_VDEVID, tx);
93cf2076
GW
2704 range_tree_vacate(condense_tree, NULL, NULL);
2705 range_tree_destroy(condense_tree);
e51be066 2706
4d044c4c 2707 space_map_write(sm, msp->ms_allocatable, SM_FREE, SM_NO_VDEVID, tx);
a1d477c2 2708 mutex_enter(&msp->ms_lock);
93cf2076 2709 msp->ms_condensing = B_FALSE;
e51be066
GW
2710}
2711
34dc7c2f
BB
2712/*
2713 * Write a metaslab to disk in the context of the specified transaction group.
2714 */
2715void
2716metaslab_sync(metaslab_t *msp, uint64_t txg)
2717{
93cf2076
GW
2718 metaslab_group_t *mg = msp->ms_group;
2719 vdev_t *vd = mg->mg_vd;
34dc7c2f 2720 spa_t *spa = vd->vdev_spa;
428870ff 2721 objset_t *mos = spa_meta_objset(spa);
d2734cce 2722 range_tree_t *alloctree = msp->ms_allocating[txg & TXG_MASK];
34dc7c2f 2723 dmu_tx_t *tx;
93cf2076 2724 uint64_t object = space_map_object(msp->ms_sm);
34dc7c2f 2725
428870ff
BB
2726 ASSERT(!vd->vdev_ishole);
2727
e51be066
GW
2728 /*
2729 * This metaslab has just been added so there's no work to do now.
2730 */
d2734cce 2731 if (msp->ms_freeing == NULL) {
93cf2076 2732 ASSERT3P(alloctree, ==, NULL);
e51be066
GW
2733 return;
2734 }
2735
93cf2076 2736 ASSERT3P(alloctree, !=, NULL);
d2734cce
SD
2737 ASSERT3P(msp->ms_freeing, !=, NULL);
2738 ASSERT3P(msp->ms_freed, !=, NULL);
2739 ASSERT3P(msp->ms_checkpointing, !=, NULL);
1b939560 2740 ASSERT3P(msp->ms_trim, !=, NULL);
e51be066 2741
f3a7f661 2742 /*
d2734cce
SD
2743 * Normally, we don't want to process a metaslab if there are no
2744 * allocations or frees to perform. However, if the metaslab is being
2745 * forced to condense and it's loaded, we need to let it through.
f3a7f661 2746 */
d2734cce
SD
2747 if (range_tree_is_empty(alloctree) &&
2748 range_tree_is_empty(msp->ms_freeing) &&
2749 range_tree_is_empty(msp->ms_checkpointing) &&
3b7f360c 2750 !(msp->ms_loaded && msp->ms_condense_wanted))
428870ff 2751 return;
34dc7c2f 2752
3b7f360c
GW
2753
2754 VERIFY(txg <= spa_final_dirty_txg(spa));
2755
34dc7c2f 2756 /*
425d3237
SD
2757 * The only state that can actually be changing concurrently
2758 * with metaslab_sync() is the metaslab's ms_allocatable. No
2759 * other thread can be modifying this txg's alloc, freeing,
d2734cce 2760 * freed, or space_map_phys_t. We drop ms_lock whenever we
425d3237
SD
2761 * could call into the DMU, because the DMU can call down to
2762 * us (e.g. via zio_free()) at any time.
a1d477c2
MA
2763 *
2764 * The spa_vdev_remove_thread() can be reading metaslab state
425d3237
SD
2765 * concurrently, and it is locked out by the ms_sync_lock.
2766 * Note that the ms_lock is insufficient for this, because it
2767 * is dropped by space_map_write().
34dc7c2f 2768 */
428870ff 2769 tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
34dc7c2f 2770
93cf2076
GW
2771 if (msp->ms_sm == NULL) {
2772 uint64_t new_object;
2773
d2734cce 2774 new_object = space_map_alloc(mos, zfs_metaslab_sm_blksz, tx);
93cf2076
GW
2775 VERIFY3U(new_object, !=, 0);
2776
2777 VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
a1d477c2 2778 msp->ms_start, msp->ms_size, vd->vdev_ashift));
425d3237 2779
93cf2076 2780 ASSERT(msp->ms_sm != NULL);
425d3237 2781 ASSERT0(metaslab_allocated_space(msp));
34dc7c2f
BB
2782 }
2783
d2734cce
SD
2784 if (!range_tree_is_empty(msp->ms_checkpointing) &&
2785 vd->vdev_checkpoint_sm == NULL) {
2786 ASSERT(spa_has_checkpoint(spa));
2787
2788 uint64_t new_object = space_map_alloc(mos,
2789 vdev_standard_sm_blksz, tx);
2790 VERIFY3U(new_object, !=, 0);
2791
2792 VERIFY0(space_map_open(&vd->vdev_checkpoint_sm,
2793 mos, new_object, 0, vd->vdev_asize, vd->vdev_ashift));
2794 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
2795
2796 /*
2797 * We save the space map object as an entry in vdev_top_zap
2798 * so it can be retrieved when the pool is reopened after an
2799 * export or through zdb.
2800 */
2801 VERIFY0(zap_add(vd->vdev_spa->spa_meta_objset,
2802 vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
2803 sizeof (new_object), 1, &new_object, tx));
2804 }
2805
a1d477c2 2806 mutex_enter(&msp->ms_sync_lock);
428870ff
BB
2807 mutex_enter(&msp->ms_lock);
2808
96358617 2809 /*
4e21fd06
DB
2810 * Note: metaslab_condense() clears the space map's histogram.
2811 * Therefore we must verify and remove this histogram before
96358617
MA
2812 * condensing.
2813 */
2814 metaslab_group_histogram_verify(mg);
2815 metaslab_class_histogram_verify(mg->mg_class);
2816 metaslab_group_histogram_remove(mg, msp);
2817
d2734cce 2818 if (msp->ms_loaded && metaslab_should_condense(msp)) {
e51be066
GW
2819 metaslab_condense(msp, txg, tx);
2820 } else {
a1d477c2 2821 mutex_exit(&msp->ms_lock);
4d044c4c
SD
2822 space_map_write(msp->ms_sm, alloctree, SM_ALLOC,
2823 SM_NO_VDEVID, tx);
2824 space_map_write(msp->ms_sm, msp->ms_freeing, SM_FREE,
2825 SM_NO_VDEVID, tx);
a1d477c2 2826 mutex_enter(&msp->ms_lock);
e51be066 2827 }
428870ff 2828
425d3237
SD
2829 msp->ms_allocated_space += range_tree_space(alloctree);
2830 ASSERT3U(msp->ms_allocated_space, >=,
2831 range_tree_space(msp->ms_freeing));
2832 msp->ms_allocated_space -= range_tree_space(msp->ms_freeing);
2833
d2734cce
SD
2834 if (!range_tree_is_empty(msp->ms_checkpointing)) {
2835 ASSERT(spa_has_checkpoint(spa));
2836 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
2837
2838 /*
2839 * Since we are doing writes to disk and the ms_checkpointing
2840 * tree won't be changing during that time, we drop the
2841 * ms_lock while writing to the checkpoint space map.
2842 */
2843 mutex_exit(&msp->ms_lock);
2844 space_map_write(vd->vdev_checkpoint_sm,
4d044c4c 2845 msp->ms_checkpointing, SM_FREE, SM_NO_VDEVID, tx);
d2734cce 2846 mutex_enter(&msp->ms_lock);
d2734cce
SD
2847
2848 spa->spa_checkpoint_info.sci_dspace +=
2849 range_tree_space(msp->ms_checkpointing);
2850 vd->vdev_stat.vs_checkpoint_space +=
2851 range_tree_space(msp->ms_checkpointing);
2852 ASSERT3U(vd->vdev_stat.vs_checkpoint_space, ==,
425d3237 2853 -space_map_allocated(vd->vdev_checkpoint_sm));
d2734cce
SD
2854
2855 range_tree_vacate(msp->ms_checkpointing, NULL, NULL);
2856 }
2857
93cf2076
GW
2858 if (msp->ms_loaded) {
2859 /*
a1d477c2 2860 * When the space map is loaded, we have an accurate
93cf2076
GW
2861 * histogram in the range tree. This gives us an opportunity
2862 * to bring the space map's histogram up-to-date so we clear
2863 * it first before updating it.
2864 */
2865 space_map_histogram_clear(msp->ms_sm);
d2734cce 2866 space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
4e21fd06
DB
2867
2868 /*
2869 * Since we've cleared the histogram we need to add back
2870 * any free space that has already been processed, plus
2871 * any deferred space. This allows the on-disk histogram
2872 * to accurately reflect all free space even if some space
2873 * is not yet available for allocation (i.e. deferred).
2874 */
d2734cce 2875 space_map_histogram_add(msp->ms_sm, msp->ms_freed, tx);
4e21fd06 2876
93cf2076 2877 /*
4e21fd06
DB
2878 * Add back any deferred free space that has not been
2879 * added back into the in-core free tree yet. This will
2880 * ensure that we don't end up with a space map histogram
2881 * that is completely empty unless the metaslab is fully
2882 * allocated.
93cf2076 2883 */
1c27024e 2884 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
4e21fd06 2885 space_map_histogram_add(msp->ms_sm,
d2734cce 2886 msp->ms_defer[t], tx);
4e21fd06 2887 }
93cf2076 2888 }
4e21fd06
DB
2889
2890 /*
2891 * Always add the free space from this sync pass to the space
2892 * map histogram. We want to make sure that the on-disk histogram
2893 * accounts for all free space. If the space map is not loaded,
2894 * then we will lose some accuracy but will correct it the next
2895 * time we load the space map.
2896 */
d2734cce 2897 space_map_histogram_add(msp->ms_sm, msp->ms_freeing, tx);
928e8ad4 2898 metaslab_aux_histograms_update(msp);
4e21fd06 2899
f3a7f661
GW
2900 metaslab_group_histogram_add(mg, msp);
2901 metaslab_group_histogram_verify(mg);
2902 metaslab_class_histogram_verify(mg->mg_class);
34dc7c2f 2903
e51be066 2904 /*
93cf2076 2905 * For sync pass 1, we avoid traversing this txg's free range tree
425d3237
SD
2906 * and instead will just swap the pointers for freeing and freed.
2907 * We can safely do this since the freed_tree is guaranteed to be
2908 * empty on the initial pass.
e51be066
GW
2909 */
2910 if (spa_sync_pass(spa) == 1) {
d2734cce 2911 range_tree_swap(&msp->ms_freeing, &msp->ms_freed);
425d3237 2912 ASSERT0(msp->ms_allocated_this_txg);
e51be066 2913 } else {
d2734cce
SD
2914 range_tree_vacate(msp->ms_freeing,
2915 range_tree_add, msp->ms_freed);
34dc7c2f 2916 }
425d3237 2917 msp->ms_allocated_this_txg += range_tree_space(alloctree);
f3a7f661 2918 range_tree_vacate(alloctree, NULL, NULL);
34dc7c2f 2919
d2734cce
SD
2920 ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
2921 ASSERT0(range_tree_space(msp->ms_allocating[TXG_CLEAN(txg)
2922 & TXG_MASK]));
2923 ASSERT0(range_tree_space(msp->ms_freeing));
2924 ASSERT0(range_tree_space(msp->ms_checkpointing));
34dc7c2f
BB
2925
2926 mutex_exit(&msp->ms_lock);
2927
93cf2076
GW
2928 if (object != space_map_object(msp->ms_sm)) {
2929 object = space_map_object(msp->ms_sm);
2930 dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
2931 msp->ms_id, sizeof (uint64_t), &object, tx);
2932 }
a1d477c2 2933 mutex_exit(&msp->ms_sync_lock);
34dc7c2f
BB
2934 dmu_tx_commit(tx);
2935}
2936
2937/*
2938 * Called after a transaction group has completely synced to mark
2939 * all of the metaslab's free space as usable.
2940 */
2941void
2942metaslab_sync_done(metaslab_t *msp, uint64_t txg)
2943{
34dc7c2f
BB
2944 metaslab_group_t *mg = msp->ms_group;
2945 vdev_t *vd = mg->mg_vd;
4e21fd06 2946 spa_t *spa = vd->vdev_spa;
93cf2076 2947 range_tree_t **defer_tree;
428870ff 2948 int64_t alloc_delta, defer_delta;
4e21fd06 2949 boolean_t defer_allowed = B_TRUE;
428870ff
BB
2950
2951 ASSERT(!vd->vdev_ishole);
34dc7c2f
BB
2952
2953 mutex_enter(&msp->ms_lock);
2954
2955 /*
2956 * If this metaslab is just becoming available, initialize its
258553d3 2957 * range trees and add its capacity to the vdev.
34dc7c2f 2958 */
d2734cce 2959 if (msp->ms_freed == NULL) {
1c27024e 2960 for (int t = 0; t < TXG_SIZE; t++) {
d2734cce 2961 ASSERT(msp->ms_allocating[t] == NULL);
93cf2076 2962
d2734cce 2963 msp->ms_allocating[t] = range_tree_create(NULL, NULL);
34dc7c2f 2964 }
428870ff 2965
d2734cce
SD
2966 ASSERT3P(msp->ms_freeing, ==, NULL);
2967 msp->ms_freeing = range_tree_create(NULL, NULL);
258553d3 2968
d2734cce
SD
2969 ASSERT3P(msp->ms_freed, ==, NULL);
2970 msp->ms_freed = range_tree_create(NULL, NULL);
258553d3 2971
1c27024e 2972 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
d2734cce 2973 ASSERT(msp->ms_defer[t] == NULL);
e51be066 2974
d2734cce 2975 msp->ms_defer[t] = range_tree_create(NULL, NULL);
93cf2076 2976 }
428870ff 2977
d2734cce
SD
2978 ASSERT3P(msp->ms_checkpointing, ==, NULL);
2979 msp->ms_checkpointing = range_tree_create(NULL, NULL);
2980
cc99f275 2981 metaslab_space_update(vd, mg->mg_class, 0, 0, msp->ms_size);
34dc7c2f 2982 }
d2734cce
SD
2983 ASSERT0(range_tree_space(msp->ms_freeing));
2984 ASSERT0(range_tree_space(msp->ms_checkpointing));
34dc7c2f 2985
d2734cce 2986 defer_tree = &msp->ms_defer[txg % TXG_DEFER_SIZE];
93cf2076 2987
1c27024e 2988 uint64_t free_space = metaslab_class_get_space(spa_normal_class(spa)) -
4e21fd06 2989 metaslab_class_get_alloc(spa_normal_class(spa));
a1d477c2 2990 if (free_space <= spa_get_slop_space(spa) || vd->vdev_removing) {
4e21fd06
DB
2991 defer_allowed = B_FALSE;
2992 }
2993
2994 defer_delta = 0;
425d3237
SD
2995 alloc_delta = msp->ms_allocated_this_txg -
2996 range_tree_space(msp->ms_freed);
4e21fd06 2997 if (defer_allowed) {
d2734cce 2998 defer_delta = range_tree_space(msp->ms_freed) -
4e21fd06
DB
2999 range_tree_space(*defer_tree);
3000 } else {
3001 defer_delta -= range_tree_space(*defer_tree);
3002 }
428870ff 3003
cc99f275
DB
3004 metaslab_space_update(vd, mg->mg_class, alloc_delta + defer_delta,
3005 defer_delta, 0);
34dc7c2f 3006
34dc7c2f 3007 /*
93cf2076 3008 * If there's a metaslab_load() in progress, wait for it to complete
34dc7c2f 3009 * so that we have a consistent view of the in-core space map.
34dc7c2f 3010 */
93cf2076 3011 metaslab_load_wait(msp);
c2e42f9d 3012
1b939560
BB
3013 /*
3014 * When auto-trimming is enabled, free ranges which are added to
3015 * ms_allocatable are also be added to ms_trim. The ms_trim tree is
3016 * periodically consumed by the vdev_autotrim_thread() which issues
3017 * trims for all ranges and then vacates the tree. The ms_trim tree
3018 * can be discarded at any time with the sole consequence of recent
3019 * frees not being trimmed.
3020 */
3021 if (spa_get_autotrim(spa) == SPA_AUTOTRIM_ON) {
3022 range_tree_walk(*defer_tree, range_tree_add, msp->ms_trim);
3023 if (!defer_allowed) {
3024 range_tree_walk(msp->ms_freed, range_tree_add,
3025 msp->ms_trim);
3026 }
3027 } else {
3028 range_tree_vacate(msp->ms_trim, NULL, NULL);
3029 }
3030
c2e42f9d 3031 /*
93cf2076 3032 * Move the frees from the defer_tree back to the free
d2734cce
SD
3033 * range tree (if it's loaded). Swap the freed_tree and
3034 * the defer_tree -- this is safe to do because we've
3035 * just emptied out the defer_tree.
c2e42f9d 3036 */
93cf2076 3037 range_tree_vacate(*defer_tree,
d2734cce 3038 msp->ms_loaded ? range_tree_add : NULL, msp->ms_allocatable);
4e21fd06 3039 if (defer_allowed) {
d2734cce 3040 range_tree_swap(&msp->ms_freed, defer_tree);
4e21fd06 3041 } else {
d2734cce
SD
3042 range_tree_vacate(msp->ms_freed,
3043 msp->ms_loaded ? range_tree_add : NULL,
3044 msp->ms_allocatable);
4e21fd06 3045 }
425d3237
SD
3046
3047 msp->ms_synced_length = space_map_length(msp->ms_sm);
34dc7c2f 3048
428870ff
BB
3049 msp->ms_deferspace += defer_delta;
3050 ASSERT3S(msp->ms_deferspace, >=, 0);
93cf2076 3051 ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
428870ff
BB
3052 if (msp->ms_deferspace != 0) {
3053 /*
3054 * Keep syncing this metaslab until all deferred frees
3055 * are back in circulation.
3056 */
3057 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
3058 }
928e8ad4 3059 metaslab_aux_histograms_update_done(msp, defer_allowed);
428870ff 3060
492f64e9
PD
3061 if (msp->ms_new) {
3062 msp->ms_new = B_FALSE;
3063 mutex_enter(&mg->mg_lock);
3064 mg->mg_ms_ready++;
3065 mutex_exit(&mg->mg_lock);
3066 }
928e8ad4 3067
4e21fd06 3068 /*
928e8ad4
SD
3069 * Re-sort metaslab within its group now that we've adjusted
3070 * its allocatable space.
4e21fd06 3071 */
928e8ad4 3072 metaslab_recalculate_weight_and_sort(msp);
4e21fd06
DB
3073
3074 /*
3075 * If the metaslab is loaded and we've not tried to load or allocate
3076 * from it in 'metaslab_unload_delay' txgs, then unload it.
3077 */
3078 if (msp->ms_loaded &&
1b939560 3079 msp->ms_disabled == 0 &&
4e21fd06
DB
3080 msp->ms_selected_txg + metaslab_unload_delay < txg) {
3081
1c27024e 3082 for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
93cf2076 3083 VERIFY0(range_tree_space(
d2734cce 3084 msp->ms_allocating[(txg + t) & TXG_MASK]));
93cf2076 3085 }
492f64e9
PD
3086 if (msp->ms_allocator != -1) {
3087 metaslab_passivate(msp, msp->ms_weight &
3088 ~METASLAB_ACTIVE_MASK);
3089 }
34dc7c2f 3090
93cf2076
GW
3091 if (!metaslab_debug_unload)
3092 metaslab_unload(msp);
34dc7c2f
BB
3093 }
3094
d2734cce
SD
3095 ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
3096 ASSERT0(range_tree_space(msp->ms_freeing));
3097 ASSERT0(range_tree_space(msp->ms_freed));
3098 ASSERT0(range_tree_space(msp->ms_checkpointing));
a1d477c2 3099
425d3237 3100 msp->ms_allocated_this_txg = 0;
34dc7c2f
BB
3101 mutex_exit(&msp->ms_lock);
3102}
3103
428870ff
BB
3104void
3105metaslab_sync_reassess(metaslab_group_t *mg)
3106{
a1d477c2
MA
3107 spa_t *spa = mg->mg_class->mc_spa;
3108
3109 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
1be627f5 3110 metaslab_group_alloc_update(mg);
f3a7f661 3111 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
6d974228 3112
428870ff 3113 /*
a1d477c2
MA
3114 * Preload the next potential metaslabs but only on active
3115 * metaslab groups. We can get into a state where the metaslab
3116 * is no longer active since we dirty metaslabs as we remove a
3117 * a device, thus potentially making the metaslab group eligible
3118 * for preloading.
428870ff 3119 */
a1d477c2
MA
3120 if (mg->mg_activation_count > 0) {
3121 metaslab_group_preload(mg);
3122 }
3123 spa_config_exit(spa, SCL_ALLOC, FTAG);
428870ff
BB
3124}
3125
cc99f275
DB
3126/*
3127 * When writing a ditto block (i.e. more than one DVA for a given BP) on
3128 * the same vdev as an existing DVA of this BP, then try to allocate it
3129 * on a different metaslab than existing DVAs (i.e. a unique metaslab).
3130 */
3131static boolean_t
3132metaslab_is_unique(metaslab_t *msp, dva_t *dva)
34dc7c2f 3133{
cc99f275
DB
3134 uint64_t dva_ms_id;
3135
3136 if (DVA_GET_ASIZE(dva) == 0)
3137 return (B_TRUE);
34dc7c2f
BB
3138
3139 if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
cc99f275 3140 return (B_TRUE);
34dc7c2f 3141
cc99f275
DB
3142 dva_ms_id = DVA_GET_OFFSET(dva) >> msp->ms_group->mg_vd->vdev_ms_shift;
3143
3144 return (msp->ms_id != dva_ms_id);
34dc7c2f
BB
3145}
3146
4e21fd06
DB
3147/*
3148 * ==========================================================================
3149 * Metaslab allocation tracing facility
3150 * ==========================================================================
3151 */
3152#ifdef _METASLAB_TRACING
3153kstat_t *metaslab_trace_ksp;
3154kstat_named_t metaslab_trace_over_limit;
3155
3156void
3157metaslab_alloc_trace_init(void)
3158{
3159 ASSERT(metaslab_alloc_trace_cache == NULL);
3160 metaslab_alloc_trace_cache = kmem_cache_create(
3161 "metaslab_alloc_trace_cache", sizeof (metaslab_alloc_trace_t),
3162 0, NULL, NULL, NULL, NULL, NULL, 0);
3163 metaslab_trace_ksp = kstat_create("zfs", 0, "metaslab_trace_stats",
3164 "misc", KSTAT_TYPE_NAMED, 1, KSTAT_FLAG_VIRTUAL);
3165 if (metaslab_trace_ksp != NULL) {
3166 metaslab_trace_ksp->ks_data = &metaslab_trace_over_limit;
3167 kstat_named_init(&metaslab_trace_over_limit,
3168 "metaslab_trace_over_limit", KSTAT_DATA_UINT64);
3169 kstat_install(metaslab_trace_ksp);
3170 }
3171}
3172
3173void
3174metaslab_alloc_trace_fini(void)
3175{
3176 if (metaslab_trace_ksp != NULL) {
3177 kstat_delete(metaslab_trace_ksp);
3178 metaslab_trace_ksp = NULL;
3179 }
3180 kmem_cache_destroy(metaslab_alloc_trace_cache);
3181 metaslab_alloc_trace_cache = NULL;
3182}
3183
3184/*
3185 * Add an allocation trace element to the allocation tracing list.
3186 */
3187static void
3188metaslab_trace_add(zio_alloc_list_t *zal, metaslab_group_t *mg,
492f64e9
PD
3189 metaslab_t *msp, uint64_t psize, uint32_t dva_id, uint64_t offset,
3190 int allocator)
4e21fd06
DB
3191{
3192 metaslab_alloc_trace_t *mat;
3193
3194 if (!metaslab_trace_enabled)
3195 return;
3196
3197 /*
3198 * When the tracing list reaches its maximum we remove
3199 * the second element in the list before adding a new one.
3200 * By removing the second element we preserve the original
3201 * entry as a clue to what allocations steps have already been
3202 * performed.
3203 */
3204 if (zal->zal_size == metaslab_trace_max_entries) {
3205 metaslab_alloc_trace_t *mat_next;
3206#ifdef DEBUG
3207 panic("too many entries in allocation list");
3208#endif
3209 atomic_inc_64(&metaslab_trace_over_limit.value.ui64);
3210 zal->zal_size--;
3211 mat_next = list_next(&zal->zal_list, list_head(&zal->zal_list));
3212 list_remove(&zal->zal_list, mat_next);
3213 kmem_cache_free(metaslab_alloc_trace_cache, mat_next);
3214 }
3215
3216 mat = kmem_cache_alloc(metaslab_alloc_trace_cache, KM_SLEEP);
3217 list_link_init(&mat->mat_list_node);
3218 mat->mat_mg = mg;
3219 mat->mat_msp = msp;
3220 mat->mat_size = psize;
3221 mat->mat_dva_id = dva_id;
3222 mat->mat_offset = offset;
3223 mat->mat_weight = 0;
492f64e9 3224 mat->mat_allocator = allocator;
4e21fd06
DB
3225
3226 if (msp != NULL)
3227 mat->mat_weight = msp->ms_weight;
3228
3229 /*
3230 * The list is part of the zio so locking is not required. Only
3231 * a single thread will perform allocations for a given zio.
3232 */
3233 list_insert_tail(&zal->zal_list, mat);
3234 zal->zal_size++;
3235
3236 ASSERT3U(zal->zal_size, <=, metaslab_trace_max_entries);
3237}
3238
3239void
3240metaslab_trace_init(zio_alloc_list_t *zal)
3241{
3242 list_create(&zal->zal_list, sizeof (metaslab_alloc_trace_t),
3243 offsetof(metaslab_alloc_trace_t, mat_list_node));
3244 zal->zal_size = 0;
3245}
3246
3247void
3248metaslab_trace_fini(zio_alloc_list_t *zal)
3249{
3250 metaslab_alloc_trace_t *mat;
3251
3252 while ((mat = list_remove_head(&zal->zal_list)) != NULL)
3253 kmem_cache_free(metaslab_alloc_trace_cache, mat);
3254 list_destroy(&zal->zal_list);
3255 zal->zal_size = 0;
3256}
3257#else
3258
492f64e9 3259#define metaslab_trace_add(zal, mg, msp, psize, id, off, alloc)
4e21fd06
DB
3260
3261void
3262metaslab_alloc_trace_init(void)
3263{
3264}
3265
3266void
3267metaslab_alloc_trace_fini(void)
3268{
3269}
3270
3271void
3272metaslab_trace_init(zio_alloc_list_t *zal)
3273{
3274}
3275
3276void
3277metaslab_trace_fini(zio_alloc_list_t *zal)
3278{
3279}
3280
3281#endif /* _METASLAB_TRACING */
3282
3dfb57a3
DB
3283/*
3284 * ==========================================================================
3285 * Metaslab block operations
3286 * ==========================================================================
3287 */
3288
3289static void
492f64e9
PD
3290metaslab_group_alloc_increment(spa_t *spa, uint64_t vdev, void *tag, int flags,
3291 int allocator)
3dfb57a3 3292{
3dfb57a3 3293 if (!(flags & METASLAB_ASYNC_ALLOC) ||
492f64e9 3294 (flags & METASLAB_DONT_THROTTLE))
3dfb57a3
DB
3295 return;
3296
1c27024e 3297 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
3dfb57a3
DB
3298 if (!mg->mg_class->mc_alloc_throttle_enabled)
3299 return;
3300
c13060e4 3301 (void) zfs_refcount_add(&mg->mg_alloc_queue_depth[allocator], tag);
492f64e9
PD
3302}
3303
3304static void
3305metaslab_group_increment_qdepth(metaslab_group_t *mg, int allocator)
3306{
3307 uint64_t max = mg->mg_max_alloc_queue_depth;
3308 uint64_t cur = mg->mg_cur_max_alloc_queue_depth[allocator];
3309 while (cur < max) {
3310 if (atomic_cas_64(&mg->mg_cur_max_alloc_queue_depth[allocator],
3311 cur, cur + 1) == cur) {
3312 atomic_inc_64(
3313 &mg->mg_class->mc_alloc_max_slots[allocator]);
3314 return;
3315 }
3316 cur = mg->mg_cur_max_alloc_queue_depth[allocator];
3317 }
3dfb57a3
DB
3318}
3319
3320void
492f64e9
PD
3321metaslab_group_alloc_decrement(spa_t *spa, uint64_t vdev, void *tag, int flags,
3322 int allocator, boolean_t io_complete)
3dfb57a3 3323{
3dfb57a3 3324 if (!(flags & METASLAB_ASYNC_ALLOC) ||
492f64e9 3325 (flags & METASLAB_DONT_THROTTLE))
3dfb57a3
DB
3326 return;
3327
1c27024e 3328 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
3dfb57a3
DB
3329 if (!mg->mg_class->mc_alloc_throttle_enabled)
3330 return;
3331
424fd7c3 3332 (void) zfs_refcount_remove(&mg->mg_alloc_queue_depth[allocator], tag);
492f64e9
PD
3333 if (io_complete)
3334 metaslab_group_increment_qdepth(mg, allocator);
3dfb57a3
DB
3335}
3336
3337void
492f64e9
PD
3338metaslab_group_alloc_verify(spa_t *spa, const blkptr_t *bp, void *tag,
3339 int allocator)
3dfb57a3
DB
3340{
3341#ifdef ZFS_DEBUG
3342 const dva_t *dva = bp->blk_dva;
3343 int ndvas = BP_GET_NDVAS(bp);
3dfb57a3 3344
1c27024e 3345 for (int d = 0; d < ndvas; d++) {
3dfb57a3
DB
3346 uint64_t vdev = DVA_GET_VDEV(&dva[d]);
3347 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
424fd7c3
TS
3348 VERIFY(zfs_refcount_not_held(
3349 &mg->mg_alloc_queue_depth[allocator], tag));
3dfb57a3
DB
3350 }
3351#endif
3352}
3353
34dc7c2f 3354static uint64_t
4e21fd06
DB
3355metaslab_block_alloc(metaslab_t *msp, uint64_t size, uint64_t txg)
3356{
3357 uint64_t start;
d2734cce 3358 range_tree_t *rt = msp->ms_allocatable;
4e21fd06
DB
3359 metaslab_class_t *mc = msp->ms_group->mg_class;
3360
3361 VERIFY(!msp->ms_condensing);
1b939560 3362 VERIFY0(msp->ms_disabled);
4e21fd06
DB
3363
3364 start = mc->mc_ops->msop_alloc(msp, size);
3365 if (start != -1ULL) {
3366 metaslab_group_t *mg = msp->ms_group;
3367 vdev_t *vd = mg->mg_vd;
3368
3369 VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
3370 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
3371 VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
3372 range_tree_remove(rt, start, size);
1b939560 3373 range_tree_clear(msp->ms_trim, start, size);
4e21fd06 3374
d2734cce 3375 if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
4e21fd06
DB
3376 vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
3377
d2734cce 3378 range_tree_add(msp->ms_allocating[txg & TXG_MASK], start, size);
4e21fd06
DB
3379
3380 /* Track the last successful allocation */
3381 msp->ms_alloc_txg = txg;
3382 metaslab_verify_space(msp, txg);
3383 }
3384
3385 /*
3386 * Now that we've attempted the allocation we need to update the
3387 * metaslab's maximum block size since it may have changed.
3388 */
3389 msp->ms_max_size = metaslab_block_maxsize(msp);
3390 return (start);
3391}
3392
492f64e9
PD
3393/*
3394 * Find the metaslab with the highest weight that is less than what we've
3395 * already tried. In the common case, this means that we will examine each
3396 * metaslab at most once. Note that concurrent callers could reorder metaslabs
3397 * by activation/passivation once we have dropped the mg_lock. If a metaslab is
3398 * activated by another thread, and we fail to allocate from the metaslab we
3399 * have selected, we may not try the newly-activated metaslab, and instead
3400 * activate another metaslab. This is not optimal, but generally does not cause
3401 * any problems (a possible exception being if every metaslab is completely full
3402 * except for the the newly-activated metaslab which we fail to examine).
3403 */
3404static metaslab_t *
3405find_valid_metaslab(metaslab_group_t *mg, uint64_t activation_weight,
cc99f275 3406 dva_t *dva, int d, boolean_t want_unique, uint64_t asize, int allocator,
492f64e9
PD
3407 zio_alloc_list_t *zal, metaslab_t *search, boolean_t *was_active)
3408{
3409 avl_index_t idx;
3410 avl_tree_t *t = &mg->mg_metaslab_tree;
3411 metaslab_t *msp = avl_find(t, search, &idx);
3412 if (msp == NULL)
3413 msp = avl_nearest(t, idx, AVL_AFTER);
3414
3415 for (; msp != NULL; msp = AVL_NEXT(t, msp)) {
3416 int i;
3417 if (!metaslab_should_allocate(msp, asize)) {
3418 metaslab_trace_add(zal, mg, msp, asize, d,
3419 TRACE_TOO_SMALL, allocator);
3420 continue;
3421 }
3422
3423 /*
1b939560
BB
3424 * If the selected metaslab is condensing or disabled,
3425 * skip it.
492f64e9 3426 */
1b939560 3427 if (msp->ms_condensing || msp->ms_disabled > 0)
492f64e9
PD
3428 continue;
3429
3430 *was_active = msp->ms_allocator != -1;
3431 /*
3432 * If we're activating as primary, this is our first allocation
3433 * from this disk, so we don't need to check how close we are.
3434 * If the metaslab under consideration was already active,
3435 * we're getting desperate enough to steal another allocator's
3436 * metaslab, so we still don't care about distances.
3437 */
3438 if (activation_weight == METASLAB_WEIGHT_PRIMARY || *was_active)
3439 break;
3440
492f64e9 3441 for (i = 0; i < d; i++) {
cc99f275
DB
3442 if (want_unique &&
3443 !metaslab_is_unique(msp, &dva[i]))
3444 break; /* try another metaslab */
492f64e9
PD
3445 }
3446 if (i == d)
3447 break;
3448 }
3449
3450 if (msp != NULL) {
3451 search->ms_weight = msp->ms_weight;
3452 search->ms_start = msp->ms_start + 1;
3453 search->ms_allocator = msp->ms_allocator;
3454 search->ms_primary = msp->ms_primary;
3455 }
3456 return (msp);
3457}
3458
3459/* ARGSUSED */
4e21fd06
DB
3460static uint64_t
3461metaslab_group_alloc_normal(metaslab_group_t *mg, zio_alloc_list_t *zal,
cc99f275
DB
3462 uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva,
3463 int d, int allocator)
34dc7c2f
BB
3464{
3465 metaslab_t *msp = NULL;
3466 uint64_t offset = -1ULL;
34dc7c2f 3467 uint64_t activation_weight;
34dc7c2f
BB
3468
3469 activation_weight = METASLAB_WEIGHT_PRIMARY;
492f64e9
PD
3470 for (int i = 0; i < d; i++) {
3471 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
3472 DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
34dc7c2f 3473 activation_weight = METASLAB_WEIGHT_SECONDARY;
492f64e9
PD
3474 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
3475 DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
e38afd34 3476 activation_weight = METASLAB_WEIGHT_CLAIM;
9babb374
BB
3477 break;
3478 }
3479 }
34dc7c2f 3480
492f64e9
PD
3481 /*
3482 * If we don't have enough metaslabs active to fill the entire array, we
3483 * just use the 0th slot.
3484 */
e38afd34 3485 if (mg->mg_ms_ready < mg->mg_allocators * 3)
492f64e9 3486 allocator = 0;
492f64e9
PD
3487
3488 ASSERT3U(mg->mg_vd->vdev_ms_count, >=, 2);
3489
1c27024e 3490 metaslab_t *search = kmem_alloc(sizeof (*search), KM_SLEEP);
4e21fd06
DB
3491 search->ms_weight = UINT64_MAX;
3492 search->ms_start = 0;
492f64e9
PD
3493 /*
3494 * At the end of the metaslab tree are the already-active metaslabs,
3495 * first the primaries, then the secondaries. When we resume searching
3496 * through the tree, we need to consider ms_allocator and ms_primary so
3497 * we start in the location right after where we left off, and don't
3498 * accidentally loop forever considering the same metaslabs.
3499 */
3500 search->ms_allocator = -1;
3501 search->ms_primary = B_TRUE;
34dc7c2f 3502 for (;;) {
492f64e9 3503 boolean_t was_active = B_FALSE;
9babb374 3504
34dc7c2f 3505 mutex_enter(&mg->mg_lock);
4e21fd06 3506
492f64e9
PD
3507 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
3508 mg->mg_primaries[allocator] != NULL) {
3509 msp = mg->mg_primaries[allocator];
3510 was_active = B_TRUE;
3511 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
e38afd34 3512 mg->mg_secondaries[allocator] != NULL) {
492f64e9
PD
3513 msp = mg->mg_secondaries[allocator];
3514 was_active = B_TRUE;
3515 } else {
3516 msp = find_valid_metaslab(mg, activation_weight, dva, d,
cc99f275 3517 want_unique, asize, allocator, zal, search,
492f64e9 3518 &was_active);
34dc7c2f 3519 }
492f64e9 3520
34dc7c2f 3521 mutex_exit(&mg->mg_lock);
4e21fd06
DB
3522 if (msp == NULL) {
3523 kmem_free(search, sizeof (*search));
34dc7c2f 3524 return (-1ULL);
4e21fd06 3525 }
34dc7c2f 3526
ac72fac3 3527 mutex_enter(&msp->ms_lock);
34dc7c2f
BB
3528 /*
3529 * Ensure that the metaslab we have selected is still
3530 * capable of handling our request. It's possible that
3531 * another thread may have changed the weight while we
4e21fd06
DB
3532 * were blocked on the metaslab lock. We check the
3533 * active status first to see if we need to reselect
3534 * a new metaslab.
34dc7c2f 3535 */
4e21fd06 3536 if (was_active && !(msp->ms_weight & METASLAB_ACTIVE_MASK)) {
34dc7c2f
BB
3537 mutex_exit(&msp->ms_lock);
3538 continue;
3539 }
3540
492f64e9
PD
3541 /*
3542 * If the metaslab is freshly activated for an allocator that
3543 * isn't the one we're allocating from, or if it's a primary and
3544 * we're seeking a secondary (or vice versa), we go back and
3545 * select a new metaslab.
3546 */
3547 if (!was_active && (msp->ms_weight & METASLAB_ACTIVE_MASK) &&
3548 (msp->ms_allocator != -1) &&
3549 (msp->ms_allocator != allocator || ((activation_weight ==
3550 METASLAB_WEIGHT_PRIMARY) != msp->ms_primary))) {
3551 mutex_exit(&msp->ms_lock);
3552 continue;
3553 }
3554
e38afd34 3555 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM &&
3556 activation_weight != METASLAB_WEIGHT_CLAIM) {
492f64e9
PD
3557 metaslab_passivate(msp, msp->ms_weight &
3558 ~METASLAB_WEIGHT_CLAIM);
34dc7c2f
BB
3559 mutex_exit(&msp->ms_lock);
3560 continue;
3561 }
3562
492f64e9 3563 if (metaslab_activate(msp, allocator, activation_weight) != 0) {
34dc7c2f
BB
3564 mutex_exit(&msp->ms_lock);
3565 continue;
3566 }
492f64e9 3567
4e21fd06
DB
3568 msp->ms_selected_txg = txg;
3569
3570 /*
3571 * Now that we have the lock, recheck to see if we should
3572 * continue to use this metaslab for this allocation. The
3573 * the metaslab is now loaded so metaslab_should_allocate() can
3574 * accurately determine if the allocation attempt should
3575 * proceed.
3576 */
3577 if (!metaslab_should_allocate(msp, asize)) {
3578 /* Passivate this metaslab and select a new one. */
3579 metaslab_trace_add(zal, mg, msp, asize, d,
492f64e9 3580 TRACE_TOO_SMALL, allocator);
4e21fd06
DB
3581 goto next;
3582 }
3583
34dc7c2f 3584
7a614407
GW
3585 /*
3586 * If this metaslab is currently condensing then pick again as
3587 * we can't manipulate this metaslab until it's committed
619f0976
GW
3588 * to disk. If this metaslab is being initialized, we shouldn't
3589 * allocate from it since the allocated region might be
3590 * overwritten after allocation.
7a614407 3591 */
93cf2076 3592 if (msp->ms_condensing) {
4e21fd06 3593 metaslab_trace_add(zal, mg, msp, asize, d,
492f64e9
PD
3594 TRACE_CONDENSING, allocator);
3595 metaslab_passivate(msp, msp->ms_weight &
3596 ~METASLAB_ACTIVE_MASK);
7a614407
GW
3597 mutex_exit(&msp->ms_lock);
3598 continue;
1b939560 3599 } else if (msp->ms_disabled > 0) {
619f0976 3600 metaslab_trace_add(zal, mg, msp, asize, d,
1b939560 3601 TRACE_DISABLED, allocator);
619f0976
GW
3602 metaslab_passivate(msp, msp->ms_weight &
3603 ~METASLAB_ACTIVE_MASK);
3604 mutex_exit(&msp->ms_lock);
3605 continue;
7a614407
GW
3606 }
3607
4e21fd06 3608 offset = metaslab_block_alloc(msp, asize, txg);
492f64e9 3609 metaslab_trace_add(zal, mg, msp, asize, d, offset, allocator);
4e21fd06
DB
3610
3611 if (offset != -1ULL) {
3612 /* Proactively passivate the metaslab, if needed */
3613 metaslab_segment_may_passivate(msp);
34dc7c2f 3614 break;
4e21fd06
DB
3615 }
3616next:
3617 ASSERT(msp->ms_loaded);
3618
3619 /*
3620 * We were unable to allocate from this metaslab so determine
3621 * a new weight for this metaslab. Now that we have loaded
3622 * the metaslab we can provide a better hint to the metaslab
3623 * selector.
3624 *
3625 * For space-based metaslabs, we use the maximum block size.
3626 * This information is only available when the metaslab
3627 * is loaded and is more accurate than the generic free
3628 * space weight that was calculated by metaslab_weight().
3629 * This information allows us to quickly compare the maximum
3630 * available allocation in the metaslab to the allocation
3631 * size being requested.
3632 *
3633 * For segment-based metaslabs, determine the new weight
3634 * based on the highest bucket in the range tree. We
3635 * explicitly use the loaded segment weight (i.e. the range
3636 * tree histogram) since it contains the space that is
3637 * currently available for allocation and is accurate
3638 * even within a sync pass.
3639 */
3640 if (WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
3641 uint64_t weight = metaslab_block_maxsize(msp);
3642 WEIGHT_SET_SPACEBASED(weight);
3643 metaslab_passivate(msp, weight);
3644 } else {
3645 metaslab_passivate(msp,
3646 metaslab_weight_from_range_tree(msp));
3647 }
34dc7c2f 3648
4e21fd06
DB
3649 /*
3650 * We have just failed an allocation attempt, check
3651 * that metaslab_should_allocate() agrees. Otherwise,
3652 * we may end up in an infinite loop retrying the same
3653 * metaslab.
3654 */
3655 ASSERT(!metaslab_should_allocate(msp, asize));
cc99f275 3656
34dc7c2f
BB
3657 mutex_exit(&msp->ms_lock);
3658 }
4e21fd06
DB
3659 mutex_exit(&msp->ms_lock);
3660 kmem_free(search, sizeof (*search));
3661 return (offset);
3662}
34dc7c2f 3663
4e21fd06
DB
3664static uint64_t
3665metaslab_group_alloc(metaslab_group_t *mg, zio_alloc_list_t *zal,
cc99f275
DB
3666 uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva,
3667 int d, int allocator)
4e21fd06
DB
3668{
3669 uint64_t offset;
3670 ASSERT(mg->mg_initialized);
34dc7c2f 3671
cc99f275
DB
3672 offset = metaslab_group_alloc_normal(mg, zal, asize, txg, want_unique,
3673 dva, d, allocator);
34dc7c2f 3674
4e21fd06
DB
3675 mutex_enter(&mg->mg_lock);
3676 if (offset == -1ULL) {
3677 mg->mg_failed_allocations++;
3678 metaslab_trace_add(zal, mg, NULL, asize, d,
492f64e9 3679 TRACE_GROUP_FAILURE, allocator);
4e21fd06
DB
3680 if (asize == SPA_GANGBLOCKSIZE) {
3681 /*
3682 * This metaslab group was unable to allocate
3683 * the minimum gang block size so it must be out of
3684 * space. We must notify the allocation throttle
3685 * to start skipping allocation attempts to this
3686 * metaslab group until more space becomes available.
3687 * Note: this failure cannot be caused by the
3688 * allocation throttle since the allocation throttle
3689 * is only responsible for skipping devices and
3690 * not failing block allocations.
3691 */
3692 mg->mg_no_free_space = B_TRUE;
3693 }
3694 }
3695 mg->mg_allocations++;
3696 mutex_exit(&mg->mg_lock);
34dc7c2f
BB
3697 return (offset);
3698}
3699
3700/*
3701 * Allocate a block for the specified i/o.
3702 */
a1d477c2 3703int
34dc7c2f 3704metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
4e21fd06 3705 dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags,
492f64e9 3706 zio_alloc_list_t *zal, int allocator)
34dc7c2f 3707{
920dd524 3708 metaslab_group_t *mg, *fast_mg, *rotor;
34dc7c2f 3709 vdev_t *vd;
4e21fd06 3710 boolean_t try_hard = B_FALSE;
34dc7c2f
BB
3711
3712 ASSERT(!DVA_IS_VALID(&dva[d]));
3713
3714 /*
3715 * For testing, make some blocks above a certain size be gang blocks.
09b85f2d
BB
3716 * This will result in more split blocks when using device removal,
3717 * and a large number of split blocks coupled with ztest-induced
3718 * damage can result in extremely long reconstruction times. This
3719 * will also test spilling from special to normal.
34dc7c2f 3720 */
09b85f2d 3721 if (psize >= metaslab_force_ganging && (spa_get_random(100) < 3)) {
492f64e9
PD
3722 metaslab_trace_add(zal, NULL, NULL, psize, d, TRACE_FORCE_GANG,
3723 allocator);
2e528b49 3724 return (SET_ERROR(ENOSPC));
4e21fd06 3725 }
34dc7c2f
BB
3726
3727 /*
3728 * Start at the rotor and loop through all mgs until we find something.
428870ff 3729 * Note that there's no locking on mc_rotor or mc_aliquot because
34dc7c2f
BB
3730 * nothing actually breaks if we miss a few updates -- we just won't
3731 * allocate quite as evenly. It all balances out over time.
3732 *
3733 * If we are doing ditto or log blocks, try to spread them across
3734 * consecutive vdevs. If we're forced to reuse a vdev before we've
3735 * allocated all of our ditto blocks, then try and spread them out on
3736 * that vdev as much as possible. If it turns out to not be possible,
3737 * gradually lower our standards until anything becomes acceptable.
3738 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
3739 * gives us hope of containing our fault domains to something we're
3740 * able to reason about. Otherwise, any two top-level vdev failures
3741 * will guarantee the loss of data. With consecutive allocation,
3742 * only two adjacent top-level vdev failures will result in data loss.
3743 *
3744 * If we are doing gang blocks (hintdva is non-NULL), try to keep
3745 * ourselves on the same vdev as our gang block header. That
3746 * way, we can hope for locality in vdev_cache, plus it makes our
3747 * fault domains something tractable.
3748 */
3749 if (hintdva) {
3750 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
428870ff
BB
3751
3752 /*
3753 * It's possible the vdev we're using as the hint no
a1d477c2
MA
3754 * longer exists or its mg has been closed (e.g. by
3755 * device removal). Consult the rotor when
428870ff
BB
3756 * all else fails.
3757 */
a1d477c2 3758 if (vd != NULL && vd->vdev_mg != NULL) {
34dc7c2f 3759 mg = vd->vdev_mg;
428870ff
BB
3760
3761 if (flags & METASLAB_HINTBP_AVOID &&
3762 mg->mg_next != NULL)
3763 mg = mg->mg_next;
3764 } else {
3765 mg = mc->mc_rotor;
3766 }
34dc7c2f
BB
3767 } else if (d != 0) {
3768 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
3769 mg = vd->vdev_mg->mg_next;
920dd524
ED
3770 } else if (flags & METASLAB_FASTWRITE) {
3771 mg = fast_mg = mc->mc_rotor;
3772
3773 do {
3774 if (fast_mg->mg_vd->vdev_pending_fastwrite <
3775 mg->mg_vd->vdev_pending_fastwrite)
3776 mg = fast_mg;
3777 } while ((fast_mg = fast_mg->mg_next) != mc->mc_rotor);
3778
34dc7c2f 3779 } else {
cc99f275 3780 ASSERT(mc->mc_rotor != NULL);
34dc7c2f
BB
3781 mg = mc->mc_rotor;
3782 }
3783
3784 /*
428870ff
BB
3785 * If the hint put us into the wrong metaslab class, or into a
3786 * metaslab group that has been passivated, just follow the rotor.
34dc7c2f 3787 */
428870ff 3788 if (mg->mg_class != mc || mg->mg_activation_count <= 0)
34dc7c2f
BB
3789 mg = mc->mc_rotor;
3790
3791 rotor = mg;
3792top:
34dc7c2f 3793 do {
4e21fd06 3794 boolean_t allocatable;
428870ff 3795
3dfb57a3 3796 ASSERT(mg->mg_activation_count == 1);
34dc7c2f 3797 vd = mg->mg_vd;
fb5f0bc8 3798
34dc7c2f 3799 /*
b128c09f 3800 * Don't allocate from faulted devices.
34dc7c2f 3801 */
4e21fd06 3802 if (try_hard) {
fb5f0bc8
BB
3803 spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
3804 allocatable = vdev_allocatable(vd);
3805 spa_config_exit(spa, SCL_ZIO, FTAG);
3806 } else {
3807 allocatable = vdev_allocatable(vd);
3808 }
ac72fac3
GW
3809
3810 /*
3811 * Determine if the selected metaslab group is eligible
3dfb57a3
DB
3812 * for allocations. If we're ganging then don't allow
3813 * this metaslab group to skip allocations since that would
3814 * inadvertently return ENOSPC and suspend the pool
ac72fac3
GW
3815 * even though space is still available.
3816 */
4e21fd06 3817 if (allocatable && !GANG_ALLOCATION(flags) && !try_hard) {
3dfb57a3 3818 allocatable = metaslab_group_allocatable(mg, rotor,
c197a77c 3819 psize, allocator, d);
3dfb57a3 3820 }
ac72fac3 3821
4e21fd06
DB
3822 if (!allocatable) {
3823 metaslab_trace_add(zal, mg, NULL, psize, d,
492f64e9 3824 TRACE_NOT_ALLOCATABLE, allocator);
34dc7c2f 3825 goto next;
4e21fd06 3826 }
fb5f0bc8 3827
3dfb57a3
DB
3828 ASSERT(mg->mg_initialized);
3829
34dc7c2f 3830 /*
4e21fd06
DB
3831 * Avoid writing single-copy data to a failing,
3832 * non-redundant vdev, unless we've already tried all
3833 * other vdevs.
34dc7c2f
BB
3834 */
3835 if ((vd->vdev_stat.vs_write_errors > 0 ||
3836 vd->vdev_state < VDEV_STATE_HEALTHY) &&
4e21fd06
DB
3837 d == 0 && !try_hard && vd->vdev_children == 0) {
3838 metaslab_trace_add(zal, mg, NULL, psize, d,
492f64e9 3839 TRACE_VDEV_ERROR, allocator);
34dc7c2f
BB
3840 goto next;
3841 }
3842
3843 ASSERT(mg->mg_class == mc);
3844
1c27024e 3845 uint64_t asize = vdev_psize_to_asize(vd, psize);
34dc7c2f
BB
3846 ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
3847
cc99f275
DB
3848 /*
3849 * If we don't need to try hard, then require that the
3850 * block be on an different metaslab from any other DVAs
3851 * in this BP (unique=true). If we are trying hard, then
3852 * allow any metaslab to be used (unique=false).
3853 */
1c27024e 3854 uint64_t offset = metaslab_group_alloc(mg, zal, asize, txg,
cc99f275 3855 !try_hard, dva, d, allocator);
3dfb57a3 3856
34dc7c2f
BB
3857 if (offset != -1ULL) {
3858 /*
3859 * If we've just selected this metaslab group,
3860 * figure out whether the corresponding vdev is
3861 * over- or under-used relative to the pool,
3862 * and set an allocation bias to even it out.
bb3250d0
ED
3863 *
3864 * Bias is also used to compensate for unequally
3865 * sized vdevs so that space is allocated fairly.
34dc7c2f 3866 */
f3a7f661 3867 if (mc->mc_aliquot == 0 && metaslab_bias_enabled) {
34dc7c2f 3868 vdev_stat_t *vs = &vd->vdev_stat;
bb3250d0
ED
3869 int64_t vs_free = vs->vs_space - vs->vs_alloc;
3870 int64_t mc_free = mc->mc_space - mc->mc_alloc;
3871 int64_t ratio;
34dc7c2f
BB
3872
3873 /*
6d974228
GW
3874 * Calculate how much more or less we should
3875 * try to allocate from this device during
3876 * this iteration around the rotor.
6d974228 3877 *
bb3250d0
ED
3878 * This basically introduces a zero-centered
3879 * bias towards the devices with the most
3880 * free space, while compensating for vdev
3881 * size differences.
3882 *
3883 * Examples:
3884 * vdev V1 = 16M/128M
3885 * vdev V2 = 16M/128M
3886 * ratio(V1) = 100% ratio(V2) = 100%
3887 *
3888 * vdev V1 = 16M/128M
3889 * vdev V2 = 64M/128M
3890 * ratio(V1) = 127% ratio(V2) = 72%
6d974228 3891 *
bb3250d0
ED
3892 * vdev V1 = 16M/128M
3893 * vdev V2 = 64M/512M
3894 * ratio(V1) = 40% ratio(V2) = 160%
34dc7c2f 3895 */
bb3250d0
ED
3896 ratio = (vs_free * mc->mc_alloc_groups * 100) /
3897 (mc_free + 1);
3898 mg->mg_bias = ((ratio - 100) *
6d974228 3899 (int64_t)mg->mg_aliquot) / 100;
f3a7f661
GW
3900 } else if (!metaslab_bias_enabled) {
3901 mg->mg_bias = 0;
34dc7c2f
BB
3902 }
3903
920dd524
ED
3904 if ((flags & METASLAB_FASTWRITE) ||
3905 atomic_add_64_nv(&mc->mc_aliquot, asize) >=
34dc7c2f
BB
3906 mg->mg_aliquot + mg->mg_bias) {
3907 mc->mc_rotor = mg->mg_next;
428870ff 3908 mc->mc_aliquot = 0;
34dc7c2f
BB
3909 }
3910
3911 DVA_SET_VDEV(&dva[d], vd->vdev_id);
3912 DVA_SET_OFFSET(&dva[d], offset);
e3e7cf60
D
3913 DVA_SET_GANG(&dva[d],
3914 ((flags & METASLAB_GANG_HEADER) ? 1 : 0));
34dc7c2f
BB
3915 DVA_SET_ASIZE(&dva[d], asize);
3916
920dd524
ED
3917 if (flags & METASLAB_FASTWRITE) {
3918 atomic_add_64(&vd->vdev_pending_fastwrite,
3919 psize);
920dd524
ED
3920 }
3921
34dc7c2f
BB
3922 return (0);
3923 }
3924next:
3925 mc->mc_rotor = mg->mg_next;
428870ff 3926 mc->mc_aliquot = 0;
34dc7c2f
BB
3927 } while ((mg = mg->mg_next) != rotor);
3928
4e21fd06
DB
3929 /*
3930 * If we haven't tried hard, do so now.
3931 */
3932 if (!try_hard) {
3933 try_hard = B_TRUE;
fb5f0bc8
BB
3934 goto top;
3935 }
3936
34dc7c2f
BB
3937 bzero(&dva[d], sizeof (dva_t));
3938
492f64e9 3939 metaslab_trace_add(zal, rotor, NULL, psize, d, TRACE_ENOSPC, allocator);
2e528b49 3940 return (SET_ERROR(ENOSPC));
34dc7c2f
BB
3941}
3942
a1d477c2
MA
3943void
3944metaslab_free_concrete(vdev_t *vd, uint64_t offset, uint64_t asize,
d2734cce 3945 boolean_t checkpoint)
a1d477c2
MA
3946{
3947 metaslab_t *msp;
d2734cce 3948 spa_t *spa = vd->vdev_spa;
a1d477c2 3949
a1d477c2
MA
3950 ASSERT(vdev_is_concrete(vd));
3951 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
3952 ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
3953
3954 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3955
3956 VERIFY(!msp->ms_condensing);
3957 VERIFY3U(offset, >=, msp->ms_start);
3958 VERIFY3U(offset + asize, <=, msp->ms_start + msp->ms_size);
3959 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
3960 VERIFY0(P2PHASE(asize, 1ULL << vd->vdev_ashift));
3961
3962 metaslab_check_free_impl(vd, offset, asize);
d2734cce 3963
a1d477c2 3964 mutex_enter(&msp->ms_lock);
d2734cce
SD
3965 if (range_tree_is_empty(msp->ms_freeing) &&
3966 range_tree_is_empty(msp->ms_checkpointing)) {
3967 vdev_dirty(vd, VDD_METASLAB, msp, spa_syncing_txg(spa));
3968 }
3969
3970 if (checkpoint) {
3971 ASSERT(spa_has_checkpoint(spa));
3972 range_tree_add(msp->ms_checkpointing, offset, asize);
3973 } else {
3974 range_tree_add(msp->ms_freeing, offset, asize);
a1d477c2 3975 }
a1d477c2
MA
3976 mutex_exit(&msp->ms_lock);
3977}
3978
3979/* ARGSUSED */
3980void
3981metaslab_free_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
3982 uint64_t size, void *arg)
3983{
d2734cce
SD
3984 boolean_t *checkpoint = arg;
3985
3986 ASSERT3P(checkpoint, !=, NULL);
a1d477c2
MA
3987
3988 if (vd->vdev_ops->vdev_op_remap != NULL)
d2734cce 3989 vdev_indirect_mark_obsolete(vd, offset, size);
a1d477c2 3990 else
d2734cce 3991 metaslab_free_impl(vd, offset, size, *checkpoint);
a1d477c2
MA
3992}
3993
3994static void
3995metaslab_free_impl(vdev_t *vd, uint64_t offset, uint64_t size,
d2734cce 3996 boolean_t checkpoint)
a1d477c2
MA
3997{
3998 spa_t *spa = vd->vdev_spa;
3999
4000 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
4001
d2734cce 4002 if (spa_syncing_txg(spa) > spa_freeze_txg(spa))
a1d477c2
MA
4003 return;
4004
4005 if (spa->spa_vdev_removal != NULL &&
9e052db4 4006 spa->spa_vdev_removal->svr_vdev_id == vd->vdev_id &&
a1d477c2
MA
4007 vdev_is_concrete(vd)) {
4008 /*
4009 * Note: we check if the vdev is concrete because when
4010 * we complete the removal, we first change the vdev to be
4011 * an indirect vdev (in open context), and then (in syncing
4012 * context) clear spa_vdev_removal.
4013 */
d2734cce 4014 free_from_removing_vdev(vd, offset, size);
a1d477c2 4015 } else if (vd->vdev_ops->vdev_op_remap != NULL) {
d2734cce 4016 vdev_indirect_mark_obsolete(vd, offset, size);
a1d477c2 4017 vd->vdev_ops->vdev_op_remap(vd, offset, size,
d2734cce 4018 metaslab_free_impl_cb, &checkpoint);
a1d477c2 4019 } else {
d2734cce 4020 metaslab_free_concrete(vd, offset, size, checkpoint);
a1d477c2
MA
4021 }
4022}
4023
4024typedef struct remap_blkptr_cb_arg {
4025 blkptr_t *rbca_bp;
4026 spa_remap_cb_t rbca_cb;
4027 vdev_t *rbca_remap_vd;
4028 uint64_t rbca_remap_offset;
4029 void *rbca_cb_arg;
4030} remap_blkptr_cb_arg_t;
4031
4032void
4033remap_blkptr_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
4034 uint64_t size, void *arg)
4035{
4036 remap_blkptr_cb_arg_t *rbca = arg;
4037 blkptr_t *bp = rbca->rbca_bp;
4038
4039 /* We can not remap split blocks. */
4040 if (size != DVA_GET_ASIZE(&bp->blk_dva[0]))
4041 return;
4042 ASSERT0(inner_offset);
4043
4044 if (rbca->rbca_cb != NULL) {
4045 /*
4046 * At this point we know that we are not handling split
4047 * blocks and we invoke the callback on the previous
4048 * vdev which must be indirect.
4049 */
4050 ASSERT3P(rbca->rbca_remap_vd->vdev_ops, ==, &vdev_indirect_ops);
4051
4052 rbca->rbca_cb(rbca->rbca_remap_vd->vdev_id,
4053 rbca->rbca_remap_offset, size, rbca->rbca_cb_arg);
4054
4055 /* set up remap_blkptr_cb_arg for the next call */
4056 rbca->rbca_remap_vd = vd;
4057 rbca->rbca_remap_offset = offset;
4058 }
4059
4060 /*
4061 * The phys birth time is that of dva[0]. This ensures that we know
4062 * when each dva was written, so that resilver can determine which
4063 * blocks need to be scrubbed (i.e. those written during the time
4064 * the vdev was offline). It also ensures that the key used in
4065 * the ARC hash table is unique (i.e. dva[0] + phys_birth). If
4066 * we didn't change the phys_birth, a lookup in the ARC for a
4067 * remapped BP could find the data that was previously stored at
4068 * this vdev + offset.
4069 */
4070 vdev_t *oldvd = vdev_lookup_top(vd->vdev_spa,
4071 DVA_GET_VDEV(&bp->blk_dva[0]));
4072 vdev_indirect_births_t *vib = oldvd->vdev_indirect_births;
4073 bp->blk_phys_birth = vdev_indirect_births_physbirth(vib,
4074 DVA_GET_OFFSET(&bp->blk_dva[0]), DVA_GET_ASIZE(&bp->blk_dva[0]));
4075
4076 DVA_SET_VDEV(&bp->blk_dva[0], vd->vdev_id);
4077 DVA_SET_OFFSET(&bp->blk_dva[0], offset);
4078}
4079
34dc7c2f 4080/*
a1d477c2
MA
4081 * If the block pointer contains any indirect DVAs, modify them to refer to
4082 * concrete DVAs. Note that this will sometimes not be possible, leaving
4083 * the indirect DVA in place. This happens if the indirect DVA spans multiple
4084 * segments in the mapping (i.e. it is a "split block").
4085 *
4086 * If the BP was remapped, calls the callback on the original dva (note the
4087 * callback can be called multiple times if the original indirect DVA refers
4088 * to another indirect DVA, etc).
4089 *
4090 * Returns TRUE if the BP was remapped.
34dc7c2f 4091 */
a1d477c2
MA
4092boolean_t
4093spa_remap_blkptr(spa_t *spa, blkptr_t *bp, spa_remap_cb_t callback, void *arg)
34dc7c2f 4094{
a1d477c2
MA
4095 remap_blkptr_cb_arg_t rbca;
4096
4097 if (!zfs_remap_blkptr_enable)
4098 return (B_FALSE);
4099
4100 if (!spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS))
4101 return (B_FALSE);
4102
4103 /*
4104 * Dedup BP's can not be remapped, because ddt_phys_select() depends
4105 * on DVA[0] being the same in the BP as in the DDT (dedup table).
4106 */
4107 if (BP_GET_DEDUP(bp))
4108 return (B_FALSE);
4109
4110 /*
4111 * Gang blocks can not be remapped, because
4112 * zio_checksum_gang_verifier() depends on the DVA[0] that's in
4113 * the BP used to read the gang block header (GBH) being the same
4114 * as the DVA[0] that we allocated for the GBH.
4115 */
4116 if (BP_IS_GANG(bp))
4117 return (B_FALSE);
4118
4119 /*
4120 * Embedded BP's have no DVA to remap.
4121 */
4122 if (BP_GET_NDVAS(bp) < 1)
4123 return (B_FALSE);
4124
4125 /*
4126 * Note: we only remap dva[0]. If we remapped other dvas, we
4127 * would no longer know what their phys birth txg is.
4128 */
4129 dva_t *dva = &bp->blk_dva[0];
4130
34dc7c2f
BB
4131 uint64_t offset = DVA_GET_OFFSET(dva);
4132 uint64_t size = DVA_GET_ASIZE(dva);
a1d477c2
MA
4133 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
4134
4135 if (vd->vdev_ops->vdev_op_remap == NULL)
4136 return (B_FALSE);
4137
4138 rbca.rbca_bp = bp;
4139 rbca.rbca_cb = callback;
4140 rbca.rbca_remap_vd = vd;
4141 rbca.rbca_remap_offset = offset;
4142 rbca.rbca_cb_arg = arg;
4143
4144 /*
4145 * remap_blkptr_cb() will be called in order for each level of
4146 * indirection, until a concrete vdev is reached or a split block is
4147 * encountered. old_vd and old_offset are updated within the callback
4148 * as we go from the one indirect vdev to the next one (either concrete
4149 * or indirect again) in that order.
4150 */
4151 vd->vdev_ops->vdev_op_remap(vd, offset, size, remap_blkptr_cb, &rbca);
4152
4153 /* Check if the DVA wasn't remapped because it is a split block */
4154 if (DVA_GET_VDEV(&rbca.rbca_bp->blk_dva[0]) == vd->vdev_id)
4155 return (B_FALSE);
4156
4157 return (B_TRUE);
4158}
4159
4160/*
4161 * Undo the allocation of a DVA which happened in the given transaction group.
4162 */
4163void
4164metaslab_unalloc_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
4165{
34dc7c2f 4166 metaslab_t *msp;
a1d477c2
MA
4167 vdev_t *vd;
4168 uint64_t vdev = DVA_GET_VDEV(dva);
4169 uint64_t offset = DVA_GET_OFFSET(dva);
4170 uint64_t size = DVA_GET_ASIZE(dva);
4171
4172 ASSERT(DVA_IS_VALID(dva));
4173 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
34dc7c2f 4174
34dc7c2f
BB
4175 if (txg > spa_freeze_txg(spa))
4176 return;
4177
7d2868d5 4178 if ((vd = vdev_lookup_top(spa, vdev)) == NULL || !DVA_IS_VALID(dva) ||
34dc7c2f 4179 (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
7d2868d5
BB
4180 zfs_panic_recover("metaslab_free_dva(): bad DVA %llu:%llu:%llu",
4181 (u_longlong_t)vdev, (u_longlong_t)offset,
4182 (u_longlong_t)size);
34dc7c2f
BB
4183 return;
4184 }
4185
a1d477c2
MA
4186 ASSERT(!vd->vdev_removing);
4187 ASSERT(vdev_is_concrete(vd));
4188 ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
4189 ASSERT3P(vd->vdev_indirect_mapping, ==, NULL);
34dc7c2f
BB
4190
4191 if (DVA_GET_GANG(dva))
4192 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
4193
a1d477c2 4194 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
93cf2076 4195
a1d477c2 4196 mutex_enter(&msp->ms_lock);
d2734cce 4197 range_tree_remove(msp->ms_allocating[txg & TXG_MASK],
a1d477c2 4198 offset, size);
34dc7c2f 4199
a1d477c2
MA
4200 VERIFY(!msp->ms_condensing);
4201 VERIFY3U(offset, >=, msp->ms_start);
4202 VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
d2734cce 4203 VERIFY3U(range_tree_space(msp->ms_allocatable) + size, <=,
a1d477c2
MA
4204 msp->ms_size);
4205 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
4206 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
d2734cce 4207 range_tree_add(msp->ms_allocatable, offset, size);
34dc7c2f
BB
4208 mutex_exit(&msp->ms_lock);
4209}
4210
4211/*
d2734cce 4212 * Free the block represented by the given DVA.
34dc7c2f 4213 */
a1d477c2 4214void
d2734cce 4215metaslab_free_dva(spa_t *spa, const dva_t *dva, boolean_t checkpoint)
34dc7c2f
BB
4216{
4217 uint64_t vdev = DVA_GET_VDEV(dva);
4218 uint64_t offset = DVA_GET_OFFSET(dva);
4219 uint64_t size = DVA_GET_ASIZE(dva);
a1d477c2 4220 vdev_t *vd = vdev_lookup_top(spa, vdev);
34dc7c2f
BB
4221
4222 ASSERT(DVA_IS_VALID(dva));
a1d477c2 4223 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
34dc7c2f 4224
a1d477c2 4225 if (DVA_GET_GANG(dva)) {
34dc7c2f 4226 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
34dc7c2f
BB
4227 }
4228
d2734cce 4229 metaslab_free_impl(vd, offset, size, checkpoint);
34dc7c2f
BB
4230}
4231
3dfb57a3
DB
4232/*
4233 * Reserve some allocation slots. The reservation system must be called
4234 * before we call into the allocator. If there aren't any available slots
4235 * then the I/O will be throttled until an I/O completes and its slots are
4236 * freed up. The function returns true if it was successful in placing
4237 * the reservation.
4238 */
4239boolean_t
492f64e9
PD
4240metaslab_class_throttle_reserve(metaslab_class_t *mc, int slots, int allocator,
4241 zio_t *zio, int flags)
3dfb57a3
DB
4242{
4243 uint64_t available_slots = 0;
3dfb57a3 4244 boolean_t slot_reserved = B_FALSE;
492f64e9 4245 uint64_t max = mc->mc_alloc_max_slots[allocator];
3dfb57a3
DB
4246
4247 ASSERT(mc->mc_alloc_throttle_enabled);
4248 mutex_enter(&mc->mc_lock);
4249
492f64e9 4250 uint64_t reserved_slots =
424fd7c3 4251 zfs_refcount_count(&mc->mc_alloc_slots[allocator]);
492f64e9
PD
4252 if (reserved_slots < max)
4253 available_slots = max - reserved_slots;
3dfb57a3 4254
cc99f275
DB
4255 if (slots <= available_slots || GANG_ALLOCATION(flags) ||
4256 flags & METASLAB_MUST_RESERVE) {
3dfb57a3
DB
4257 /*
4258 * We reserve the slots individually so that we can unreserve
4259 * them individually when an I/O completes.
4260 */
1c27024e 4261 for (int d = 0; d < slots; d++) {
492f64e9 4262 reserved_slots =
c13060e4 4263 zfs_refcount_add(&mc->mc_alloc_slots[allocator],
492f64e9 4264 zio);
3dfb57a3
DB
4265 }
4266 zio->io_flags |= ZIO_FLAG_IO_ALLOCATING;
4267 slot_reserved = B_TRUE;
4268 }
4269
4270 mutex_exit(&mc->mc_lock);
4271 return (slot_reserved);
4272}
4273
4274void
492f64e9
PD
4275metaslab_class_throttle_unreserve(metaslab_class_t *mc, int slots,
4276 int allocator, zio_t *zio)
3dfb57a3 4277{
3dfb57a3
DB
4278 ASSERT(mc->mc_alloc_throttle_enabled);
4279 mutex_enter(&mc->mc_lock);
1c27024e 4280 for (int d = 0; d < slots; d++) {
424fd7c3 4281 (void) zfs_refcount_remove(&mc->mc_alloc_slots[allocator],
492f64e9 4282 zio);
3dfb57a3
DB
4283 }
4284 mutex_exit(&mc->mc_lock);
4285}
4286
a1d477c2
MA
4287static int
4288metaslab_claim_concrete(vdev_t *vd, uint64_t offset, uint64_t size,
4289 uint64_t txg)
4290{
4291 metaslab_t *msp;
4292 spa_t *spa = vd->vdev_spa;
4293 int error = 0;
4294
4295 if (offset >> vd->vdev_ms_shift >= vd->vdev_ms_count)
7ab96299 4296 return (SET_ERROR(ENXIO));
a1d477c2
MA
4297
4298 ASSERT3P(vd->vdev_ms, !=, NULL);
4299 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
4300
4301 mutex_enter(&msp->ms_lock);
4302
7ab96299 4303 if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded) {
492f64e9 4304 error = metaslab_activate(msp, 0, METASLAB_WEIGHT_CLAIM);
7ab96299
TC
4305 if (error == EBUSY) {
4306 ASSERT(msp->ms_loaded);
4307 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
4308 error = 0;
4309 }
4310 }
a1d477c2 4311
d2734cce
SD
4312 if (error == 0 &&
4313 !range_tree_contains(msp->ms_allocatable, offset, size))
a1d477c2
MA
4314 error = SET_ERROR(ENOENT);
4315
4316 if (error || txg == 0) { /* txg == 0 indicates dry run */
4317 mutex_exit(&msp->ms_lock);
4318 return (error);
4319 }
4320
4321 VERIFY(!msp->ms_condensing);
4322 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
4323 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
d2734cce
SD
4324 VERIFY3U(range_tree_space(msp->ms_allocatable) - size, <=,
4325 msp->ms_size);
4326 range_tree_remove(msp->ms_allocatable, offset, size);
1b939560 4327 range_tree_clear(msp->ms_trim, offset, size);
a1d477c2
MA
4328
4329 if (spa_writeable(spa)) { /* don't dirty if we're zdb(1M) */
d2734cce 4330 if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
a1d477c2 4331 vdev_dirty(vd, VDD_METASLAB, msp, txg);
d2734cce
SD
4332 range_tree_add(msp->ms_allocating[txg & TXG_MASK],
4333 offset, size);
a1d477c2
MA
4334 }
4335
4336 mutex_exit(&msp->ms_lock);
4337
4338 return (0);
4339}
4340
4341typedef struct metaslab_claim_cb_arg_t {
4342 uint64_t mcca_txg;
4343 int mcca_error;
4344} metaslab_claim_cb_arg_t;
4345
4346/* ARGSUSED */
4347static void
4348metaslab_claim_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
4349 uint64_t size, void *arg)
4350{
4351 metaslab_claim_cb_arg_t *mcca_arg = arg;
4352
4353 if (mcca_arg->mcca_error == 0) {
4354 mcca_arg->mcca_error = metaslab_claim_concrete(vd, offset,
4355 size, mcca_arg->mcca_txg);
4356 }
4357}
4358
4359int
4360metaslab_claim_impl(vdev_t *vd, uint64_t offset, uint64_t size, uint64_t txg)
4361{
4362 if (vd->vdev_ops->vdev_op_remap != NULL) {
4363 metaslab_claim_cb_arg_t arg;
4364
4365 /*
4366 * Only zdb(1M) can claim on indirect vdevs. This is used
4367 * to detect leaks of mapped space (that are not accounted
4368 * for in the obsolete counts, spacemap, or bpobj).
4369 */
4370 ASSERT(!spa_writeable(vd->vdev_spa));
4371 arg.mcca_error = 0;
4372 arg.mcca_txg = txg;
4373
4374 vd->vdev_ops->vdev_op_remap(vd, offset, size,
4375 metaslab_claim_impl_cb, &arg);
4376
4377 if (arg.mcca_error == 0) {
4378 arg.mcca_error = metaslab_claim_concrete(vd,
4379 offset, size, txg);
4380 }
4381 return (arg.mcca_error);
4382 } else {
4383 return (metaslab_claim_concrete(vd, offset, size, txg));
4384 }
4385}
4386
4387/*
4388 * Intent log support: upon opening the pool after a crash, notify the SPA
4389 * of blocks that the intent log has allocated for immediate write, but
4390 * which are still considered free by the SPA because the last transaction
4391 * group didn't commit yet.
4392 */
4393static int
4394metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
4395{
4396 uint64_t vdev = DVA_GET_VDEV(dva);
4397 uint64_t offset = DVA_GET_OFFSET(dva);
4398 uint64_t size = DVA_GET_ASIZE(dva);
4399 vdev_t *vd;
4400
4401 if ((vd = vdev_lookup_top(spa, vdev)) == NULL) {
4402 return (SET_ERROR(ENXIO));
4403 }
4404
4405 ASSERT(DVA_IS_VALID(dva));
4406
4407 if (DVA_GET_GANG(dva))
4408 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
4409
4410 return (metaslab_claim_impl(vd, offset, size, txg));
4411}
4412
34dc7c2f
BB
4413int
4414metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
4e21fd06 4415 int ndvas, uint64_t txg, blkptr_t *hintbp, int flags,
492f64e9 4416 zio_alloc_list_t *zal, zio_t *zio, int allocator)
34dc7c2f
BB
4417{
4418 dva_t *dva = bp->blk_dva;
928e8ad4 4419 dva_t *hintdva = (hintbp != NULL) ? hintbp->blk_dva : NULL;
1c27024e 4420 int error = 0;
34dc7c2f 4421
b128c09f 4422 ASSERT(bp->blk_birth == 0);
428870ff 4423 ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
b128c09f
BB
4424
4425 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
4426
4427 if (mc->mc_rotor == NULL) { /* no vdevs in this class */
4428 spa_config_exit(spa, SCL_ALLOC, FTAG);
2e528b49 4429 return (SET_ERROR(ENOSPC));
b128c09f 4430 }
34dc7c2f
BB
4431
4432 ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
4433 ASSERT(BP_GET_NDVAS(bp) == 0);
4434 ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
4e21fd06 4435 ASSERT3P(zal, !=, NULL);
34dc7c2f 4436
1c27024e 4437 for (int d = 0; d < ndvas; d++) {
34dc7c2f 4438 error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
492f64e9 4439 txg, flags, zal, allocator);
93cf2076 4440 if (error != 0) {
34dc7c2f 4441 for (d--; d >= 0; d--) {
a1d477c2 4442 metaslab_unalloc_dva(spa, &dva[d], txg);
3dfb57a3 4443 metaslab_group_alloc_decrement(spa,
492f64e9
PD
4444 DVA_GET_VDEV(&dva[d]), zio, flags,
4445 allocator, B_FALSE);
34dc7c2f
BB
4446 bzero(&dva[d], sizeof (dva_t));
4447 }
b128c09f 4448 spa_config_exit(spa, SCL_ALLOC, FTAG);
34dc7c2f 4449 return (error);
3dfb57a3
DB
4450 } else {
4451 /*
4452 * Update the metaslab group's queue depth
4453 * based on the newly allocated dva.
4454 */
4455 metaslab_group_alloc_increment(spa,
492f64e9 4456 DVA_GET_VDEV(&dva[d]), zio, flags, allocator);
34dc7c2f 4457 }
3dfb57a3 4458
34dc7c2f
BB
4459 }
4460 ASSERT(error == 0);
4461 ASSERT(BP_GET_NDVAS(bp) == ndvas);
4462
b128c09f
BB
4463 spa_config_exit(spa, SCL_ALLOC, FTAG);
4464
efe7978d 4465 BP_SET_BIRTH(bp, txg, 0);
b128c09f 4466
34dc7c2f
BB
4467 return (0);
4468}
4469
4470void
4471metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
4472{
4473 const dva_t *dva = bp->blk_dva;
1c27024e 4474 int ndvas = BP_GET_NDVAS(bp);
34dc7c2f
BB
4475
4476 ASSERT(!BP_IS_HOLE(bp));
428870ff 4477 ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
b128c09f 4478
d2734cce
SD
4479 /*
4480 * If we have a checkpoint for the pool we need to make sure that
4481 * the blocks that we free that are part of the checkpoint won't be
4482 * reused until the checkpoint is discarded or we revert to it.
4483 *
4484 * The checkpoint flag is passed down the metaslab_free code path
4485 * and is set whenever we want to add a block to the checkpoint's
4486 * accounting. That is, we "checkpoint" blocks that existed at the
4487 * time the checkpoint was created and are therefore referenced by
4488 * the checkpointed uberblock.
4489 *
4490 * Note that, we don't checkpoint any blocks if the current
4491 * syncing txg <= spa_checkpoint_txg. We want these frees to sync
4492 * normally as they will be referenced by the checkpointed uberblock.
4493 */
4494 boolean_t checkpoint = B_FALSE;
4495 if (bp->blk_birth <= spa->spa_checkpoint_txg &&
4496 spa_syncing_txg(spa) > spa->spa_checkpoint_txg) {
4497 /*
4498 * At this point, if the block is part of the checkpoint
4499 * there is no way it was created in the current txg.
4500 */
4501 ASSERT(!now);
4502 ASSERT3U(spa_syncing_txg(spa), ==, txg);
4503 checkpoint = B_TRUE;
4504 }
4505
b128c09f 4506 spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
34dc7c2f 4507
a1d477c2
MA
4508 for (int d = 0; d < ndvas; d++) {
4509 if (now) {
4510 metaslab_unalloc_dva(spa, &dva[d], txg);
4511 } else {
d2734cce
SD
4512 ASSERT3U(txg, ==, spa_syncing_txg(spa));
4513 metaslab_free_dva(spa, &dva[d], checkpoint);
a1d477c2
MA
4514 }
4515 }
b128c09f
BB
4516
4517 spa_config_exit(spa, SCL_FREE, FTAG);
34dc7c2f
BB
4518}
4519
4520int
4521metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
4522{
4523 const dva_t *dva = bp->blk_dva;
4524 int ndvas = BP_GET_NDVAS(bp);
1c27024e 4525 int error = 0;
34dc7c2f
BB
4526
4527 ASSERT(!BP_IS_HOLE(bp));
4528
b128c09f
BB
4529 if (txg != 0) {
4530 /*
4531 * First do a dry run to make sure all DVAs are claimable,
4532 * so we don't have to unwind from partial failures below.
4533 */
4534 if ((error = metaslab_claim(spa, bp, 0)) != 0)
4535 return (error);
4536 }
4537
4538 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
4539
cc99f275
DB
4540 for (int d = 0; d < ndvas; d++) {
4541 error = metaslab_claim_dva(spa, &dva[d], txg);
4542 if (error != 0)
b128c09f 4543 break;
cc99f275 4544 }
b128c09f
BB
4545
4546 spa_config_exit(spa, SCL_ALLOC, FTAG);
4547
4548 ASSERT(error == 0 || txg == 0);
34dc7c2f 4549
b128c09f 4550 return (error);
34dc7c2f 4551}
920dd524 4552
d1d7e268
MK
4553void
4554metaslab_fastwrite_mark(spa_t *spa, const blkptr_t *bp)
920dd524
ED
4555{
4556 const dva_t *dva = bp->blk_dva;
4557 int ndvas = BP_GET_NDVAS(bp);
4558 uint64_t psize = BP_GET_PSIZE(bp);
4559 int d;
4560 vdev_t *vd;
4561
4562 ASSERT(!BP_IS_HOLE(bp));
9b67f605 4563 ASSERT(!BP_IS_EMBEDDED(bp));
920dd524
ED
4564 ASSERT(psize > 0);
4565
4566 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
4567
4568 for (d = 0; d < ndvas; d++) {
4569 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
4570 continue;
4571 atomic_add_64(&vd->vdev_pending_fastwrite, psize);
4572 }
4573
4574 spa_config_exit(spa, SCL_VDEV, FTAG);
4575}
4576
d1d7e268
MK
4577void
4578metaslab_fastwrite_unmark(spa_t *spa, const blkptr_t *bp)
920dd524
ED
4579{
4580 const dva_t *dva = bp->blk_dva;
4581 int ndvas = BP_GET_NDVAS(bp);
4582 uint64_t psize = BP_GET_PSIZE(bp);
4583 int d;
4584 vdev_t *vd;
4585
4586 ASSERT(!BP_IS_HOLE(bp));
9b67f605 4587 ASSERT(!BP_IS_EMBEDDED(bp));
920dd524
ED
4588 ASSERT(psize > 0);
4589
4590 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
4591
4592 for (d = 0; d < ndvas; d++) {
4593 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
4594 continue;
4595 ASSERT3U(vd->vdev_pending_fastwrite, >=, psize);
4596 atomic_sub_64(&vd->vdev_pending_fastwrite, psize);
4597 }
4598
4599 spa_config_exit(spa, SCL_VDEV, FTAG);
4600}
30b92c1d 4601
a1d477c2
MA
4602/* ARGSUSED */
4603static void
4604metaslab_check_free_impl_cb(uint64_t inner, vdev_t *vd, uint64_t offset,
4605 uint64_t size, void *arg)
4606{
4607 if (vd->vdev_ops == &vdev_indirect_ops)
4608 return;
4609
4610 metaslab_check_free_impl(vd, offset, size);
4611}
4612
4613static void
4614metaslab_check_free_impl(vdev_t *vd, uint64_t offset, uint64_t size)
4615{
4616 metaslab_t *msp;
4617 ASSERTV(spa_t *spa = vd->vdev_spa);
4618
4619 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
4620 return;
4621
4622 if (vd->vdev_ops->vdev_op_remap != NULL) {
4623 vd->vdev_ops->vdev_op_remap(vd, offset, size,
4624 metaslab_check_free_impl_cb, NULL);
4625 return;
4626 }
4627
4628 ASSERT(vdev_is_concrete(vd));
4629 ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
4630 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
4631
4632 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
4633
4634 mutex_enter(&msp->ms_lock);
df72b8be
SD
4635 if (msp->ms_loaded) {
4636 range_tree_verify_not_present(msp->ms_allocatable,
4637 offset, size);
4638 }
a1d477c2 4639
1b939560 4640 range_tree_verify_not_present(msp->ms_trim, offset, size);
df72b8be
SD
4641 range_tree_verify_not_present(msp->ms_freeing, offset, size);
4642 range_tree_verify_not_present(msp->ms_checkpointing, offset, size);
4643 range_tree_verify_not_present(msp->ms_freed, offset, size);
a1d477c2 4644 for (int j = 0; j < TXG_DEFER_SIZE; j++)
df72b8be 4645 range_tree_verify_not_present(msp->ms_defer[j], offset, size);
a1d477c2
MA
4646 mutex_exit(&msp->ms_lock);
4647}
4648
13fe0198
MA
4649void
4650metaslab_check_free(spa_t *spa, const blkptr_t *bp)
4651{
13fe0198
MA
4652 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
4653 return;
4654
4655 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1c27024e 4656 for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
93cf2076
GW
4657 uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
4658 vdev_t *vd = vdev_lookup_top(spa, vdev);
4659 uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
13fe0198 4660 uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
13fe0198 4661
a1d477c2
MA
4662 if (DVA_GET_GANG(&bp->blk_dva[i]))
4663 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
4664
4665 ASSERT3P(vd, !=, NULL);
13fe0198 4666
a1d477c2 4667 metaslab_check_free_impl(vd, offset, size);
13fe0198
MA
4668 }
4669 spa_config_exit(spa, SCL_VDEV, FTAG);
4670}
4671
1b939560
BB
4672static void
4673metaslab_group_disable_wait(metaslab_group_t *mg)
4674{
4675 ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
4676 while (mg->mg_disabled_updating) {
4677 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
4678 }
4679}
4680
4681static void
4682metaslab_group_disabled_increment(metaslab_group_t *mg)
4683{
4684 ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
4685 ASSERT(mg->mg_disabled_updating);
4686
4687 while (mg->mg_ms_disabled >= max_disabled_ms) {
4688 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
4689 }
4690 mg->mg_ms_disabled++;
4691 ASSERT3U(mg->mg_ms_disabled, <=, max_disabled_ms);
4692}
4693
4694/*
4695 * Mark the metaslab as disabled to prevent any allocations on this metaslab.
4696 * We must also track how many metaslabs are currently disabled within a
4697 * metaslab group and limit them to prevent allocation failures from
4698 * occurring because all metaslabs are disabled.
4699 */
4700void
4701metaslab_disable(metaslab_t *msp)
4702{
4703 ASSERT(!MUTEX_HELD(&msp->ms_lock));
4704 metaslab_group_t *mg = msp->ms_group;
4705
4706 mutex_enter(&mg->mg_ms_disabled_lock);
4707
4708 /*
4709 * To keep an accurate count of how many threads have disabled
4710 * a specific metaslab group, we only allow one thread to mark
4711 * the metaslab group at a time. This ensures that the value of
4712 * ms_disabled will be accurate when we decide to mark a metaslab
4713 * group as disabled. To do this we force all other threads
4714 * to wait till the metaslab's mg_disabled_updating flag is no
4715 * longer set.
4716 */
4717 metaslab_group_disable_wait(mg);
4718 mg->mg_disabled_updating = B_TRUE;
4719 if (msp->ms_disabled == 0) {
4720 metaslab_group_disabled_increment(mg);
4721 }
4722 mutex_enter(&msp->ms_lock);
4723 msp->ms_disabled++;
4724 mutex_exit(&msp->ms_lock);
4725
4726 mg->mg_disabled_updating = B_FALSE;
4727 cv_broadcast(&mg->mg_ms_disabled_cv);
4728 mutex_exit(&mg->mg_ms_disabled_lock);
4729}
4730
4731void
4732metaslab_enable(metaslab_t *msp, boolean_t sync)
4733{
4734 metaslab_group_t *mg = msp->ms_group;
4735 spa_t *spa = mg->mg_vd->vdev_spa;
4736
4737 /*
4738 * Wait for the outstanding IO to be synced to prevent newly
4739 * allocated blocks from being overwritten. This used by
4740 * initialize and TRIM which are modifying unallocated space.
4741 */
4742 if (sync)
4743 txg_wait_synced(spa_get_dsl(spa), 0);
4744
4745 mutex_enter(&mg->mg_ms_disabled_lock);
4746 mutex_enter(&msp->ms_lock);
4747 if (--msp->ms_disabled == 0) {
4748 mg->mg_ms_disabled--;
4749 cv_broadcast(&mg->mg_ms_disabled_cv);
4750 }
4751 mutex_exit(&msp->ms_lock);
4752 mutex_exit(&mg->mg_ms_disabled_lock);
4753}
4754
93ce2b4c 4755#if defined(_KERNEL)
cc99f275 4756/* BEGIN CSTYLED */
99b14de4 4757module_param(metaslab_aliquot, ulong, 0644);
99b14de4
ED
4758MODULE_PARM_DESC(metaslab_aliquot,
4759 "allocation granularity (a.k.a. stripe size)");
02730c33
BB
4760
4761module_param(metaslab_debug_load, int, 0644);
93cf2076
GW
4762MODULE_PARM_DESC(metaslab_debug_load,
4763 "load all metaslabs when pool is first opened");
02730c33
BB
4764
4765module_param(metaslab_debug_unload, int, 0644);
1ce04573
BB
4766MODULE_PARM_DESC(metaslab_debug_unload,
4767 "prevent metaslabs from being unloaded");
02730c33
BB
4768
4769module_param(metaslab_preload_enabled, int, 0644);
f3a7f661
GW
4770MODULE_PARM_DESC(metaslab_preload_enabled,
4771 "preload potential metaslabs during reassessment");
f4a4046b 4772
02730c33 4773module_param(zfs_mg_noalloc_threshold, int, 0644);
f4a4046b
TC
4774MODULE_PARM_DESC(zfs_mg_noalloc_threshold,
4775 "percentage of free space for metaslab group to allow allocation");
02730c33
BB
4776
4777module_param(zfs_mg_fragmentation_threshold, int, 0644);
f3a7f661
GW
4778MODULE_PARM_DESC(zfs_mg_fragmentation_threshold,
4779 "fragmentation for metaslab group to allow allocation");
4780
02730c33 4781module_param(zfs_metaslab_fragmentation_threshold, int, 0644);
f3a7f661
GW
4782MODULE_PARM_DESC(zfs_metaslab_fragmentation_threshold,
4783 "fragmentation for metaslab to allow allocation");
02730c33
BB
4784
4785module_param(metaslab_fragmentation_factor_enabled, int, 0644);
f3a7f661
GW
4786MODULE_PARM_DESC(metaslab_fragmentation_factor_enabled,
4787 "use the fragmentation metric to prefer less fragmented metaslabs");
02730c33
BB
4788
4789module_param(metaslab_lba_weighting_enabled, int, 0644);
f3a7f661
GW
4790MODULE_PARM_DESC(metaslab_lba_weighting_enabled,
4791 "prefer metaslabs with lower LBAs");
02730c33
BB
4792
4793module_param(metaslab_bias_enabled, int, 0644);
f3a7f661
GW
4794MODULE_PARM_DESC(metaslab_bias_enabled,
4795 "enable metaslab group biasing");
4e21fd06
DB
4796
4797module_param(zfs_metaslab_segment_weight_enabled, int, 0644);
4798MODULE_PARM_DESC(zfs_metaslab_segment_weight_enabled,
4799 "enable segment-based metaslab selection");
4800
4801module_param(zfs_metaslab_switch_threshold, int, 0644);
4802MODULE_PARM_DESC(zfs_metaslab_switch_threshold,
4803 "segment-based metaslab selection maximum buckets before switching");
a1d477c2 4804
d830d479
MA
4805module_param(metaslab_force_ganging, ulong, 0644);
4806MODULE_PARM_DESC(metaslab_force_ganging,
a1d477c2 4807 "blocks larger than this size are forced to be gang blocks");
cc99f275
DB
4808/* END CSTYLED */
4809
93ce2b4c 4810#endif