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