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