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