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