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