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