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 http://www.opensolaris.org/os/licensing.
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, 2018 by Delphix. All rights reserved.
24  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
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/zio.h>
36 #include <sys/spa_impl.h>
37 #include <sys/zfeature.h>
38 #include <sys/vdev_indirect_mapping.h>
39 #include <sys/zap.h>
40 
41 SYSCTL_DECL(_vfs_zfs);
42 SYSCTL_NODE(_vfs_zfs, OID_AUTO, metaslab, CTLFLAG_RW, 0, "ZFS metaslab");
43 
44 #define	GANG_ALLOCATION(flags) \
45 	((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER))
46 
47 uint64_t metaslab_aliquot = 512ULL << 10;
48 uint64_t metaslab_force_ganging = SPA_MAXBLOCKSIZE + 1;	/* force gang blocks */
49 SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, force_ganging, CTLFLAG_RWTUN,
50     &metaslab_force_ganging, 0,
51     "Force gang block allocation for blocks larger than or equal to this value");
52 
53 /*
54  * Since we can touch multiple metaslabs (and their respective space maps)
55  * with each transaction group, we benefit from having a smaller space map
56  * block size since it allows us to issue more I/O operations scattered
57  * around the disk.
58  */
59 int zfs_metaslab_sm_blksz = (1 << 12);
60 SYSCTL_INT(_vfs_zfs, OID_AUTO, metaslab_sm_blksz, CTLFLAG_RDTUN,
61     &zfs_metaslab_sm_blksz, 0,
62     "Block size for metaslab DTL space map.  Power of 2 and greater than 4096.");
63 
64 /*
65  * The in-core space map representation is more compact than its on-disk form.
66  * The zfs_condense_pct determines how much more compact the in-core
67  * space map representation must be before we compact it on-disk.
68  * Values should be greater than or equal to 100.
69  */
70 int zfs_condense_pct = 200;
71 SYSCTL_INT(_vfs_zfs, OID_AUTO, condense_pct, CTLFLAG_RWTUN,
72     &zfs_condense_pct, 0,
73     "Condense on-disk spacemap when it is more than this many percents"
74     " of in-memory counterpart");
75 
76 /*
77  * Condensing a metaslab is not guaranteed to actually reduce the amount of
78  * space used on disk. In particular, a space map uses data in increments of
79  * MAX(1 << ashift, space_map_blksize), so a metaslab might use the
80  * same number of blocks after condensing. Since the goal of condensing is to
81  * reduce the number of IOPs required to read the space map, we only want to
82  * condense when we can be sure we will reduce the number of blocks used by the
83  * space map. Unfortunately, we cannot precisely compute whether or not this is
84  * the case in metaslab_should_condense since we are holding ms_lock. Instead,
85  * we apply the following heuristic: do not condense a spacemap unless the
86  * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
87  * blocks.
88  */
89 int zfs_metaslab_condense_block_threshold = 4;
90 
91 /*
92  * The zfs_mg_noalloc_threshold defines which metaslab groups should
93  * be eligible for allocation. The value is defined as a percentage of
94  * free space. Metaslab groups that have more free space than
95  * zfs_mg_noalloc_threshold are always eligible for allocations. Once
96  * a metaslab group's free space is less than or equal to the
97  * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
98  * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
99  * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
100  * groups are allowed to accept allocations. Gang blocks are always
101  * eligible to allocate on any metaslab group. The default value of 0 means
102  * no metaslab group will be excluded based on this criterion.
103  */
104 int zfs_mg_noalloc_threshold = 0;
105 SYSCTL_INT(_vfs_zfs, OID_AUTO, mg_noalloc_threshold, CTLFLAG_RWTUN,
106     &zfs_mg_noalloc_threshold, 0,
107     "Percentage of metaslab group size that should be free"
108     " to make it eligible for allocation");
109 
110 /*
111  * Metaslab groups are considered eligible for allocations if their
112  * fragmenation metric (measured as a percentage) is less than or equal to
113  * zfs_mg_fragmentation_threshold. If a metaslab group exceeds this threshold
114  * then it will be skipped unless all metaslab groups within the metaslab
115  * class have also crossed this threshold.
116  */
117 int zfs_mg_fragmentation_threshold = 85;
118 SYSCTL_INT(_vfs_zfs, OID_AUTO, mg_fragmentation_threshold, CTLFLAG_RWTUN,
119     &zfs_mg_fragmentation_threshold, 0,
120     "Percentage of metaslab group size that should be considered "
121     "eligible for allocations unless all metaslab groups within the metaslab class "
122     "have also crossed this threshold");
123 
124 /*
125  * Allow metaslabs to keep their active state as long as their fragmentation
126  * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
127  * active metaslab that exceeds this threshold will no longer keep its active
128  * status allowing better metaslabs to be selected.
129  */
130 int zfs_metaslab_fragmentation_threshold = 70;
131 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, fragmentation_threshold, CTLFLAG_RWTUN,
132     &zfs_metaslab_fragmentation_threshold, 0,
133     "Maximum percentage of metaslab fragmentation level to keep their active state");
134 
135 /*
136  * When set will load all metaslabs when pool is first opened.
137  */
138 int metaslab_debug_load = 0;
139 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, debug_load, CTLFLAG_RWTUN,
140     &metaslab_debug_load, 0,
141     "Load all metaslabs when pool is first opened");
142 
143 /*
144  * When set will prevent metaslabs from being unloaded.
145  */
146 int metaslab_debug_unload = 0;
147 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, debug_unload, CTLFLAG_RWTUN,
148     &metaslab_debug_unload, 0,
149     "Prevent metaslabs from being unloaded");
150 
151 /*
152  * Minimum size which forces the dynamic allocator to change
153  * it's allocation strategy.  Once the space map cannot satisfy
154  * an allocation of this size then it switches to using more
155  * aggressive strategy (i.e search by size rather than offset).
156  */
157 uint64_t metaslab_df_alloc_threshold = SPA_OLD_MAXBLOCKSIZE;
158 SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, df_alloc_threshold, CTLFLAG_RWTUN,
159     &metaslab_df_alloc_threshold, 0,
160     "Minimum size which forces the dynamic allocator to change it's allocation strategy");
161 
162 /*
163  * The minimum free space, in percent, which must be available
164  * in a space map to continue allocations in a first-fit fashion.
165  * Once the space map's free space drops below this level we dynamically
166  * switch to using best-fit allocations.
167  */
168 int metaslab_df_free_pct = 4;
169 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, df_free_pct, CTLFLAG_RWTUN,
170     &metaslab_df_free_pct, 0,
171     "The minimum free space, in percent, which must be available in a "
172     "space map to continue allocations in a first-fit fashion");
173 
174 /*
175  * A metaslab is considered "free" if it contains a contiguous
176  * segment which is greater than metaslab_min_alloc_size.
177  */
178 uint64_t metaslab_min_alloc_size = DMU_MAX_ACCESS;
179 SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, min_alloc_size, CTLFLAG_RWTUN,
180     &metaslab_min_alloc_size, 0,
181     "A metaslab is considered \"free\" if it contains a contiguous "
182     "segment which is greater than vfs.zfs.metaslab.min_alloc_size");
183 
184 /*
185  * Percentage of all cpus that can be used by the metaslab taskq.
186  */
187 int metaslab_load_pct = 50;
188 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, load_pct, CTLFLAG_RWTUN,
189     &metaslab_load_pct, 0,
190     "Percentage of cpus that can be used by the metaslab taskq");
191 
192 /*
193  * Determines how many txgs a metaslab may remain loaded without having any
194  * allocations from it. As long as a metaslab continues to be used we will
195  * keep it loaded.
196  */
197 int metaslab_unload_delay = TXG_SIZE * 2;
198 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, unload_delay, CTLFLAG_RWTUN,
199     &metaslab_unload_delay, 0,
200     "Number of TXGs that an unused metaslab can be kept in memory");
201 
202 /*
203  * Max number of metaslabs per group to preload.
204  */
205 int metaslab_preload_limit = SPA_DVAS_PER_BP;
206 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, preload_limit, CTLFLAG_RWTUN,
207     &metaslab_preload_limit, 0,
208     "Max number of metaslabs per group to preload");
209 
210 /*
211  * Enable/disable preloading of metaslab.
212  */
213 boolean_t metaslab_preload_enabled = B_TRUE;
214 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, preload_enabled, CTLFLAG_RWTUN,
215     &metaslab_preload_enabled, 0,
216     "Max number of metaslabs per group to preload");
217 
218 /*
219  * Enable/disable fragmentation weighting on metaslabs.
220  */
221 boolean_t metaslab_fragmentation_factor_enabled = B_TRUE;
222 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, fragmentation_factor_enabled, CTLFLAG_RWTUN,
223     &metaslab_fragmentation_factor_enabled, 0,
224     "Enable fragmentation weighting on metaslabs");
225 
226 /*
227  * Enable/disable lba weighting (i.e. outer tracks are given preference).
228  */
229 boolean_t metaslab_lba_weighting_enabled = B_TRUE;
230 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, lba_weighting_enabled, CTLFLAG_RWTUN,
231     &metaslab_lba_weighting_enabled, 0,
232     "Enable LBA weighting (i.e. outer tracks are given preference)");
233 
234 /*
235  * Enable/disable metaslab group biasing.
236  */
237 boolean_t metaslab_bias_enabled = B_TRUE;
238 SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, bias_enabled, CTLFLAG_RWTUN,
239     &metaslab_bias_enabled, 0,
240     "Enable metaslab group biasing");
241 
242 /*
243  * Enable/disable remapping of indirect DVAs to their concrete vdevs.
244  */
245 boolean_t zfs_remap_blkptr_enable = B_TRUE;
246 
247 /*
248  * Enable/disable segment-based metaslab selection.
249  */
250 boolean_t zfs_metaslab_segment_weight_enabled = B_TRUE;
251 
252 /*
253  * When using segment-based metaslab selection, we will continue
254  * allocating from the active metaslab until we have exhausted
255  * zfs_metaslab_switch_threshold of its buckets.
256  */
257 int zfs_metaslab_switch_threshold = 2;
258 
259 /*
260  * Internal switch to enable/disable the metaslab allocation tracing
261  * facility.
262  */
263 #ifdef _METASLAB_TRACING
264 boolean_t metaslab_trace_enabled = B_TRUE;
265 #endif
266 
267 /*
268  * Maximum entries that the metaslab allocation tracing facility will keep
269  * in a given list when running in non-debug mode. We limit the number
270  * of entries in non-debug mode to prevent us from using up too much memory.
271  * The limit should be sufficiently large that we don't expect any allocation
272  * to every exceed this value. In debug mode, the system will panic if this
273  * limit is ever reached allowing for further investigation.
274  */
275 #ifdef _METASLAB_TRACING
276 uint64_t metaslab_trace_max_entries = 5000;
277 #endif
278 
279 static uint64_t metaslab_weight(metaslab_t *);
280 static void metaslab_set_fragmentation(metaslab_t *);
281 static void metaslab_free_impl(vdev_t *, uint64_t, uint64_t, boolean_t);
282 static void metaslab_check_free_impl(vdev_t *, uint64_t, uint64_t);
283 static void metaslab_passivate(metaslab_t *msp, uint64_t weight);
284 static uint64_t metaslab_weight_from_range_tree(metaslab_t *msp);
285 #ifdef _METASLAB_TRACING
286 kmem_cache_t *metaslab_alloc_trace_cache;
287 #endif
288 
289 /*
290  * ==========================================================================
291  * Metaslab classes
292  * ==========================================================================
293  */
294 metaslab_class_t *
metaslab_class_create(spa_t * spa,metaslab_ops_t * ops)295 metaslab_class_create(spa_t *spa, metaslab_ops_t *ops)
296 {
297 	metaslab_class_t *mc;
298 
299 	mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
300 
301 	mc->mc_spa = spa;
302 	mc->mc_rotor = NULL;
303 	mc->mc_ops = ops;
304 	mutex_init(&mc->mc_lock, NULL, MUTEX_DEFAULT, NULL);
305 	mc->mc_alloc_slots = kmem_zalloc(spa->spa_alloc_count *
306 	    sizeof (zfs_refcount_t), KM_SLEEP);
307 	mc->mc_alloc_max_slots = kmem_zalloc(spa->spa_alloc_count *
308 	    sizeof (uint64_t), KM_SLEEP);
309 	for (int i = 0; i < spa->spa_alloc_count; i++)
310 		zfs_refcount_create_tracked(&mc->mc_alloc_slots[i]);
311 
312 	return (mc);
313 }
314 
315 void
metaslab_class_destroy(metaslab_class_t * mc)316 metaslab_class_destroy(metaslab_class_t *mc)
317 {
318 	ASSERT(mc->mc_rotor == NULL);
319 	ASSERT(mc->mc_alloc == 0);
320 	ASSERT(mc->mc_deferred == 0);
321 	ASSERT(mc->mc_space == 0);
322 	ASSERT(mc->mc_dspace == 0);
323 
324 	for (int i = 0; i < mc->mc_spa->spa_alloc_count; i++)
325 		zfs_refcount_destroy(&mc->mc_alloc_slots[i]);
326 	kmem_free(mc->mc_alloc_slots, mc->mc_spa->spa_alloc_count *
327 	    sizeof (zfs_refcount_t));
328 	kmem_free(mc->mc_alloc_max_slots, mc->mc_spa->spa_alloc_count *
329 	    sizeof (uint64_t));
330 	mutex_destroy(&mc->mc_lock);
331 	kmem_free(mc, sizeof (metaslab_class_t));
332 }
333 
334 int
metaslab_class_validate(metaslab_class_t * mc)335 metaslab_class_validate(metaslab_class_t *mc)
336 {
337 	metaslab_group_t *mg;
338 	vdev_t *vd;
339 
340 	/*
341 	 * Must hold one of the spa_config locks.
342 	 */
343 	ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
344 	    spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
345 
346 	if ((mg = mc->mc_rotor) == NULL)
347 		return (0);
348 
349 	do {
350 		vd = mg->mg_vd;
351 		ASSERT(vd->vdev_mg != NULL);
352 		ASSERT3P(vd->vdev_top, ==, vd);
353 		ASSERT3P(mg->mg_class, ==, mc);
354 		ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
355 	} while ((mg = mg->mg_next) != mc->mc_rotor);
356 
357 	return (0);
358 }
359 
360 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)361 metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
362     int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
363 {
364 	atomic_add_64(&mc->mc_alloc, alloc_delta);
365 	atomic_add_64(&mc->mc_deferred, defer_delta);
366 	atomic_add_64(&mc->mc_space, space_delta);
367 	atomic_add_64(&mc->mc_dspace, dspace_delta);
368 }
369 
370 void
metaslab_class_minblocksize_update(metaslab_class_t * mc)371 metaslab_class_minblocksize_update(metaslab_class_t *mc)
372 {
373 	metaslab_group_t *mg;
374 	vdev_t *vd;
375 	uint64_t minashift = UINT64_MAX;
376 
377 	if ((mg = mc->mc_rotor) == NULL) {
378 		mc->mc_minblocksize = SPA_MINBLOCKSIZE;
379 		return;
380 	}
381 
382 	do {
383 		vd = mg->mg_vd;
384 		if (vd->vdev_ashift < minashift)
385 			minashift = vd->vdev_ashift;
386 	} while ((mg = mg->mg_next) != mc->mc_rotor);
387 
388 	mc->mc_minblocksize = 1ULL << minashift;
389 }
390 
391 uint64_t
metaslab_class_get_alloc(metaslab_class_t * mc)392 metaslab_class_get_alloc(metaslab_class_t *mc)
393 {
394 	return (mc->mc_alloc);
395 }
396 
397 uint64_t
metaslab_class_get_deferred(metaslab_class_t * mc)398 metaslab_class_get_deferred(metaslab_class_t *mc)
399 {
400 	return (mc->mc_deferred);
401 }
402 
403 uint64_t
metaslab_class_get_space(metaslab_class_t * mc)404 metaslab_class_get_space(metaslab_class_t *mc)
405 {
406 	return (mc->mc_space);
407 }
408 
409 uint64_t
metaslab_class_get_dspace(metaslab_class_t * mc)410 metaslab_class_get_dspace(metaslab_class_t *mc)
411 {
412 	return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
413 }
414 
415 uint64_t
metaslab_class_get_minblocksize(metaslab_class_t * mc)416 metaslab_class_get_minblocksize(metaslab_class_t *mc)
417 {
418 	return (mc->mc_minblocksize);
419 }
420 
421 void
metaslab_class_histogram_verify(metaslab_class_t * mc)422 metaslab_class_histogram_verify(metaslab_class_t *mc)
423 {
424 	spa_t *spa = mc->mc_spa;
425 	vdev_t *rvd = spa->spa_root_vdev;
426 	uint64_t *mc_hist;
427 	int i;
428 
429 	if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
430 		return;
431 
432 	mc_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
433 	    KM_SLEEP);
434 
435 	for (int c = 0; c < rvd->vdev_children; c++) {
436 		vdev_t *tvd = rvd->vdev_child[c];
437 		metaslab_group_t *mg = tvd->vdev_mg;
438 
439 		/*
440 		 * Skip any holes, uninitialized top-levels, or
441 		 * vdevs that are not in this metalab class.
442 		 */
443 		if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
444 		    mg->mg_class != mc) {
445 			continue;
446 		}
447 
448 		for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
449 			mc_hist[i] += mg->mg_histogram[i];
450 	}
451 
452 	for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
453 		VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
454 
455 	kmem_free(mc_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
456 }
457 
458 /*
459  * Calculate the metaslab class's fragmentation metric. The metric
460  * is weighted based on the space contribution of each metaslab group.
461  * The return value will be a number between 0 and 100 (inclusive), or
462  * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
463  * zfs_frag_table for more information about the metric.
464  */
465 uint64_t
metaslab_class_fragmentation(metaslab_class_t * mc)466 metaslab_class_fragmentation(metaslab_class_t *mc)
467 {
468 	vdev_t *rvd = mc->mc_spa->spa_root_vdev;
469 	uint64_t fragmentation = 0;
470 
471 	spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
472 
473 	for (int c = 0; c < rvd->vdev_children; c++) {
474 		vdev_t *tvd = rvd->vdev_child[c];
475 		metaslab_group_t *mg = tvd->vdev_mg;
476 
477 		/*
478 		 * Skip any holes, uninitialized top-levels,
479 		 * or vdevs that are not in this metalab class.
480 		 */
481 		if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
482 		    mg->mg_class != mc) {
483 			continue;
484 		}
485 
486 		/*
487 		 * If a metaslab group does not contain a fragmentation
488 		 * metric then just bail out.
489 		 */
490 		if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
491 			spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
492 			return (ZFS_FRAG_INVALID);
493 		}
494 
495 		/*
496 		 * Determine how much this metaslab_group is contributing
497 		 * to the overall pool fragmentation metric.
498 		 */
499 		fragmentation += mg->mg_fragmentation *
500 		    metaslab_group_get_space(mg);
501 	}
502 	fragmentation /= metaslab_class_get_space(mc);
503 
504 	ASSERT3U(fragmentation, <=, 100);
505 	spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
506 	return (fragmentation);
507 }
508 
509 /*
510  * Calculate the amount of expandable space that is available in
511  * this metaslab class. If a device is expanded then its expandable
512  * space will be the amount of allocatable space that is currently not
513  * part of this metaslab class.
514  */
515 uint64_t
metaslab_class_expandable_space(metaslab_class_t * mc)516 metaslab_class_expandable_space(metaslab_class_t *mc)
517 {
518 	vdev_t *rvd = mc->mc_spa->spa_root_vdev;
519 	uint64_t space = 0;
520 
521 	spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
522 	for (int c = 0; c < rvd->vdev_children; c++) {
523 		uint64_t tspace;
524 		vdev_t *tvd = rvd->vdev_child[c];
525 		metaslab_group_t *mg = tvd->vdev_mg;
526 
527 		if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
528 		    mg->mg_class != mc) {
529 			continue;
530 		}
531 
532 		/*
533 		 * Calculate if we have enough space to add additional
534 		 * metaslabs. We report the expandable space in terms
535 		 * of the metaslab size since that's the unit of expansion.
536 		 * Adjust by efi system partition size.
537 		 */
538 		tspace = tvd->vdev_max_asize - tvd->vdev_asize;
539 		if (tspace > mc->mc_spa->spa_bootsize) {
540 			tspace -= mc->mc_spa->spa_bootsize;
541 		}
542 		space += P2ALIGN(tspace, 1ULL << tvd->vdev_ms_shift);
543 	}
544 	spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
545 	return (space);
546 }
547 
548 static int
metaslab_compare(const void * x1,const void * x2)549 metaslab_compare(const void *x1, const void *x2)
550 {
551 	const metaslab_t *m1 = (const metaslab_t *)x1;
552 	const metaslab_t *m2 = (const metaslab_t *)x2;
553 
554 	int sort1 = 0;
555 	int sort2 = 0;
556 	if (m1->ms_allocator != -1 && m1->ms_primary)
557 		sort1 = 1;
558 	else if (m1->ms_allocator != -1 && !m1->ms_primary)
559 		sort1 = 2;
560 	if (m2->ms_allocator != -1 && m2->ms_primary)
561 		sort2 = 1;
562 	else if (m2->ms_allocator != -1 && !m2->ms_primary)
563 		sort2 = 2;
564 
565 	/*
566 	 * Sort inactive metaslabs first, then primaries, then secondaries. When
567 	 * selecting a metaslab to allocate from, an allocator first tries its
568 	 * primary, then secondary active metaslab. If it doesn't have active
569 	 * metaslabs, or can't allocate from them, it searches for an inactive
570 	 * metaslab to activate. If it can't find a suitable one, it will steal
571 	 * a primary or secondary metaslab from another allocator.
572 	 */
573 	if (sort1 < sort2)
574 		return (-1);
575 	if (sort1 > sort2)
576 		return (1);
577 
578 	int cmp = AVL_CMP(m2->ms_weight, m1->ms_weight);
579 	if (likely(cmp))
580 		return (cmp);
581 
582 	IMPLY(AVL_CMP(m1->ms_start, m2->ms_start) == 0, m1 == m2);
583 
584 	return (AVL_CMP(m1->ms_start, m2->ms_start));
585 }
586 
587 uint64_t
metaslab_allocated_space(metaslab_t * msp)588 metaslab_allocated_space(metaslab_t *msp)
589 {
590 	return (msp->ms_allocated_space);
591 }
592 
593 /*
594  * Verify that the space accounting on disk matches the in-core range_trees.
595  */
596 static void
metaslab_verify_space(metaslab_t * msp,uint64_t txg)597 metaslab_verify_space(metaslab_t *msp, uint64_t txg)
598 {
599 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
600 	uint64_t allocating = 0;
601 	uint64_t sm_free_space, msp_free_space;
602 
603 	ASSERT(MUTEX_HELD(&msp->ms_lock));
604 	ASSERT(!msp->ms_condensing);
605 
606 	if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
607 		return;
608 
609 	/*
610 	 * We can only verify the metaslab space when we're called
611 	 * from syncing context with a loaded metaslab that has an
612 	 * allocated space map. Calling this in non-syncing context
613 	 * does not provide a consistent view of the metaslab since
614 	 * we're performing allocations in the future.
615 	 */
616 	if (txg != spa_syncing_txg(spa) || msp->ms_sm == NULL ||
617 	    !msp->ms_loaded)
618 		return;
619 
620 	/*
621 	 * Even though the smp_alloc field can get negative (e.g.
622 	 * see vdev_checkpoint_sm), that should never be the case
623 	 * when it come's to a metaslab's space map.
624 	 */
625 	ASSERT3S(space_map_allocated(msp->ms_sm), >=, 0);
626 
627 	sm_free_space = msp->ms_size - metaslab_allocated_space(msp);
628 
629 	/*
630 	 * Account for future allocations since we would have
631 	 * already deducted that space from the ms_allocatable.
632 	 */
633 	for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
634 		allocating +=
635 		    range_tree_space(msp->ms_allocating[(txg + t) & TXG_MASK]);
636 	}
637 
638 	ASSERT3U(msp->ms_deferspace, ==,
639 	    range_tree_space(msp->ms_defer[0]) +
640 	    range_tree_space(msp->ms_defer[1]));
641 
642 	msp_free_space = range_tree_space(msp->ms_allocatable) + allocating +
643 	    msp->ms_deferspace + range_tree_space(msp->ms_freed);
644 
645 	VERIFY3U(sm_free_space, ==, msp_free_space);
646 }
647 
648 /*
649  * ==========================================================================
650  * Metaslab groups
651  * ==========================================================================
652  */
653 /*
654  * Update the allocatable flag and the metaslab group's capacity.
655  * The allocatable flag is set to true if the capacity is below
656  * the zfs_mg_noalloc_threshold or has a fragmentation value that is
657  * greater than zfs_mg_fragmentation_threshold. If a metaslab group
658  * transitions from allocatable to non-allocatable or vice versa then the
659  * metaslab group's class is updated to reflect the transition.
660  */
661 static void
metaslab_group_alloc_update(metaslab_group_t * mg)662 metaslab_group_alloc_update(metaslab_group_t *mg)
663 {
664 	vdev_t *vd = mg->mg_vd;
665 	metaslab_class_t *mc = mg->mg_class;
666 	vdev_stat_t *vs = &vd->vdev_stat;
667 	boolean_t was_allocatable;
668 	boolean_t was_initialized;
669 
670 	ASSERT(vd == vd->vdev_top);
671 	ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_READER), ==,
672 	    SCL_ALLOC);
673 
674 	mutex_enter(&mg->mg_lock);
675 	was_allocatable = mg->mg_allocatable;
676 	was_initialized = mg->mg_initialized;
677 
678 	mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
679 	    (vs->vs_space + 1);
680 
681 	mutex_enter(&mc->mc_lock);
682 
683 	/*
684 	 * If the metaslab group was just added then it won't
685 	 * have any space until we finish syncing out this txg.
686 	 * At that point we will consider it initialized and available
687 	 * for allocations.  We also don't consider non-activated
688 	 * metaslab groups (e.g. vdevs that are in the middle of being removed)
689 	 * to be initialized, because they can't be used for allocation.
690 	 */
691 	mg->mg_initialized = metaslab_group_initialized(mg);
692 	if (!was_initialized && mg->mg_initialized) {
693 		mc->mc_groups++;
694 	} else if (was_initialized && !mg->mg_initialized) {
695 		ASSERT3U(mc->mc_groups, >, 0);
696 		mc->mc_groups--;
697 	}
698 	if (mg->mg_initialized)
699 		mg->mg_no_free_space = B_FALSE;
700 
701 	/*
702 	 * A metaslab group is considered allocatable if it has plenty
703 	 * of free space or is not heavily fragmented. We only take
704 	 * fragmentation into account if the metaslab group has a valid
705 	 * fragmentation metric (i.e. a value between 0 and 100).
706 	 */
707 	mg->mg_allocatable = (mg->mg_activation_count > 0 &&
708 	    mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
709 	    (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
710 	    mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
711 
712 	/*
713 	 * The mc_alloc_groups maintains a count of the number of
714 	 * groups in this metaslab class that are still above the
715 	 * zfs_mg_noalloc_threshold. This is used by the allocating
716 	 * threads to determine if they should avoid allocations to
717 	 * a given group. The allocator will avoid allocations to a group
718 	 * if that group has reached or is below the zfs_mg_noalloc_threshold
719 	 * and there are still other groups that are above the threshold.
720 	 * When a group transitions from allocatable to non-allocatable or
721 	 * vice versa we update the metaslab class to reflect that change.
722 	 * When the mc_alloc_groups value drops to 0 that means that all
723 	 * groups have reached the zfs_mg_noalloc_threshold making all groups
724 	 * eligible for allocations. This effectively means that all devices
725 	 * are balanced again.
726 	 */
727 	if (was_allocatable && !mg->mg_allocatable)
728 		mc->mc_alloc_groups--;
729 	else if (!was_allocatable && mg->mg_allocatable)
730 		mc->mc_alloc_groups++;
731 	mutex_exit(&mc->mc_lock);
732 
733 	mutex_exit(&mg->mg_lock);
734 }
735 
736 metaslab_group_t *
metaslab_group_create(metaslab_class_t * mc,vdev_t * vd,int allocators)737 metaslab_group_create(metaslab_class_t *mc, vdev_t *vd, int allocators)
738 {
739 	metaslab_group_t *mg;
740 
741 	mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
742 	mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
743 	mutex_init(&mg->mg_ms_initialize_lock, NULL, MUTEX_DEFAULT, NULL);
744 	cv_init(&mg->mg_ms_initialize_cv, NULL, CV_DEFAULT, NULL);
745 	mg->mg_primaries = kmem_zalloc(allocators * sizeof (metaslab_t *),
746 	    KM_SLEEP);
747 	mg->mg_secondaries = kmem_zalloc(allocators * sizeof (metaslab_t *),
748 	    KM_SLEEP);
749 	avl_create(&mg->mg_metaslab_tree, metaslab_compare,
750 	    sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
751 	mg->mg_vd = vd;
752 	mg->mg_class = mc;
753 	mg->mg_activation_count = 0;
754 	mg->mg_initialized = B_FALSE;
755 	mg->mg_no_free_space = B_TRUE;
756 	mg->mg_allocators = allocators;
757 
758 	mg->mg_alloc_queue_depth = kmem_zalloc(allocators *
759 	    sizeof (zfs_refcount_t), KM_SLEEP);
760 	mg->mg_cur_max_alloc_queue_depth = kmem_zalloc(allocators *
761 	    sizeof (uint64_t), KM_SLEEP);
762 	for (int i = 0; i < allocators; i++) {
763 		zfs_refcount_create_tracked(&mg->mg_alloc_queue_depth[i]);
764 		mg->mg_cur_max_alloc_queue_depth[i] = 0;
765 	}
766 
767 	mg->mg_taskq = taskq_create("metaslab_group_taskq", metaslab_load_pct,
768 	    minclsyspri, 10, INT_MAX, TASKQ_THREADS_CPU_PCT);
769 
770 	return (mg);
771 }
772 
773 void
metaslab_group_destroy(metaslab_group_t * mg)774 metaslab_group_destroy(metaslab_group_t *mg)
775 {
776 	ASSERT(mg->mg_prev == NULL);
777 	ASSERT(mg->mg_next == NULL);
778 	/*
779 	 * We may have gone below zero with the activation count
780 	 * either because we never activated in the first place or
781 	 * because we're done, and possibly removing the vdev.
782 	 */
783 	ASSERT(mg->mg_activation_count <= 0);
784 
785 	taskq_destroy(mg->mg_taskq);
786 	avl_destroy(&mg->mg_metaslab_tree);
787 	kmem_free(mg->mg_primaries, mg->mg_allocators * sizeof (metaslab_t *));
788 	kmem_free(mg->mg_secondaries, mg->mg_allocators *
789 	    sizeof (metaslab_t *));
790 	mutex_destroy(&mg->mg_lock);
791 	mutex_destroy(&mg->mg_ms_initialize_lock);
792 	cv_destroy(&mg->mg_ms_initialize_cv);
793 
794 	for (int i = 0; i < mg->mg_allocators; i++) {
795 		zfs_refcount_destroy(&mg->mg_alloc_queue_depth[i]);
796 		mg->mg_cur_max_alloc_queue_depth[i] = 0;
797 	}
798 	kmem_free(mg->mg_alloc_queue_depth, mg->mg_allocators *
799 	    sizeof (zfs_refcount_t));
800 	kmem_free(mg->mg_cur_max_alloc_queue_depth, mg->mg_allocators *
801 	    sizeof (uint64_t));
802 
803 	kmem_free(mg, sizeof (metaslab_group_t));
804 }
805 
806 void
metaslab_group_activate(metaslab_group_t * mg)807 metaslab_group_activate(metaslab_group_t *mg)
808 {
809 	metaslab_class_t *mc = mg->mg_class;
810 	metaslab_group_t *mgprev, *mgnext;
811 
812 	ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER), !=, 0);
813 
814 	ASSERT(mc->mc_rotor != mg);
815 	ASSERT(mg->mg_prev == NULL);
816 	ASSERT(mg->mg_next == NULL);
817 	ASSERT(mg->mg_activation_count <= 0);
818 
819 	if (++mg->mg_activation_count <= 0)
820 		return;
821 
822 	mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
823 	metaslab_group_alloc_update(mg);
824 
825 	if ((mgprev = mc->mc_rotor) == NULL) {
826 		mg->mg_prev = mg;
827 		mg->mg_next = mg;
828 	} else {
829 		mgnext = mgprev->mg_next;
830 		mg->mg_prev = mgprev;
831 		mg->mg_next = mgnext;
832 		mgprev->mg_next = mg;
833 		mgnext->mg_prev = mg;
834 	}
835 	mc->mc_rotor = mg;
836 	metaslab_class_minblocksize_update(mc);
837 }
838 
839 /*
840  * Passivate a metaslab group and remove it from the allocation rotor.
841  * Callers must hold both the SCL_ALLOC and SCL_ZIO lock prior to passivating
842  * a metaslab group. This function will momentarily drop spa_config_locks
843  * that are lower than the SCL_ALLOC lock (see comment below).
844  */
845 void
metaslab_group_passivate(metaslab_group_t * mg)846 metaslab_group_passivate(metaslab_group_t *mg)
847 {
848 	metaslab_class_t *mc = mg->mg_class;
849 	spa_t *spa = mc->mc_spa;
850 	metaslab_group_t *mgprev, *mgnext;
851 	int locks = spa_config_held(spa, SCL_ALL, RW_WRITER);
852 
853 	ASSERT3U(spa_config_held(spa, SCL_ALLOC | SCL_ZIO, RW_WRITER), ==,
854 	    (SCL_ALLOC | SCL_ZIO));
855 
856 	if (--mg->mg_activation_count != 0) {
857 		ASSERT(mc->mc_rotor != mg);
858 		ASSERT(mg->mg_prev == NULL);
859 		ASSERT(mg->mg_next == NULL);
860 		ASSERT(mg->mg_activation_count < 0);
861 		return;
862 	}
863 
864 	/*
865 	 * The spa_config_lock is an array of rwlocks, ordered as
866 	 * follows (from highest to lowest):
867 	 *	SCL_CONFIG > SCL_STATE > SCL_L2ARC > SCL_ALLOC >
868 	 *	SCL_ZIO > SCL_FREE > SCL_VDEV
869 	 * (For more information about the spa_config_lock see spa_misc.c)
870 	 * The higher the lock, the broader its coverage. When we passivate
871 	 * a metaslab group, we must hold both the SCL_ALLOC and the SCL_ZIO
872 	 * config locks. However, the metaslab group's taskq might be trying
873 	 * to preload metaslabs so we must drop the SCL_ZIO lock and any
874 	 * lower locks to allow the I/O to complete. At a minimum,
875 	 * we continue to hold the SCL_ALLOC lock, which prevents any future
876 	 * allocations from taking place and any changes to the vdev tree.
877 	 */
878 	spa_config_exit(spa, locks & ~(SCL_ZIO - 1), spa);
879 	taskq_wait(mg->mg_taskq);
880 	spa_config_enter(spa, locks & ~(SCL_ZIO - 1), spa, RW_WRITER);
881 	metaslab_group_alloc_update(mg);
882 	for (int i = 0; i < mg->mg_allocators; i++) {
883 		metaslab_t *msp = mg->mg_primaries[i];
884 		if (msp != NULL) {
885 			mutex_enter(&msp->ms_lock);
886 			metaslab_passivate(msp,
887 			    metaslab_weight_from_range_tree(msp));
888 			mutex_exit(&msp->ms_lock);
889 		}
890 		msp = mg->mg_secondaries[i];
891 		if (msp != NULL) {
892 			mutex_enter(&msp->ms_lock);
893 			metaslab_passivate(msp,
894 			    metaslab_weight_from_range_tree(msp));
895 			mutex_exit(&msp->ms_lock);
896 		}
897 	}
898 
899 	mgprev = mg->mg_prev;
900 	mgnext = mg->mg_next;
901 
902 	if (mg == mgnext) {
903 		mc->mc_rotor = NULL;
904 	} else {
905 		mc->mc_rotor = mgnext;
906 		mgprev->mg_next = mgnext;
907 		mgnext->mg_prev = mgprev;
908 	}
909 
910 	mg->mg_prev = NULL;
911 	mg->mg_next = NULL;
912 	metaslab_class_minblocksize_update(mc);
913 }
914 
915 boolean_t
metaslab_group_initialized(metaslab_group_t * mg)916 metaslab_group_initialized(metaslab_group_t *mg)
917 {
918 	vdev_t *vd = mg->mg_vd;
919 	vdev_stat_t *vs = &vd->vdev_stat;
920 
921 	return (vs->vs_space != 0 && mg->mg_activation_count > 0);
922 }
923 
924 uint64_t
metaslab_group_get_space(metaslab_group_t * mg)925 metaslab_group_get_space(metaslab_group_t *mg)
926 {
927 	return ((1ULL << mg->mg_vd->vdev_ms_shift) * mg->mg_vd->vdev_ms_count);
928 }
929 
930 void
metaslab_group_histogram_verify(metaslab_group_t * mg)931 metaslab_group_histogram_verify(metaslab_group_t *mg)
932 {
933 	uint64_t *mg_hist;
934 	vdev_t *vd = mg->mg_vd;
935 	uint64_t ashift = vd->vdev_ashift;
936 	int i;
937 
938 	if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
939 		return;
940 
941 	mg_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
942 	    KM_SLEEP);
943 
944 	ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE, >=,
945 	    SPACE_MAP_HISTOGRAM_SIZE + ashift);
946 
947 	for (int m = 0; m < vd->vdev_ms_count; m++) {
948 		metaslab_t *msp = vd->vdev_ms[m];
949 		ASSERT(msp != NULL);
950 
951 		/* skip if not active or not a member */
952 		if (msp->ms_sm == NULL || msp->ms_group != mg)
953 			continue;
954 
955 		for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
956 			mg_hist[i + ashift] +=
957 			    msp->ms_sm->sm_phys->smp_histogram[i];
958 	}
959 
960 	for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i ++)
961 		VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
962 
963 	kmem_free(mg_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
964 }
965 
966 static void
metaslab_group_histogram_add(metaslab_group_t * mg,metaslab_t * msp)967 metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
968 {
969 	metaslab_class_t *mc = mg->mg_class;
970 	uint64_t ashift = mg->mg_vd->vdev_ashift;
971 
972 	ASSERT(MUTEX_HELD(&msp->ms_lock));
973 	if (msp->ms_sm == NULL)
974 		return;
975 
976 	mutex_enter(&mg->mg_lock);
977 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
978 		mg->mg_histogram[i + ashift] +=
979 		    msp->ms_sm->sm_phys->smp_histogram[i];
980 		mc->mc_histogram[i + ashift] +=
981 		    msp->ms_sm->sm_phys->smp_histogram[i];
982 	}
983 	mutex_exit(&mg->mg_lock);
984 }
985 
986 void
metaslab_group_histogram_remove(metaslab_group_t * mg,metaslab_t * msp)987 metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
988 {
989 	metaslab_class_t *mc = mg->mg_class;
990 	uint64_t ashift = mg->mg_vd->vdev_ashift;
991 
992 	ASSERT(MUTEX_HELD(&msp->ms_lock));
993 	if (msp->ms_sm == NULL)
994 		return;
995 
996 	mutex_enter(&mg->mg_lock);
997 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
998 		ASSERT3U(mg->mg_histogram[i + ashift], >=,
999 		    msp->ms_sm->sm_phys->smp_histogram[i]);
1000 		ASSERT3U(mc->mc_histogram[i + ashift], >=,
1001 		    msp->ms_sm->sm_phys->smp_histogram[i]);
1002 
1003 		mg->mg_histogram[i + ashift] -=
1004 		    msp->ms_sm->sm_phys->smp_histogram[i];
1005 		mc->mc_histogram[i + ashift] -=
1006 		    msp->ms_sm->sm_phys->smp_histogram[i];
1007 	}
1008 	mutex_exit(&mg->mg_lock);
1009 }
1010 
1011 static void
metaslab_group_add(metaslab_group_t * mg,metaslab_t * msp)1012 metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
1013 {
1014 	ASSERT(msp->ms_group == NULL);
1015 	mutex_enter(&mg->mg_lock);
1016 	msp->ms_group = mg;
1017 	msp->ms_weight = 0;
1018 	avl_add(&mg->mg_metaslab_tree, msp);
1019 	mutex_exit(&mg->mg_lock);
1020 
1021 	mutex_enter(&msp->ms_lock);
1022 	metaslab_group_histogram_add(mg, msp);
1023 	mutex_exit(&msp->ms_lock);
1024 }
1025 
1026 static void
metaslab_group_remove(metaslab_group_t * mg,metaslab_t * msp)1027 metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
1028 {
1029 	mutex_enter(&msp->ms_lock);
1030 	metaslab_group_histogram_remove(mg, msp);
1031 	mutex_exit(&msp->ms_lock);
1032 
1033 	mutex_enter(&mg->mg_lock);
1034 	ASSERT(msp->ms_group == mg);
1035 	avl_remove(&mg->mg_metaslab_tree, msp);
1036 	msp->ms_group = NULL;
1037 	mutex_exit(&mg->mg_lock);
1038 }
1039 
1040 static void
metaslab_group_sort_impl(metaslab_group_t * mg,metaslab_t * msp,uint64_t weight)1041 metaslab_group_sort_impl(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1042 {
1043 	ASSERT(MUTEX_HELD(&mg->mg_lock));
1044 	ASSERT(msp->ms_group == mg);
1045 	avl_remove(&mg->mg_metaslab_tree, msp);
1046 	msp->ms_weight = weight;
1047 	avl_add(&mg->mg_metaslab_tree, msp);
1048 
1049 }
1050 
1051 static void
metaslab_group_sort(metaslab_group_t * mg,metaslab_t * msp,uint64_t weight)1052 metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1053 {
1054 	/*
1055 	 * Although in principle the weight can be any value, in
1056 	 * practice we do not use values in the range [1, 511].
1057 	 */
1058 	ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
1059 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1060 
1061 	mutex_enter(&mg->mg_lock);
1062 	metaslab_group_sort_impl(mg, msp, weight);
1063 	mutex_exit(&mg->mg_lock);
1064 }
1065 
1066 /*
1067  * Calculate the fragmentation for a given metaslab group. We can use
1068  * a simple average here since all metaslabs within the group must have
1069  * the same size. The return value will be a value between 0 and 100
1070  * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
1071  * group have a fragmentation metric.
1072  */
1073 uint64_t
metaslab_group_fragmentation(metaslab_group_t * mg)1074 metaslab_group_fragmentation(metaslab_group_t *mg)
1075 {
1076 	vdev_t *vd = mg->mg_vd;
1077 	uint64_t fragmentation = 0;
1078 	uint64_t valid_ms = 0;
1079 
1080 	for (int m = 0; m < vd->vdev_ms_count; m++) {
1081 		metaslab_t *msp = vd->vdev_ms[m];
1082 
1083 		if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
1084 			continue;
1085 		if (msp->ms_group != mg)
1086 			continue;
1087 
1088 		valid_ms++;
1089 		fragmentation += msp->ms_fragmentation;
1090 	}
1091 
1092 	if (valid_ms <= mg->mg_vd->vdev_ms_count / 2)
1093 		return (ZFS_FRAG_INVALID);
1094 
1095 	fragmentation /= valid_ms;
1096 	ASSERT3U(fragmentation, <=, 100);
1097 	return (fragmentation);
1098 }
1099 
1100 /*
1101  * Determine if a given metaslab group should skip allocations. A metaslab
1102  * group should avoid allocations if its free capacity is less than the
1103  * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
1104  * zfs_mg_fragmentation_threshold and there is at least one metaslab group
1105  * that can still handle allocations. If the allocation throttle is enabled
1106  * then we skip allocations to devices that have reached their maximum
1107  * allocation queue depth unless the selected metaslab group is the only
1108  * eligible group remaining.
1109  */
1110 static boolean_t
metaslab_group_allocatable(metaslab_group_t * mg,metaslab_group_t * rotor,uint64_t psize,int allocator,int d)1111 metaslab_group_allocatable(metaslab_group_t *mg, metaslab_group_t *rotor,
1112     uint64_t psize, int allocator, int d)
1113 {
1114 	spa_t *spa = mg->mg_vd->vdev_spa;
1115 	metaslab_class_t *mc = mg->mg_class;
1116 
1117 	/*
1118 	 * We can only consider skipping this metaslab group if it's
1119 	 * in the normal metaslab class and there are other metaslab
1120 	 * groups to select from. Otherwise, we always consider it eligible
1121 	 * for allocations.
1122 	 */
1123 	if ((mc != spa_normal_class(spa) &&
1124 	    mc != spa_special_class(spa) &&
1125 	    mc != spa_dedup_class(spa)) ||
1126 	    mc->mc_groups <= 1)
1127 		return (B_TRUE);
1128 
1129 	/*
1130 	 * If the metaslab group's mg_allocatable flag is set (see comments
1131 	 * in metaslab_group_alloc_update() for more information) and
1132 	 * the allocation throttle is disabled then allow allocations to this
1133 	 * device. However, if the allocation throttle is enabled then
1134 	 * check if we have reached our allocation limit (mg_alloc_queue_depth)
1135 	 * to determine if we should allow allocations to this metaslab group.
1136 	 * If all metaslab groups are no longer considered allocatable
1137 	 * (mc_alloc_groups == 0) or we're trying to allocate the smallest
1138 	 * gang block size then we allow allocations on this metaslab group
1139 	 * regardless of the mg_allocatable or throttle settings.
1140 	 */
1141 	if (mg->mg_allocatable) {
1142 		metaslab_group_t *mgp;
1143 		int64_t qdepth;
1144 		uint64_t qmax = mg->mg_cur_max_alloc_queue_depth[allocator];
1145 
1146 		if (!mc->mc_alloc_throttle_enabled)
1147 			return (B_TRUE);
1148 
1149 		/*
1150 		 * If this metaslab group does not have any free space, then
1151 		 * there is no point in looking further.
1152 		 */
1153 		if (mg->mg_no_free_space)
1154 			return (B_FALSE);
1155 
1156 		/*
1157 		 * Relax allocation throttling for ditto blocks.  Due to
1158 		 * random imbalances in allocation it tends to push copies
1159 		 * to one vdev, that looks a bit better at the moment.
1160 		 */
1161 		qmax = qmax * (4 + d) / 4;
1162 
1163 		qdepth = zfs_refcount_count(
1164 		    &mg->mg_alloc_queue_depth[allocator]);
1165 
1166 		/*
1167 		 * If this metaslab group is below its qmax or it's
1168 		 * the only allocatable metasable group, then attempt
1169 		 * to allocate from it.
1170 		 */
1171 		if (qdepth < qmax || mc->mc_alloc_groups == 1)
1172 			return (B_TRUE);
1173 		ASSERT3U(mc->mc_alloc_groups, >, 1);
1174 
1175 		/*
1176 		 * Since this metaslab group is at or over its qmax, we
1177 		 * need to determine if there are metaslab groups after this
1178 		 * one that might be able to handle this allocation. This is
1179 		 * racy since we can't hold the locks for all metaslab
1180 		 * groups at the same time when we make this check.
1181 		 */
1182 		for (mgp = mg->mg_next; mgp != rotor; mgp = mgp->mg_next) {
1183 			qmax = mgp->mg_cur_max_alloc_queue_depth[allocator];
1184 			qmax = qmax * (4 + d) / 4;
1185 			qdepth = zfs_refcount_count(
1186 			    &mgp->mg_alloc_queue_depth[allocator]);
1187 
1188 			/*
1189 			 * If there is another metaslab group that
1190 			 * might be able to handle the allocation, then
1191 			 * we return false so that we skip this group.
1192 			 */
1193 			if (qdepth < qmax && !mgp->mg_no_free_space)
1194 				return (B_FALSE);
1195 		}
1196 
1197 		/*
1198 		 * We didn't find another group to handle the allocation
1199 		 * so we can't skip this metaslab group even though
1200 		 * we are at or over our qmax.
1201 		 */
1202 		return (B_TRUE);
1203 
1204 	} else if (mc->mc_alloc_groups == 0 || psize == SPA_MINBLOCKSIZE) {
1205 		return (B_TRUE);
1206 	}
1207 	return (B_FALSE);
1208 }
1209 
1210 /*
1211  * ==========================================================================
1212  * Range tree callbacks
1213  * ==========================================================================
1214  */
1215 
1216 /*
1217  * Comparison function for the private size-ordered tree. Tree is sorted
1218  * by size, larger sizes at the end of the tree.
1219  */
1220 static int
metaslab_rangesize_compare(const void * x1,const void * x2)1221 metaslab_rangesize_compare(const void *x1, const void *x2)
1222 {
1223 	const range_seg_t *r1 = x1;
1224 	const range_seg_t *r2 = x2;
1225 	uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1226 	uint64_t rs_size2 = r2->rs_end - r2->rs_start;
1227 
1228 	int cmp = AVL_CMP(rs_size1, rs_size2);
1229 	if (likely(cmp))
1230 		return (cmp);
1231 
1232 	return (AVL_CMP(r1->rs_start, r2->rs_start));
1233 }
1234 
1235 /*
1236  * ==========================================================================
1237  * Common allocator routines
1238  * ==========================================================================
1239  */
1240 
1241 /*
1242  * Return the maximum contiguous segment within the metaslab.
1243  */
1244 uint64_t
metaslab_block_maxsize(metaslab_t * msp)1245 metaslab_block_maxsize(metaslab_t *msp)
1246 {
1247 	avl_tree_t *t = &msp->ms_allocatable_by_size;
1248 	range_seg_t *rs;
1249 
1250 	if (t == NULL || (rs = avl_last(t)) == NULL)
1251 		return (0ULL);
1252 
1253 	return (rs->rs_end - rs->rs_start);
1254 }
1255 
1256 static range_seg_t *
metaslab_block_find(avl_tree_t * t,uint64_t start,uint64_t size)1257 metaslab_block_find(avl_tree_t *t, uint64_t start, uint64_t size)
1258 {
1259 	range_seg_t *rs, rsearch;
1260 	avl_index_t where;
1261 
1262 	rsearch.rs_start = start;
1263 	rsearch.rs_end = start + size;
1264 
1265 	rs = avl_find(t, &rsearch, &where);
1266 	if (rs == NULL) {
1267 		rs = avl_nearest(t, where, AVL_AFTER);
1268 	}
1269 
1270 	return (rs);
1271 }
1272 
1273 /*
1274  * This is a helper function that can be used by the allocator to find
1275  * a suitable block to allocate. This will search the specified AVL
1276  * tree looking for a block that matches the specified criteria.
1277  */
1278 static uint64_t
metaslab_block_picker(avl_tree_t * t,uint64_t * cursor,uint64_t size,uint64_t align)1279 metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
1280     uint64_t align)
1281 {
1282 	range_seg_t *rs = metaslab_block_find(t, *cursor, size);
1283 
1284 	while (rs != NULL) {
1285 		uint64_t offset = P2ROUNDUP(rs->rs_start, align);
1286 
1287 		if (offset + size <= rs->rs_end) {
1288 			*cursor = offset + size;
1289 			return (offset);
1290 		}
1291 		rs = AVL_NEXT(t, rs);
1292 	}
1293 
1294 	/*
1295 	 * If we know we've searched the whole map (*cursor == 0), give up.
1296 	 * Otherwise, reset the cursor to the beginning and try again.
1297 	 */
1298 	if (*cursor == 0)
1299 		return (-1ULL);
1300 
1301 	*cursor = 0;
1302 	return (metaslab_block_picker(t, cursor, size, align));
1303 }
1304 
1305 /*
1306  * ==========================================================================
1307  * The first-fit block allocator
1308  * ==========================================================================
1309  */
1310 static uint64_t
metaslab_ff_alloc(metaslab_t * msp,uint64_t size)1311 metaslab_ff_alloc(metaslab_t *msp, uint64_t size)
1312 {
1313 	/*
1314 	 * Find the largest power of 2 block size that evenly divides the
1315 	 * requested size. This is used to try to allocate blocks with similar
1316 	 * alignment from the same area of the metaslab (i.e. same cursor
1317 	 * bucket) but it does not guarantee that other allocations sizes
1318 	 * may exist in the same region.
1319 	 */
1320 	uint64_t align = size & -size;
1321 	uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
1322 	avl_tree_t *t = &msp->ms_allocatable->rt_root;
1323 
1324 	return (metaslab_block_picker(t, cursor, size, align));
1325 }
1326 
1327 static metaslab_ops_t metaslab_ff_ops = {
1328 	metaslab_ff_alloc
1329 };
1330 
1331 /*
1332  * ==========================================================================
1333  * Dynamic block allocator -
1334  * Uses the first fit allocation scheme until space get low and then
1335  * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
1336  * and metaslab_df_free_pct to determine when to switch the allocation scheme.
1337  * ==========================================================================
1338  */
1339 static uint64_t
metaslab_df_alloc(metaslab_t * msp,uint64_t size)1340 metaslab_df_alloc(metaslab_t *msp, uint64_t size)
1341 {
1342 	/*
1343 	 * Find the largest power of 2 block size that evenly divides the
1344 	 * requested size. This is used to try to allocate blocks with similar
1345 	 * alignment from the same area of the metaslab (i.e. same cursor
1346 	 * bucket) but it does not guarantee that other allocations sizes
1347 	 * may exist in the same region.
1348 	 */
1349 	uint64_t align = size & -size;
1350 	uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
1351 	range_tree_t *rt = msp->ms_allocatable;
1352 	avl_tree_t *t = &rt->rt_root;
1353 	uint64_t max_size = metaslab_block_maxsize(msp);
1354 	int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1355 
1356 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1357 	ASSERT3U(avl_numnodes(t), ==,
1358 	    avl_numnodes(&msp->ms_allocatable_by_size));
1359 
1360 	if (max_size < size)
1361 		return (-1ULL);
1362 
1363 	/*
1364 	 * If we're running low on space switch to using the size
1365 	 * sorted AVL tree (best-fit).
1366 	 */
1367 	if (max_size < metaslab_df_alloc_threshold ||
1368 	    free_pct < metaslab_df_free_pct) {
1369 		t = &msp->ms_allocatable_by_size;
1370 		*cursor = 0;
1371 	}
1372 
1373 	return (metaslab_block_picker(t, cursor, size, 1ULL));
1374 }
1375 
1376 static metaslab_ops_t metaslab_df_ops = {
1377 	metaslab_df_alloc
1378 };
1379 
1380 /*
1381  * ==========================================================================
1382  * Cursor fit block allocator -
1383  * Select the largest region in the metaslab, set the cursor to the beginning
1384  * of the range and the cursor_end to the end of the range. As allocations
1385  * are made advance the cursor. Continue allocating from the cursor until
1386  * the range is exhausted and then find a new range.
1387  * ==========================================================================
1388  */
1389 static uint64_t
metaslab_cf_alloc(metaslab_t * msp,uint64_t size)1390 metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
1391 {
1392 	range_tree_t *rt = msp->ms_allocatable;
1393 	avl_tree_t *t = &msp->ms_allocatable_by_size;
1394 	uint64_t *cursor = &msp->ms_lbas[0];
1395 	uint64_t *cursor_end = &msp->ms_lbas[1];
1396 	uint64_t offset = 0;
1397 
1398 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1399 	ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&rt->rt_root));
1400 
1401 	ASSERT3U(*cursor_end, >=, *cursor);
1402 
1403 	if ((*cursor + size) > *cursor_end) {
1404 		range_seg_t *rs;
1405 
1406 		rs = avl_last(&msp->ms_allocatable_by_size);
1407 		if (rs == NULL || (rs->rs_end - rs->rs_start) < size)
1408 			return (-1ULL);
1409 
1410 		*cursor = rs->rs_start;
1411 		*cursor_end = rs->rs_end;
1412 	}
1413 
1414 	offset = *cursor;
1415 	*cursor += size;
1416 
1417 	return (offset);
1418 }
1419 
1420 static metaslab_ops_t metaslab_cf_ops = {
1421 	metaslab_cf_alloc
1422 };
1423 
1424 /*
1425  * ==========================================================================
1426  * New dynamic fit allocator -
1427  * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1428  * contiguous blocks. If no region is found then just use the largest segment
1429  * that remains.
1430  * ==========================================================================
1431  */
1432 
1433 /*
1434  * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1435  * to request from the allocator.
1436  */
1437 uint64_t metaslab_ndf_clump_shift = 4;
1438 
1439 static uint64_t
metaslab_ndf_alloc(metaslab_t * msp,uint64_t size)1440 metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
1441 {
1442 	avl_tree_t *t = &msp->ms_allocatable->rt_root;
1443 	avl_index_t where;
1444 	range_seg_t *rs, rsearch;
1445 	uint64_t hbit = highbit64(size);
1446 	uint64_t *cursor = &msp->ms_lbas[hbit - 1];
1447 	uint64_t max_size = metaslab_block_maxsize(msp);
1448 
1449 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1450 	ASSERT3U(avl_numnodes(t), ==,
1451 	    avl_numnodes(&msp->ms_allocatable_by_size));
1452 
1453 	if (max_size < size)
1454 		return (-1ULL);
1455 
1456 	rsearch.rs_start = *cursor;
1457 	rsearch.rs_end = *cursor + size;
1458 
1459 	rs = avl_find(t, &rsearch, &where);
1460 	if (rs == NULL || (rs->rs_end - rs->rs_start) < size) {
1461 		t = &msp->ms_allocatable_by_size;
1462 
1463 		rsearch.rs_start = 0;
1464 		rsearch.rs_end = MIN(max_size,
1465 		    1ULL << (hbit + metaslab_ndf_clump_shift));
1466 		rs = avl_find(t, &rsearch, &where);
1467 		if (rs == NULL)
1468 			rs = avl_nearest(t, where, AVL_AFTER);
1469 		ASSERT(rs != NULL);
1470 	}
1471 
1472 	if ((rs->rs_end - rs->rs_start) >= size) {
1473 		*cursor = rs->rs_start + size;
1474 		return (rs->rs_start);
1475 	}
1476 	return (-1ULL);
1477 }
1478 
1479 static metaslab_ops_t metaslab_ndf_ops = {
1480 	metaslab_ndf_alloc
1481 };
1482 
1483 metaslab_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
1484 
1485 /*
1486  * ==========================================================================
1487  * Metaslabs
1488  * ==========================================================================
1489  */
1490 
1491 static void
metaslab_aux_histograms_clear(metaslab_t * msp)1492 metaslab_aux_histograms_clear(metaslab_t *msp)
1493 {
1494 	/*
1495 	 * Auxiliary histograms are only cleared when resetting them,
1496 	 * which can only happen while the metaslab is loaded.
1497 	 */
1498 	ASSERT(msp->ms_loaded);
1499 
1500 	bzero(msp->ms_synchist, sizeof (msp->ms_synchist));
1501 	for (int t = 0; t < TXG_DEFER_SIZE; t++)
1502 		bzero(msp->ms_deferhist[t], sizeof (msp->ms_deferhist[t]));
1503 }
1504 
1505 static void
metaslab_aux_histogram_add(uint64_t * histogram,uint64_t shift,range_tree_t * rt)1506 metaslab_aux_histogram_add(uint64_t *histogram, uint64_t shift,
1507     range_tree_t *rt)
1508 {
1509 	/*
1510 	 * This is modeled after space_map_histogram_add(), so refer to that
1511 	 * function for implementation details. We want this to work like
1512 	 * the space map histogram, and not the range tree histogram, as we
1513 	 * are essentially constructing a delta that will be later subtracted
1514 	 * from the space map histogram.
1515 	 */
1516 	int idx = 0;
1517 	for (int i = shift; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
1518 		ASSERT3U(i, >=, idx + shift);
1519 		histogram[idx] += rt->rt_histogram[i] << (i - idx - shift);
1520 
1521 		if (idx < SPACE_MAP_HISTOGRAM_SIZE - 1) {
1522 			ASSERT3U(idx + shift, ==, i);
1523 			idx++;
1524 			ASSERT3U(idx, <, SPACE_MAP_HISTOGRAM_SIZE);
1525 		}
1526 	}
1527 }
1528 
1529 /*
1530  * Called at every sync pass that the metaslab gets synced.
1531  *
1532  * The reason is that we want our auxiliary histograms to be updated
1533  * wherever the metaslab's space map histogram is updated. This way
1534  * we stay consistent on which parts of the metaslab space map's
1535  * histogram are currently not available for allocations (e.g because
1536  * they are in the defer, freed, and freeing trees).
1537  */
1538 static void
metaslab_aux_histograms_update(metaslab_t * msp)1539 metaslab_aux_histograms_update(metaslab_t *msp)
1540 {
1541 	space_map_t *sm = msp->ms_sm;
1542 	ASSERT(sm != NULL);
1543 
1544 	/*
1545 	 * This is similar to the metaslab's space map histogram updates
1546 	 * that take place in metaslab_sync(). The only difference is that
1547 	 * we only care about segments that haven't made it into the
1548 	 * ms_allocatable tree yet.
1549 	 */
1550 	if (msp->ms_loaded) {
1551 		metaslab_aux_histograms_clear(msp);
1552 
1553 		metaslab_aux_histogram_add(msp->ms_synchist,
1554 		    sm->sm_shift, msp->ms_freed);
1555 
1556 		for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1557 			metaslab_aux_histogram_add(msp->ms_deferhist[t],
1558 			    sm->sm_shift, msp->ms_defer[t]);
1559 		}
1560 	}
1561 
1562 	metaslab_aux_histogram_add(msp->ms_synchist,
1563 	    sm->sm_shift, msp->ms_freeing);
1564 }
1565 
1566 /*
1567  * Called every time we are done syncing (writing to) the metaslab,
1568  * i.e. at the end of each sync pass.
1569  * [see the comment in metaslab_impl.h for ms_synchist, ms_deferhist]
1570  */
1571 static void
metaslab_aux_histograms_update_done(metaslab_t * msp,boolean_t defer_allowed)1572 metaslab_aux_histograms_update_done(metaslab_t *msp, boolean_t defer_allowed)
1573 {
1574 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1575 	space_map_t *sm = msp->ms_sm;
1576 
1577 	if (sm == NULL) {
1578 		/*
1579 		 * We came here from metaslab_init() when creating/opening a
1580 		 * pool, looking at a metaslab that hasn't had any allocations
1581 		 * yet.
1582 		 */
1583 		return;
1584 	}
1585 
1586 	/*
1587 	 * This is similar to the actions that we take for the ms_freed
1588 	 * and ms_defer trees in metaslab_sync_done().
1589 	 */
1590 	uint64_t hist_index = spa_syncing_txg(spa) % TXG_DEFER_SIZE;
1591 	if (defer_allowed) {
1592 		bcopy(msp->ms_synchist, msp->ms_deferhist[hist_index],
1593 		    sizeof (msp->ms_synchist));
1594 	} else {
1595 		bzero(msp->ms_deferhist[hist_index],
1596 		    sizeof (msp->ms_deferhist[hist_index]));
1597 	}
1598 	bzero(msp->ms_synchist, sizeof (msp->ms_synchist));
1599 }
1600 
1601 /*
1602  * Ensure that the metaslab's weight and fragmentation are consistent
1603  * with the contents of the histogram (either the range tree's histogram
1604  * or the space map's depending whether the metaslab is loaded).
1605  */
1606 static void
metaslab_verify_weight_and_frag(metaslab_t * msp)1607 metaslab_verify_weight_and_frag(metaslab_t *msp)
1608 {
1609 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1610 
1611 	if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
1612 		return;
1613 
1614 	/* see comment in metaslab_verify_unflushed_changes() */
1615 	if (msp->ms_group == NULL)
1616 		return;
1617 
1618 	/*
1619 	 * Devices being removed always return a weight of 0 and leave
1620 	 * fragmentation and ms_max_size as is - there is nothing for
1621 	 * us to verify here.
1622 	 */
1623 	vdev_t *vd = msp->ms_group->mg_vd;
1624 	if (vd->vdev_removing)
1625 		return;
1626 
1627 	/*
1628 	 * If the metaslab is dirty it probably means that we've done
1629 	 * some allocations or frees that have changed our histograms
1630 	 * and thus the weight.
1631 	 */
1632 	for (int t = 0; t < TXG_SIZE; t++) {
1633 		if (txg_list_member(&vd->vdev_ms_list, msp, t))
1634 			return;
1635 	}
1636 
1637 	/*
1638 	 * This verification checks that our in-memory state is consistent
1639 	 * with what's on disk. If the pool is read-only then there aren't
1640 	 * any changes and we just have the initially-loaded state.
1641 	 */
1642 	if (!spa_writeable(msp->ms_group->mg_vd->vdev_spa))
1643 		return;
1644 
1645 	/* some extra verification for in-core tree if you can */
1646 	if (msp->ms_loaded) {
1647 		range_tree_stat_verify(msp->ms_allocatable);
1648 		VERIFY(space_map_histogram_verify(msp->ms_sm,
1649 		    msp->ms_allocatable));
1650 	}
1651 
1652 	uint64_t weight = msp->ms_weight;
1653 	uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
1654 	boolean_t space_based = WEIGHT_IS_SPACEBASED(msp->ms_weight);
1655 	uint64_t frag = msp->ms_fragmentation;
1656 	uint64_t max_segsize = msp->ms_max_size;
1657 
1658 	msp->ms_weight = 0;
1659 	msp->ms_fragmentation = 0;
1660 	msp->ms_max_size = 0;
1661 
1662 	/*
1663 	 * This function is used for verification purposes. Regardless of
1664 	 * whether metaslab_weight() thinks this metaslab should be active or
1665 	 * not, we want to ensure that the actual weight (and therefore the
1666 	 * value of ms_weight) would be the same if it was to be recalculated
1667 	 * at this point.
1668 	 */
1669 	msp->ms_weight = metaslab_weight(msp) | was_active;
1670 
1671 	VERIFY3U(max_segsize, ==, msp->ms_max_size);
1672 
1673 	/*
1674 	 * If the weight type changed then there is no point in doing
1675 	 * verification. Revert fields to their original values.
1676 	 */
1677 	if ((space_based && !WEIGHT_IS_SPACEBASED(msp->ms_weight)) ||
1678 	    (!space_based && WEIGHT_IS_SPACEBASED(msp->ms_weight))) {
1679 		msp->ms_fragmentation = frag;
1680 		msp->ms_weight = weight;
1681 		return;
1682 	}
1683 
1684 	VERIFY3U(msp->ms_fragmentation, ==, frag);
1685 	VERIFY3U(msp->ms_weight, ==, weight);
1686 }
1687 
1688 /*
1689  * Wait for any in-progress metaslab loads to complete.
1690  */
1691 static void
metaslab_load_wait(metaslab_t * msp)1692 metaslab_load_wait(metaslab_t *msp)
1693 {
1694 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1695 
1696 	while (msp->ms_loading) {
1697 		ASSERT(!msp->ms_loaded);
1698 		cv_wait(&msp->ms_load_cv, &msp->ms_lock);
1699 	}
1700 }
1701 
1702 static int
metaslab_load_impl(metaslab_t * msp)1703 metaslab_load_impl(metaslab_t *msp)
1704 {
1705 	int error = 0;
1706 
1707 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1708 	ASSERT(msp->ms_loading);
1709 	ASSERT(!msp->ms_condensing);
1710 
1711 	/*
1712 	 * We temporarily drop the lock to unblock other operations while we
1713 	 * are reading the space map. Therefore, metaslab_sync() and
1714 	 * metaslab_sync_done() can run at the same time as we do.
1715 	 *
1716 	 * metaslab_sync() can append to the space map while we are loading.
1717 	 * Therefore we load only entries that existed when we started the
1718 	 * load. Additionally, metaslab_sync_done() has to wait for the load
1719 	 * to complete because there are potential races like metaslab_load()
1720 	 * loading parts of the space map that are currently being appended
1721 	 * by metaslab_sync(). If we didn't, the ms_allocatable would have
1722 	 * entries that metaslab_sync_done() would try to re-add later.
1723 	 *
1724 	 * That's why before dropping the lock we remember the synced length
1725 	 * of the metaslab and read up to that point of the space map,
1726 	 * ignoring entries appended by metaslab_sync() that happen after we
1727 	 * drop the lock.
1728 	 */
1729 	uint64_t length = msp->ms_synced_length;
1730 	mutex_exit(&msp->ms_lock);
1731 
1732 	if (msp->ms_sm != NULL) {
1733 		error = space_map_load_length(msp->ms_sm, msp->ms_allocatable,
1734 		    SM_FREE, length);
1735 	} else {
1736 		/*
1737 		 * The space map has not been allocated yet, so treat
1738 		 * all the space in the metaslab as free and add it to the
1739 		 * ms_allocatable tree.
1740 		 */
1741 		range_tree_add(msp->ms_allocatable,
1742 		    msp->ms_start, msp->ms_size);
1743 	}
1744 
1745 	/*
1746 	 * We need to grab the ms_sync_lock to prevent metaslab_sync() from
1747 	 * changing the ms_sm and the metaslab's range trees while we are
1748 	 * about to use them and populate the ms_allocatable. The ms_lock
1749 	 * is insufficient for this because metaslab_sync() doesn't hold
1750 	 * the ms_lock while writing the ms_checkpointing tree to disk.
1751 	 */
1752 	mutex_enter(&msp->ms_sync_lock);
1753 	mutex_enter(&msp->ms_lock);
1754 	ASSERT(!msp->ms_condensing);
1755 
1756 	if (error != 0) {
1757 		mutex_exit(&msp->ms_sync_lock);
1758 		return (error);
1759 	}
1760 
1761 	ASSERT3P(msp->ms_group, !=, NULL);
1762 	msp->ms_loaded = B_TRUE;
1763 
1764 	/*
1765 	 * The ms_allocatable contains the segments that exist in the
1766 	 * ms_defer trees [see ms_synced_length]. Thus we need to remove
1767 	 * them from ms_allocatable as they will be added again in
1768 	 * metaslab_sync_done().
1769 	 */
1770 	for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1771 		range_tree_walk(msp->ms_defer[t],
1772 		    range_tree_remove, msp->ms_allocatable);
1773 	}
1774 
1775 	/*
1776 	 * Call metaslab_recalculate_weight_and_sort() now that the
1777 	 * metaslab is loaded so we get the metaslab's real weight.
1778 	 *
1779 	 * Unless this metaslab was created with older software and
1780 	 * has not yet been converted to use segment-based weight, we
1781 	 * expect the new weight to be better or equal to the weight
1782 	 * that the metaslab had while it was not loaded. This is
1783 	 * because the old weight does not take into account the
1784 	 * consolidation of adjacent segments between TXGs. [see
1785 	 * comment for ms_synchist and ms_deferhist[] for more info]
1786 	 */
1787 	uint64_t weight = msp->ms_weight;
1788 	metaslab_recalculate_weight_and_sort(msp);
1789 	if (!WEIGHT_IS_SPACEBASED(weight))
1790 		ASSERT3U(weight, <=, msp->ms_weight);
1791 	msp->ms_max_size = metaslab_block_maxsize(msp);
1792 
1793 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1794 	metaslab_verify_space(msp, spa_syncing_txg(spa));
1795 	mutex_exit(&msp->ms_sync_lock);
1796 
1797 	return (0);
1798 }
1799 
1800 int
metaslab_load(metaslab_t * msp)1801 metaslab_load(metaslab_t *msp)
1802 {
1803 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1804 
1805 	/*
1806 	 * There may be another thread loading the same metaslab, if that's
1807 	 * the case just wait until the other thread is done and return.
1808 	 */
1809 	metaslab_load_wait(msp);
1810 	if (msp->ms_loaded)
1811 		return (0);
1812 	VERIFY(!msp->ms_loading);
1813 	ASSERT(!msp->ms_condensing);
1814 
1815 	msp->ms_loading = B_TRUE;
1816 	int error = metaslab_load_impl(msp);
1817 	msp->ms_loading = B_FALSE;
1818 	cv_broadcast(&msp->ms_load_cv);
1819 
1820 	return (error);
1821 }
1822 
1823 void
metaslab_unload(metaslab_t * msp)1824 metaslab_unload(metaslab_t *msp)
1825 {
1826 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1827 
1828 	metaslab_verify_weight_and_frag(msp);
1829 
1830 	range_tree_vacate(msp->ms_allocatable, NULL, NULL);
1831 	msp->ms_loaded = B_FALSE;
1832 
1833 	msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
1834 	msp->ms_max_size = 0;
1835 
1836 	/*
1837 	 * We explicitly recalculate the metaslab's weight based on its space
1838 	 * map (as it is now not loaded). We want unload metaslabs to always
1839 	 * have their weights calculated from the space map histograms, while
1840 	 * loaded ones have it calculated from their in-core range tree
1841 	 * [see metaslab_load()]. This way, the weight reflects the information
1842 	 * available in-core, whether it is loaded or not
1843 	 *
1844 	 * If ms_group == NULL means that we came here from metaslab_fini(),
1845 	 * at which point it doesn't make sense for us to do the recalculation
1846 	 * and the sorting.
1847 	 */
1848 	if (msp->ms_group != NULL)
1849 		metaslab_recalculate_weight_and_sort(msp);
1850 }
1851 
1852 static void
metaslab_space_update(vdev_t * vd,metaslab_class_t * mc,int64_t alloc_delta,int64_t defer_delta,int64_t space_delta)1853 metaslab_space_update(vdev_t *vd, metaslab_class_t *mc, int64_t alloc_delta,
1854     int64_t defer_delta, int64_t space_delta)
1855 {
1856 	vdev_space_update(vd, alloc_delta, defer_delta, space_delta);
1857 
1858 	ASSERT3P(vd->vdev_spa->spa_root_vdev, ==, vd->vdev_parent);
1859 	ASSERT(vd->vdev_ms_count != 0);
1860 
1861 	metaslab_class_space_update(mc, alloc_delta, defer_delta, space_delta,
1862 	    vdev_deflated_space(vd, space_delta));
1863 }
1864 
1865 int
metaslab_init(metaslab_group_t * mg,uint64_t id,uint64_t object,uint64_t txg,metaslab_t ** msp)1866 metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object, uint64_t txg,
1867     metaslab_t **msp)
1868 {
1869 	vdev_t *vd = mg->mg_vd;
1870 	spa_t *spa = vd->vdev_spa;
1871 	objset_t *mos = spa->spa_meta_objset;
1872 	metaslab_t *ms;
1873 	int error;
1874 
1875 	ms = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
1876 	mutex_init(&ms->ms_lock, NULL, MUTEX_DEFAULT, NULL);
1877 	mutex_init(&ms->ms_sync_lock, NULL, MUTEX_DEFAULT, NULL);
1878 	cv_init(&ms->ms_load_cv, NULL, CV_DEFAULT, NULL);
1879 
1880 	ms->ms_id = id;
1881 	ms->ms_start = id << vd->vdev_ms_shift;
1882 	ms->ms_size = 1ULL << vd->vdev_ms_shift;
1883 	ms->ms_allocator = -1;
1884 	ms->ms_new = B_TRUE;
1885 
1886 	/*
1887 	 * We only open space map objects that already exist. All others
1888 	 * will be opened when we finally allocate an object for it.
1889 	 *
1890 	 * Note:
1891 	 * When called from vdev_expand(), we can't call into the DMU as
1892 	 * we are holding the spa_config_lock as a writer and we would
1893 	 * deadlock [see relevant comment in vdev_metaslab_init()]. in
1894 	 * that case, the object parameter is zero though, so we won't
1895 	 * call into the DMU.
1896 	 */
1897 	if (object != 0) {
1898 		error = space_map_open(&ms->ms_sm, mos, object, ms->ms_start,
1899 		    ms->ms_size, vd->vdev_ashift);
1900 
1901 		if (error != 0) {
1902 			kmem_free(ms, sizeof (metaslab_t));
1903 			return (error);
1904 		}
1905 
1906 		ASSERT(ms->ms_sm != NULL);
1907 		ASSERT3S(space_map_allocated(ms->ms_sm), >=, 0);
1908 		ms->ms_allocated_space = space_map_allocated(ms->ms_sm);
1909 	}
1910 
1911 	/*
1912 	 * We create the ms_allocatable here, but we don't create the
1913 	 * other range trees until metaslab_sync_done().  This serves
1914 	 * two purposes: it allows metaslab_sync_done() to detect the
1915 	 * addition of new space; and for debugging, it ensures that
1916 	 * we'd data fault on any attempt to use this metaslab before
1917 	 * it's ready.
1918 	 */
1919 	ms->ms_allocatable = range_tree_create_impl(&rt_avl_ops, &ms->ms_allocatable_by_size,
1920 	    metaslab_rangesize_compare, 0);
1921 	metaslab_group_add(mg, ms);
1922 
1923 	metaslab_set_fragmentation(ms);
1924 
1925 	/*
1926 	 * If we're opening an existing pool (txg == 0) or creating
1927 	 * a new one (txg == TXG_INITIAL), all space is available now.
1928 	 * If we're adding space to an existing pool, the new space
1929 	 * does not become available until after this txg has synced.
1930 	 * The metaslab's weight will also be initialized when we sync
1931 	 * out this txg. This ensures that we don't attempt to allocate
1932 	 * from it before we have initialized it completely.
1933 	 */
1934 	if (txg <= TXG_INITIAL) {
1935 		metaslab_sync_done(ms, 0);
1936 		metaslab_space_update(vd, mg->mg_class,
1937 		    metaslab_allocated_space(ms), 0, 0);
1938 	}
1939 
1940 	/*
1941 	 * If metaslab_debug_load is set and we're initializing a metaslab
1942 	 * that has an allocated space map object then load the space map
1943 	 * so that we can verify frees.
1944 	 */
1945 	if (metaslab_debug_load && ms->ms_sm != NULL) {
1946 		mutex_enter(&ms->ms_lock);
1947 		VERIFY0(metaslab_load(ms));
1948 		mutex_exit(&ms->ms_lock);
1949 	}
1950 
1951 	if (txg != 0) {
1952 		vdev_dirty(vd, 0, NULL, txg);
1953 		vdev_dirty(vd, VDD_METASLAB, ms, txg);
1954 	}
1955 
1956 	*msp = ms;
1957 
1958 	return (0);
1959 }
1960 
1961 void
metaslab_fini(metaslab_t * msp)1962 metaslab_fini(metaslab_t *msp)
1963 {
1964 	metaslab_group_t *mg = msp->ms_group;
1965 	vdev_t *vd = mg->mg_vd;
1966 
1967 	metaslab_group_remove(mg, msp);
1968 
1969 	mutex_enter(&msp->ms_lock);
1970 	VERIFY(msp->ms_group == NULL);
1971 	metaslab_space_update(vd, mg->mg_class,
1972 	    -metaslab_allocated_space(msp), 0, -msp->ms_size);
1973 
1974 	space_map_close(msp->ms_sm);
1975 
1976 	metaslab_unload(msp);
1977 
1978 	range_tree_destroy(msp->ms_allocatable);
1979 	range_tree_destroy(msp->ms_freeing);
1980 	range_tree_destroy(msp->ms_freed);
1981 
1982 	for (int t = 0; t < TXG_SIZE; t++) {
1983 		range_tree_destroy(msp->ms_allocating[t]);
1984 	}
1985 
1986 	for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1987 		range_tree_destroy(msp->ms_defer[t]);
1988 	}
1989 	ASSERT0(msp->ms_deferspace);
1990 
1991 	range_tree_destroy(msp->ms_checkpointing);
1992 
1993 	for (int t = 0; t < TXG_SIZE; t++)
1994 		ASSERT(!txg_list_member(&vd->vdev_ms_list, msp, t));
1995 
1996 	mutex_exit(&msp->ms_lock);
1997 	cv_destroy(&msp->ms_load_cv);
1998 	mutex_destroy(&msp->ms_lock);
1999 	mutex_destroy(&msp->ms_sync_lock);
2000 	ASSERT3U(msp->ms_allocator, ==, -1);
2001 
2002 	kmem_free(msp, sizeof (metaslab_t));
2003 }
2004 
2005 #define	FRAGMENTATION_TABLE_SIZE	17
2006 
2007 /*
2008  * This table defines a segment size based fragmentation metric that will
2009  * allow each metaslab to derive its own fragmentation value. This is done
2010  * by calculating the space in each bucket of the spacemap histogram and
2011  * multiplying that by the fragmentation metric in this table. Doing
2012  * this for all buckets and dividing it by the total amount of free
2013  * space in this metaslab (i.e. the total free space in all buckets) gives
2014  * us the fragmentation metric. This means that a high fragmentation metric
2015  * equates to most of the free space being comprised of small segments.
2016  * Conversely, if the metric is low, then most of the free space is in
2017  * large segments. A 10% change in fragmentation equates to approximately
2018  * double the number of segments.
2019  *
2020  * This table defines 0% fragmented space using 16MB segments. Testing has
2021  * shown that segments that are greater than or equal to 16MB do not suffer
2022  * from drastic performance problems. Using this value, we derive the rest
2023  * of the table. Since the fragmentation value is never stored on disk, it
2024  * is possible to change these calculations in the future.
2025  */
2026 int zfs_frag_table[FRAGMENTATION_TABLE_SIZE] = {
2027 	100,	/* 512B	*/
2028 	100,	/* 1K	*/
2029 	98,	/* 2K	*/
2030 	95,	/* 4K	*/
2031 	90,	/* 8K	*/
2032 	80,	/* 16K	*/
2033 	70,	/* 32K	*/
2034 	60,	/* 64K	*/
2035 	50,	/* 128K	*/
2036 	40,	/* 256K	*/
2037 	30,	/* 512K	*/
2038 	20,	/* 1M	*/
2039 	15,	/* 2M	*/
2040 	10,	/* 4M	*/
2041 	5,	/* 8M	*/
2042 	0	/* 16M	*/
2043 };
2044 
2045 /*
2046  * Calculate the metaslab's fragmentation metric and set ms_fragmentation.
2047  * Setting this value to ZFS_FRAG_INVALID means that the metaslab has not
2048  * been upgraded and does not support this metric. Otherwise, the return
2049  * value should be in the range [0, 100].
2050  */
2051 static void
metaslab_set_fragmentation(metaslab_t * msp)2052 metaslab_set_fragmentation(metaslab_t *msp)
2053 {
2054 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2055 	uint64_t fragmentation = 0;
2056 	uint64_t total = 0;
2057 	boolean_t feature_enabled = spa_feature_is_enabled(spa,
2058 	    SPA_FEATURE_SPACEMAP_HISTOGRAM);
2059 
2060 	if (!feature_enabled) {
2061 		msp->ms_fragmentation = ZFS_FRAG_INVALID;
2062 		return;
2063 	}
2064 
2065 	/*
2066 	 * A null space map means that the entire metaslab is free
2067 	 * and thus is not fragmented.
2068 	 */
2069 	if (msp->ms_sm == NULL) {
2070 		msp->ms_fragmentation = 0;
2071 		return;
2072 	}
2073 
2074 	/*
2075 	 * If this metaslab's space map has not been upgraded, flag it
2076 	 * so that we upgrade next time we encounter it.
2077 	 */
2078 	if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
2079 		uint64_t txg = spa_syncing_txg(spa);
2080 		vdev_t *vd = msp->ms_group->mg_vd;
2081 
2082 		/*
2083 		 * If we've reached the final dirty txg, then we must
2084 		 * be shutting down the pool. We don't want to dirty
2085 		 * any data past this point so skip setting the condense
2086 		 * flag. We can retry this action the next time the pool
2087 		 * is imported.
2088 		 */
2089 		if (spa_writeable(spa) && txg < spa_final_dirty_txg(spa)) {
2090 			msp->ms_condense_wanted = B_TRUE;
2091 			vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
2092 			zfs_dbgmsg("txg %llu, requesting force condense: "
2093 			    "ms_id %llu, vdev_id %llu", txg, msp->ms_id,
2094 			    vd->vdev_id);
2095 		}
2096 		msp->ms_fragmentation = ZFS_FRAG_INVALID;
2097 		return;
2098 	}
2099 
2100 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
2101 		uint64_t space = 0;
2102 		uint8_t shift = msp->ms_sm->sm_shift;
2103 
2104 		int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
2105 		    FRAGMENTATION_TABLE_SIZE - 1);
2106 
2107 		if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
2108 			continue;
2109 
2110 		space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
2111 		total += space;
2112 
2113 		ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
2114 		fragmentation += space * zfs_frag_table[idx];
2115 	}
2116 
2117 	if (total > 0)
2118 		fragmentation /= total;
2119 	ASSERT3U(fragmentation, <=, 100);
2120 
2121 	msp->ms_fragmentation = fragmentation;
2122 }
2123 
2124 /*
2125  * Compute a weight -- a selection preference value -- for the given metaslab.
2126  * This is based on the amount of free space, the level of fragmentation,
2127  * the LBA range, and whether the metaslab is loaded.
2128  */
2129 static uint64_t
metaslab_space_weight(metaslab_t * msp)2130 metaslab_space_weight(metaslab_t *msp)
2131 {
2132 	metaslab_group_t *mg = msp->ms_group;
2133 	vdev_t *vd = mg->mg_vd;
2134 	uint64_t weight, space;
2135 
2136 	ASSERT(MUTEX_HELD(&msp->ms_lock));
2137 	ASSERT(!vd->vdev_removing);
2138 
2139 	/*
2140 	 * The baseline weight is the metaslab's free space.
2141 	 */
2142 	space = msp->ms_size - metaslab_allocated_space(msp);
2143 
2144 	if (metaslab_fragmentation_factor_enabled &&
2145 	    msp->ms_fragmentation != ZFS_FRAG_INVALID) {
2146 		/*
2147 		 * Use the fragmentation information to inversely scale
2148 		 * down the baseline weight. We need to ensure that we
2149 		 * don't exclude this metaslab completely when it's 100%
2150 		 * fragmented. To avoid this we reduce the fragmented value
2151 		 * by 1.
2152 		 */
2153 		space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
2154 
2155 		/*
2156 		 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
2157 		 * this metaslab again. The fragmentation metric may have
2158 		 * decreased the space to something smaller than
2159 		 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
2160 		 * so that we can consume any remaining space.
2161 		 */
2162 		if (space > 0 && space < SPA_MINBLOCKSIZE)
2163 			space = SPA_MINBLOCKSIZE;
2164 	}
2165 	weight = space;
2166 
2167 	/*
2168 	 * Modern disks have uniform bit density and constant angular velocity.
2169 	 * Therefore, the outer recording zones are faster (higher bandwidth)
2170 	 * than the inner zones by the ratio of outer to inner track diameter,
2171 	 * which is typically around 2:1.  We account for this by assigning
2172 	 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
2173 	 * In effect, this means that we'll select the metaslab with the most
2174 	 * free bandwidth rather than simply the one with the most free space.
2175 	 */
2176 	if (!vd->vdev_nonrot && metaslab_lba_weighting_enabled) {
2177 		weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
2178 		ASSERT(weight >= space && weight <= 2 * space);
2179 	}
2180 
2181 	/*
2182 	 * If this metaslab is one we're actively using, adjust its
2183 	 * weight to make it preferable to any inactive metaslab so
2184 	 * we'll polish it off. If the fragmentation on this metaslab
2185 	 * has exceed our threshold, then don't mark it active.
2186 	 */
2187 	if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
2188 	    msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
2189 		weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
2190 	}
2191 
2192 	WEIGHT_SET_SPACEBASED(weight);
2193 	return (weight);
2194 }
2195 
2196 /*
2197  * Return the weight of the specified metaslab, according to the segment-based
2198  * weighting algorithm. The metaslab must be loaded. This function can
2199  * be called within a sync pass since it relies only on the metaslab's
2200  * range tree which is always accurate when the metaslab is loaded.
2201  */
2202 static uint64_t
metaslab_weight_from_range_tree(metaslab_t * msp)2203 metaslab_weight_from_range_tree(metaslab_t *msp)
2204 {
2205 	uint64_t weight = 0;
2206 	uint32_t segments = 0;
2207 
2208 	ASSERT(msp->ms_loaded);
2209 
2210 	for (int i = RANGE_TREE_HISTOGRAM_SIZE - 1; i >= SPA_MINBLOCKSHIFT;
2211 	    i--) {
2212 		uint8_t shift = msp->ms_group->mg_vd->vdev_ashift;
2213 		int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
2214 
2215 		segments <<= 1;
2216 		segments += msp->ms_allocatable->rt_histogram[i];
2217 
2218 		/*
2219 		 * The range tree provides more precision than the space map
2220 		 * and must be downgraded so that all values fit within the
2221 		 * space map's histogram. This allows us to compare loaded
2222 		 * vs. unloaded metaslabs to determine which metaslab is
2223 		 * considered "best".
2224 		 */
2225 		if (i > max_idx)
2226 			continue;
2227 
2228 		if (segments != 0) {
2229 			WEIGHT_SET_COUNT(weight, segments);
2230 			WEIGHT_SET_INDEX(weight, i);
2231 			WEIGHT_SET_ACTIVE(weight, 0);
2232 			break;
2233 		}
2234 	}
2235 	return (weight);
2236 }
2237 
2238 /*
2239  * Calculate the weight based on the on-disk histogram. This should only
2240  * be called after a sync pass has completely finished since the on-disk
2241  * information is updated in metaslab_sync().
2242  */
2243 static uint64_t
metaslab_weight_from_spacemap(metaslab_t * msp)2244 metaslab_weight_from_spacemap(metaslab_t *msp)
2245 {
2246 	space_map_t *sm = msp->ms_sm;
2247 	ASSERT(!msp->ms_loaded);
2248 	ASSERT(sm != NULL);
2249 	ASSERT3U(space_map_object(sm), !=, 0);
2250 	ASSERT3U(sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
2251 
2252 	/*
2253 	 * Create a joint histogram from all the segments that have made
2254 	 * it to the metaslab's space map histogram, that are not yet
2255 	 * available for allocation because they are still in the freeing
2256 	 * pipeline (e.g. freeing, freed, and defer trees). Then subtract
2257 	 * these segments from the space map's histogram to get a more
2258 	 * accurate weight.
2259 	 */
2260 	uint64_t deferspace_histogram[SPACE_MAP_HISTOGRAM_SIZE] = {0};
2261 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
2262 		deferspace_histogram[i] += msp->ms_synchist[i];
2263 	for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2264 		for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
2265 			deferspace_histogram[i] += msp->ms_deferhist[t][i];
2266 		}
2267 	}
2268 
2269 	uint64_t weight = 0;
2270 	for (int i = SPACE_MAP_HISTOGRAM_SIZE - 1; i >= 0; i--) {
2271 		ASSERT3U(sm->sm_phys->smp_histogram[i], >=,
2272 		    deferspace_histogram[i]);
2273 		uint64_t count =
2274 		    sm->sm_phys->smp_histogram[i] - deferspace_histogram[i];
2275 		if (count != 0) {
2276 			WEIGHT_SET_COUNT(weight, count);
2277 			WEIGHT_SET_INDEX(weight, i + sm->sm_shift);
2278 			WEIGHT_SET_ACTIVE(weight, 0);
2279 			break;
2280 		}
2281 	}
2282 	return (weight);
2283 }
2284 
2285 /*
2286  * Compute a segment-based weight for the specified metaslab. The weight
2287  * is determined by highest bucket in the histogram. The information
2288  * for the highest bucket is encoded into the weight value.
2289  */
2290 static uint64_t
metaslab_segment_weight(metaslab_t * msp)2291 metaslab_segment_weight(metaslab_t *msp)
2292 {
2293 	metaslab_group_t *mg = msp->ms_group;
2294 	uint64_t weight = 0;
2295 	uint8_t shift = mg->mg_vd->vdev_ashift;
2296 
2297 	ASSERT(MUTEX_HELD(&msp->ms_lock));
2298 
2299 	/*
2300 	 * The metaslab is completely free.
2301 	 */
2302 	if (metaslab_allocated_space(msp) == 0) {
2303 		int idx = highbit64(msp->ms_size) - 1;
2304 		int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
2305 
2306 		if (idx < max_idx) {
2307 			WEIGHT_SET_COUNT(weight, 1ULL);
2308 			WEIGHT_SET_INDEX(weight, idx);
2309 		} else {
2310 			WEIGHT_SET_COUNT(weight, 1ULL << (idx - max_idx));
2311 			WEIGHT_SET_INDEX(weight, max_idx);
2312 		}
2313 		WEIGHT_SET_ACTIVE(weight, 0);
2314 		ASSERT(!WEIGHT_IS_SPACEBASED(weight));
2315 
2316 		return (weight);
2317 	}
2318 
2319 	ASSERT3U(msp->ms_sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
2320 
2321 	/*
2322 	 * If the metaslab is fully allocated then just make the weight 0.
2323 	 */
2324 	if (metaslab_allocated_space(msp) == msp->ms_size)
2325 		return (0);
2326 	/*
2327 	 * If the metaslab is already loaded, then use the range tree to
2328 	 * determine the weight. Otherwise, we rely on the space map information
2329 	 * to generate the weight.
2330 	 */
2331 	if (msp->ms_loaded) {
2332 		weight = metaslab_weight_from_range_tree(msp);
2333 	} else {
2334 		weight = metaslab_weight_from_spacemap(msp);
2335 	}
2336 
2337 	/*
2338 	 * If the metaslab was active the last time we calculated its weight
2339 	 * then keep it active. We want to consume the entire region that
2340 	 * is associated with this weight.
2341 	 */
2342 	if (msp->ms_activation_weight != 0 && weight != 0)
2343 		WEIGHT_SET_ACTIVE(weight, WEIGHT_GET_ACTIVE(msp->ms_weight));
2344 	return (weight);
2345 }
2346 
2347 /*
2348  * Determine if we should attempt to allocate from this metaslab. If the
2349  * metaslab has a maximum size then we can quickly determine if the desired
2350  * allocation size can be satisfied. Otherwise, if we're using segment-based
2351  * weighting then we can determine the maximum allocation that this metaslab
2352  * can accommodate based on the index encoded in the weight. If we're using
2353  * space-based weights then rely on the entire weight (excluding the weight
2354  * type bit).
2355  */
2356 boolean_t
metaslab_should_allocate(metaslab_t * msp,uint64_t asize)2357 metaslab_should_allocate(metaslab_t *msp, uint64_t asize)
2358 {
2359 	boolean_t should_allocate;
2360 
2361 	if (msp->ms_max_size != 0)
2362 		return (msp->ms_max_size >= asize);
2363 
2364 	if (!WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
2365 		/*
2366 		 * The metaslab segment weight indicates segments in the
2367 		 * range [2^i, 2^(i+1)), where i is the index in the weight.
2368 		 * Since the asize might be in the middle of the range, we
2369 		 * should attempt the allocation if asize < 2^(i+1).
2370 		 */
2371 		should_allocate = (asize <
2372 		    1ULL << (WEIGHT_GET_INDEX(msp->ms_weight) + 1));
2373 	} else {
2374 		should_allocate = (asize <=
2375 		    (msp->ms_weight & ~METASLAB_WEIGHT_TYPE));
2376 	}
2377 	return (should_allocate);
2378 }
2379 
2380 static uint64_t
metaslab_weight(metaslab_t * msp)2381 metaslab_weight(metaslab_t *msp)
2382 {
2383 	vdev_t *vd = msp->ms_group->mg_vd;
2384 	spa_t *spa = vd->vdev_spa;
2385 	uint64_t weight;
2386 
2387 	ASSERT(MUTEX_HELD(&msp->ms_lock));
2388 
2389 	/*
2390 	 * If this vdev is in the process of being removed, there is nothing
2391 	 * for us to do here.
2392 	 */
2393 	if (vd->vdev_removing)
2394 		return (0);
2395 
2396 	metaslab_set_fragmentation(msp);
2397 
2398 	/*
2399 	 * Update the maximum size if the metaslab is loaded. This will
2400 	 * ensure that we get an accurate maximum size if newly freed space
2401 	 * has been added back into the free tree.
2402 	 */
2403 	if (msp->ms_loaded)
2404 		msp->ms_max_size = metaslab_block_maxsize(msp);
2405 	else
2406 		ASSERT0(msp->ms_max_size);
2407 
2408 	/*
2409 	 * Segment-based weighting requires space map histogram support.
2410 	 */
2411 	if (zfs_metaslab_segment_weight_enabled &&
2412 	    spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM) &&
2413 	    (msp->ms_sm == NULL || msp->ms_sm->sm_dbuf->db_size ==
2414 	    sizeof (space_map_phys_t))) {
2415 		weight = metaslab_segment_weight(msp);
2416 	} else {
2417 		weight = metaslab_space_weight(msp);
2418 	}
2419 	return (weight);
2420 }
2421 
2422 void
metaslab_recalculate_weight_and_sort(metaslab_t * msp)2423 metaslab_recalculate_weight_and_sort(metaslab_t *msp)
2424 {
2425 	/* note: we preserve the mask (e.g. indication of primary, etc..) */
2426 	uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
2427 	metaslab_group_sort(msp->ms_group, msp,
2428 	    metaslab_weight(msp) | was_active);
2429 }
2430 
2431 static int
metaslab_activate_allocator(metaslab_group_t * mg,metaslab_t * msp,int allocator,uint64_t activation_weight)2432 metaslab_activate_allocator(metaslab_group_t *mg, metaslab_t *msp,
2433     int allocator, uint64_t activation_weight)
2434 {
2435 	/*
2436 	 * If we're activating for the claim code, we don't want to actually
2437 	 * set the metaslab up for a specific allocator.
2438 	 */
2439 	if (activation_weight == METASLAB_WEIGHT_CLAIM)
2440 		return (0);
2441 	metaslab_t **arr = (activation_weight == METASLAB_WEIGHT_PRIMARY ?
2442 	    mg->mg_primaries : mg->mg_secondaries);
2443 
2444 	ASSERT(MUTEX_HELD(&msp->ms_lock));
2445 	mutex_enter(&mg->mg_lock);
2446 	if (arr[allocator] != NULL) {
2447 		mutex_exit(&mg->mg_lock);
2448 		return (EEXIST);
2449 	}
2450 
2451 	arr[allocator] = msp;
2452 	ASSERT3S(msp->ms_allocator, ==, -1);
2453 	msp->ms_allocator = allocator;
2454 	msp->ms_primary = (activation_weight == METASLAB_WEIGHT_PRIMARY);
2455 	mutex_exit(&mg->mg_lock);
2456 
2457 	return (0);
2458 }
2459 
2460 static int
metaslab_activate(metaslab_t * msp,int allocator,uint64_t activation_weight)2461 metaslab_activate(metaslab_t *msp, int allocator, uint64_t activation_weight)
2462 {
2463 	ASSERT(MUTEX_HELD(&msp->ms_lock));
2464 
2465 	if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
2466 		int error = metaslab_load(msp);
2467 		if (error != 0) {
2468 			metaslab_group_sort(msp->ms_group, msp, 0);
2469 			return (error);
2470 		}
2471 		if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
2472 			/*
2473 			 * The metaslab was activated for another allocator
2474 			 * while we were waiting, we should reselect.
2475 			 */
2476 			return (EBUSY);
2477 		}
2478 		if ((error = metaslab_activate_allocator(msp->ms_group, msp,
2479 		    allocator, activation_weight)) != 0) {
2480 			return (error);
2481 		}
2482 
2483 		msp->ms_activation_weight = msp->ms_weight;
2484 		metaslab_group_sort(msp->ms_group, msp,
2485 		    msp->ms_weight | activation_weight);
2486 	}
2487 	ASSERT(msp->ms_loaded);
2488 	ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
2489 
2490 	return (0);
2491 }
2492 
2493 static void
metaslab_passivate_allocator(metaslab_group_t * mg,metaslab_t * msp,uint64_t weight)2494 metaslab_passivate_allocator(metaslab_group_t *mg, metaslab_t *msp,
2495     uint64_t weight)
2496 {
2497 	ASSERT(MUTEX_HELD(&msp->ms_lock));
2498 	if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
2499 		metaslab_group_sort(mg, msp, weight);
2500 		return;
2501 	}
2502 
2503 	mutex_enter(&mg->mg_lock);
2504 	ASSERT3P(msp->ms_group, ==, mg);
2505 	if (msp->ms_primary) {
2506 		ASSERT3U(0, <=, msp->ms_allocator);
2507 		ASSERT3U(msp->ms_allocator, <, mg->mg_allocators);
2508 		ASSERT3P(mg->mg_primaries[msp->ms_allocator], ==, msp);
2509 		ASSERT(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
2510 		mg->mg_primaries[msp->ms_allocator] = NULL;
2511 	} else {
2512 		ASSERT(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
2513 		ASSERT3P(mg->mg_secondaries[msp->ms_allocator], ==, msp);
2514 		mg->mg_secondaries[msp->ms_allocator] = NULL;
2515 	}
2516 	msp->ms_allocator = -1;
2517 	metaslab_group_sort_impl(mg, msp, weight);
2518 	mutex_exit(&mg->mg_lock);
2519 }
2520 
2521 static void
metaslab_passivate(metaslab_t * msp,uint64_t weight)2522 metaslab_passivate(metaslab_t *msp, uint64_t weight)
2523 {
2524 	uint64_t size = weight & ~METASLAB_WEIGHT_TYPE;
2525 
2526 	/*
2527 	 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
2528 	 * this metaslab again.  In that case, it had better be empty,
2529 	 * or we would be leaving space on the table.
2530 	 */
2531 	ASSERT(size >= SPA_MINBLOCKSIZE ||
2532 	    range_tree_is_empty(msp->ms_allocatable));
2533 	ASSERT0(weight & METASLAB_ACTIVE_MASK);
2534 
2535 	msp->ms_activation_weight = 0;
2536 	metaslab_passivate_allocator(msp->ms_group, msp, weight);
2537 	ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
2538 }
2539 
2540 /*
2541  * Segment-based metaslabs are activated once and remain active until
2542  * we either fail an allocation attempt (similar to space-based metaslabs)
2543  * or have exhausted the free space in zfs_metaslab_switch_threshold
2544  * buckets since the metaslab was activated. This function checks to see
2545  * if we've exhaused the zfs_metaslab_switch_threshold buckets in the
2546  * metaslab and passivates it proactively. This will allow us to select a
2547  * metaslabs with larger contiguous region if any remaining within this
2548  * metaslab group. If we're in sync pass > 1, then we continue using this
2549  * metaslab so that we don't dirty more block and cause more sync passes.
2550  */
2551 void
metaslab_segment_may_passivate(metaslab_t * msp)2552 metaslab_segment_may_passivate(metaslab_t *msp)
2553 {
2554 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2555 
2556 	if (WEIGHT_IS_SPACEBASED(msp->ms_weight) || spa_sync_pass(spa) > 1)
2557 		return;
2558 
2559 	/*
2560 	 * Since we are in the middle of a sync pass, the most accurate
2561 	 * information that is accessible to us is the in-core range tree
2562 	 * histogram; calculate the new weight based on that information.
2563 	 */
2564 	uint64_t weight = metaslab_weight_from_range_tree(msp);
2565 	int activation_idx = WEIGHT_GET_INDEX(msp->ms_activation_weight);
2566 	int current_idx = WEIGHT_GET_INDEX(weight);
2567 
2568 	if (current_idx <= activation_idx - zfs_metaslab_switch_threshold)
2569 		metaslab_passivate(msp, weight);
2570 }
2571 
2572 static void
metaslab_preload(void * arg)2573 metaslab_preload(void *arg)
2574 {
2575 	metaslab_t *msp = arg;
2576 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2577 
2578 	ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
2579 
2580 	mutex_enter(&msp->ms_lock);
2581 	(void) metaslab_load(msp);
2582 	msp->ms_selected_txg = spa_syncing_txg(spa);
2583 	mutex_exit(&msp->ms_lock);
2584 }
2585 
2586 static void
metaslab_group_preload(metaslab_group_t * mg)2587 metaslab_group_preload(metaslab_group_t *mg)
2588 {
2589 	spa_t *spa = mg->mg_vd->vdev_spa;
2590 	metaslab_t *msp;
2591 	avl_tree_t *t = &mg->mg_metaslab_tree;
2592 	int m = 0;
2593 
2594 	if (spa_shutting_down(spa) || !metaslab_preload_enabled) {
2595 		taskq_wait(mg->mg_taskq);
2596 		return;
2597 	}
2598 
2599 	mutex_enter(&mg->mg_lock);
2600 
2601 	/*
2602 	 * Load the next potential metaslabs
2603 	 */
2604 	for (msp = avl_first(t); msp != NULL; msp = AVL_NEXT(t, msp)) {
2605 		ASSERT3P(msp->ms_group, ==, mg);
2606 
2607 		/*
2608 		 * We preload only the maximum number of metaslabs specified
2609 		 * by metaslab_preload_limit. If a metaslab is being forced
2610 		 * to condense then we preload it too. This will ensure
2611 		 * that force condensing happens in the next txg.
2612 		 */
2613 		if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
2614 			continue;
2615 		}
2616 
2617 		VERIFY(taskq_dispatch(mg->mg_taskq, metaslab_preload,
2618 		    msp, TQ_SLEEP) != 0);
2619 	}
2620 	mutex_exit(&mg->mg_lock);
2621 }
2622 
2623 /*
2624  * Determine if the space map's on-disk footprint is past our tolerance
2625  * for inefficiency. We would like to use the following criteria to make
2626  * our decision:
2627  *
2628  * 1. The size of the space map object should not dramatically increase as a
2629  * result of writing out the free space range tree.
2630  *
2631  * 2. The minimal on-disk space map representation is zfs_condense_pct/100
2632  * times the size than the free space range tree representation
2633  * (i.e. zfs_condense_pct = 110 and in-core = 1MB, minimal = 1.1MB).
2634  *
2635  * 3. The on-disk size of the space map should actually decrease.
2636  *
2637  * Unfortunately, we cannot compute the on-disk size of the space map in this
2638  * context because we cannot accurately compute the effects of compression, etc.
2639  * Instead, we apply the heuristic described in the block comment for
2640  * zfs_metaslab_condense_block_threshold - we only condense if the space used
2641  * is greater than a threshold number of blocks.
2642  */
2643 static boolean_t
metaslab_should_condense(metaslab_t * msp)2644 metaslab_should_condense(metaslab_t *msp)
2645 {
2646 	space_map_t *sm = msp->ms_sm;
2647 	vdev_t *vd = msp->ms_group->mg_vd;
2648 	uint64_t vdev_blocksize = 1 << vd->vdev_ashift;
2649 	uint64_t current_txg = spa_syncing_txg(vd->vdev_spa);
2650 
2651 	ASSERT(MUTEX_HELD(&msp->ms_lock));
2652 	ASSERT(msp->ms_loaded);
2653 
2654 	/*
2655 	 * Allocations and frees in early passes are generally more space
2656 	 * efficient (in terms of blocks described in space map entries)
2657 	 * than the ones in later passes (e.g. we don't compress after
2658 	 * sync pass 5) and condensing a metaslab multiple times in a txg
2659 	 * could degrade performance.
2660 	 *
2661 	 * Thus we prefer condensing each metaslab at most once every txg at
2662 	 * the earliest sync pass possible. If a metaslab is eligible for
2663 	 * condensing again after being considered for condensing within the
2664 	 * same txg, it will hopefully be dirty in the next txg where it will
2665 	 * be condensed at an earlier pass.
2666 	 */
2667 	if (msp->ms_condense_checked_txg == current_txg)
2668 		return (B_FALSE);
2669 	msp->ms_condense_checked_txg = current_txg;
2670 
2671 	/*
2672 	 * We always condense metaslabs that are empty and metaslabs for
2673 	 * which a condense request has been made.
2674 	 */
2675 	if (avl_is_empty(&msp->ms_allocatable_by_size) ||
2676 	    msp->ms_condense_wanted)
2677 		return (B_TRUE);
2678 
2679 	uint64_t object_size = space_map_length(msp->ms_sm);
2680 	uint64_t optimal_size = space_map_estimate_optimal_size(sm,
2681 	    msp->ms_allocatable, SM_NO_VDEVID);
2682 
2683 	dmu_object_info_t doi;
2684 	dmu_object_info_from_db(sm->sm_dbuf, &doi);
2685 	uint64_t record_size = MAX(doi.doi_data_block_size, vdev_blocksize);
2686 
2687 	return (object_size >= (optimal_size * zfs_condense_pct / 100) &&
2688 	    object_size > zfs_metaslab_condense_block_threshold * record_size);
2689 }
2690 
2691 /*
2692  * Condense the on-disk space map representation to its minimized form.
2693  * The minimized form consists of a small number of allocations followed by
2694  * the entries of the free range tree.
2695  */
2696 static void
metaslab_condense(metaslab_t * msp,uint64_t txg,dmu_tx_t * tx)2697 metaslab_condense(metaslab_t *msp, uint64_t txg, dmu_tx_t *tx)
2698 {
2699 	range_tree_t *condense_tree;
2700 	space_map_t *sm = msp->ms_sm;
2701 
2702 	ASSERT(MUTEX_HELD(&msp->ms_lock));
2703 	ASSERT(msp->ms_loaded);
2704 
2705 	zfs_dbgmsg("condensing: txg %llu, msp[%llu] %p, vdev id %llu, "
2706 	    "spa %s, smp size %llu, segments %lu, forcing condense=%s", txg,
2707 	    msp->ms_id, msp, msp->ms_group->mg_vd->vdev_id,
2708 	    msp->ms_group->mg_vd->vdev_spa->spa_name,
2709 	    space_map_length(msp->ms_sm),
2710 	    avl_numnodes(&msp->ms_allocatable->rt_root),
2711 	    msp->ms_condense_wanted ? "TRUE" : "FALSE");
2712 
2713 	msp->ms_condense_wanted = B_FALSE;
2714 
2715 	/*
2716 	 * Create an range tree that is 100% allocated. We remove segments
2717 	 * that have been freed in this txg, any deferred frees that exist,
2718 	 * and any allocation in the future. Removing segments should be
2719 	 * a relatively inexpensive operation since we expect these trees to
2720 	 * have a small number of nodes.
2721 	 */
2722 	condense_tree = range_tree_create(NULL, NULL);
2723 	range_tree_add(condense_tree, msp->ms_start, msp->ms_size);
2724 
2725 	range_tree_walk(msp->ms_freeing, range_tree_remove, condense_tree);
2726 	range_tree_walk(msp->ms_freed, range_tree_remove, condense_tree);
2727 
2728 	for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2729 		range_tree_walk(msp->ms_defer[t],
2730 		    range_tree_remove, condense_tree);
2731 	}
2732 
2733 	for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
2734 		range_tree_walk(msp->ms_allocating[(txg + t) & TXG_MASK],
2735 		    range_tree_remove, condense_tree);
2736 	}
2737 
2738 	/*
2739 	 * We're about to drop the metaslab's lock thus allowing
2740 	 * other consumers to change it's content. Set the
2741 	 * metaslab's ms_condensing flag to ensure that
2742 	 * allocations on this metaslab do not occur while we're
2743 	 * in the middle of committing it to disk. This is only critical
2744 	 * for ms_allocatable as all other range trees use per txg
2745 	 * views of their content.
2746 	 */
2747 	msp->ms_condensing = B_TRUE;
2748 
2749 	mutex_exit(&msp->ms_lock);
2750 	space_map_truncate(sm, zfs_metaslab_sm_blksz, tx);
2751 
2752 	/*
2753 	 * While we would ideally like to create a space map representation
2754 	 * that consists only of allocation records, doing so can be
2755 	 * prohibitively expensive because the in-core free tree can be
2756 	 * large, and therefore computationally expensive to subtract
2757 	 * from the condense_tree. Instead we sync out two trees, a cheap
2758 	 * allocation only tree followed by the in-core free tree. While not
2759 	 * optimal, this is typically close to optimal, and much cheaper to
2760 	 * compute.
2761 	 */
2762 	space_map_write(sm, condense_tree, SM_ALLOC, SM_NO_VDEVID, tx);
2763 	range_tree_vacate(condense_tree, NULL, NULL);
2764 	range_tree_destroy(condense_tree);
2765 
2766 	space_map_write(sm, msp->ms_allocatable, SM_FREE, SM_NO_VDEVID, tx);
2767 	mutex_enter(&msp->ms_lock);
2768 	msp->ms_condensing = B_FALSE;
2769 }
2770 
2771 /*
2772  * Write a metaslab to disk in the context of the specified transaction group.
2773  */
2774 void
metaslab_sync(metaslab_t * msp,uint64_t txg)2775 metaslab_sync(metaslab_t *msp, uint64_t txg)
2776 {
2777 	metaslab_group_t *mg = msp->ms_group;
2778 	vdev_t *vd = mg->mg_vd;
2779 	spa_t *spa = vd->vdev_spa;
2780 	objset_t *mos = spa_meta_objset(spa);
2781 	range_tree_t *alloctree = msp->ms_allocating[txg & TXG_MASK];
2782 	dmu_tx_t *tx;
2783 	uint64_t object = space_map_object(msp->ms_sm);
2784 
2785 	ASSERT(!vd->vdev_ishole);
2786 
2787 	/*
2788 	 * This metaslab has just been added so there's no work to do now.
2789 	 */
2790 	if (msp->ms_freeing == NULL) {
2791 		ASSERT3P(alloctree, ==, NULL);
2792 		return;
2793 	}
2794 
2795 	ASSERT3P(alloctree, !=, NULL);
2796 	ASSERT3P(msp->ms_freeing, !=, NULL);
2797 	ASSERT3P(msp->ms_freed, !=, NULL);
2798 	ASSERT3P(msp->ms_checkpointing, !=, NULL);
2799 
2800 	/*
2801 	 * Normally, we don't want to process a metaslab if there are no
2802 	 * allocations or frees to perform. However, if the metaslab is being
2803 	 * forced to condense and it's loaded, we need to let it through.
2804 	 */
2805 	if (range_tree_is_empty(alloctree) &&
2806 	    range_tree_is_empty(msp->ms_freeing) &&
2807 	    range_tree_is_empty(msp->ms_checkpointing) &&
2808 	    !(msp->ms_loaded && msp->ms_condense_wanted))
2809 		return;
2810 
2811 
2812 	VERIFY(txg <= spa_final_dirty_txg(spa));
2813 
2814 	/*
2815 	 * The only state that can actually be changing concurrently
2816 	 * with metaslab_sync() is the metaslab's ms_allocatable. No
2817 	 * other thread can be modifying this txg's alloc, freeing,
2818 	 * freed, or space_map_phys_t.  We drop ms_lock whenever we
2819 	 * could call into the DMU, because the DMU can call down to
2820 	 * us (e.g. via zio_free()) at any time.
2821 	 *
2822 	 * The spa_vdev_remove_thread() can be reading metaslab state
2823 	 * concurrently, and it is locked out by the ms_sync_lock.
2824 	 * Note that the ms_lock is insufficient for this, because it
2825 	 * is dropped by space_map_write().
2826 	 */
2827 	tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
2828 
2829 	if (msp->ms_sm == NULL) {
2830 		uint64_t new_object;
2831 
2832 		new_object = space_map_alloc(mos, zfs_metaslab_sm_blksz, tx);
2833 		VERIFY3U(new_object, !=, 0);
2834 
2835 		VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
2836 		    msp->ms_start, msp->ms_size, vd->vdev_ashift));
2837 
2838 		ASSERT(msp->ms_sm != NULL);
2839 		ASSERT0(metaslab_allocated_space(msp));
2840 	}
2841 
2842 	if (!range_tree_is_empty(msp->ms_checkpointing) &&
2843 	    vd->vdev_checkpoint_sm == NULL) {
2844 		ASSERT(spa_has_checkpoint(spa));
2845 
2846 		uint64_t new_object = space_map_alloc(mos,
2847 		    vdev_standard_sm_blksz, tx);
2848 		VERIFY3U(new_object, !=, 0);
2849 
2850 		VERIFY0(space_map_open(&vd->vdev_checkpoint_sm,
2851 		    mos, new_object, 0, vd->vdev_asize, vd->vdev_ashift));
2852 		ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
2853 
2854 		/*
2855 		 * We save the space map object as an entry in vdev_top_zap
2856 		 * so it can be retrieved when the pool is reopened after an
2857 		 * export or through zdb.
2858 		 */
2859 		VERIFY0(zap_add(vd->vdev_spa->spa_meta_objset,
2860 		    vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
2861 		    sizeof (new_object), 1, &new_object, tx));
2862 	}
2863 
2864 	mutex_enter(&msp->ms_sync_lock);
2865 	mutex_enter(&msp->ms_lock);
2866 
2867 	/*
2868 	 * Note: metaslab_condense() clears the space map's histogram.
2869 	 * Therefore we must verify and remove this histogram before
2870 	 * condensing.
2871 	 */
2872 	metaslab_group_histogram_verify(mg);
2873 	metaslab_class_histogram_verify(mg->mg_class);
2874 	metaslab_group_histogram_remove(mg, msp);
2875 
2876 	if (msp->ms_loaded && metaslab_should_condense(msp)) {
2877 		metaslab_condense(msp, txg, tx);
2878 	} else {
2879 		mutex_exit(&msp->ms_lock);
2880 		space_map_write(msp->ms_sm, alloctree, SM_ALLOC,
2881 		    SM_NO_VDEVID, tx);
2882 		space_map_write(msp->ms_sm, msp->ms_freeing, SM_FREE,
2883 		    SM_NO_VDEVID, tx);
2884 		mutex_enter(&msp->ms_lock);
2885 	}
2886 
2887 	msp->ms_allocated_space += range_tree_space(alloctree);
2888 	ASSERT3U(msp->ms_allocated_space, >=,
2889 	    range_tree_space(msp->ms_freeing));
2890 	msp->ms_allocated_space -= range_tree_space(msp->ms_freeing);
2891 
2892 	if (!range_tree_is_empty(msp->ms_checkpointing)) {
2893 		ASSERT(spa_has_checkpoint(spa));
2894 		ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
2895 
2896 		/*
2897 		 * Since we are doing writes to disk and the ms_checkpointing
2898 		 * tree won't be changing during that time, we drop the
2899 		 * ms_lock while writing to the checkpoint space map.
2900 		 */
2901 		mutex_exit(&msp->ms_lock);
2902 		space_map_write(vd->vdev_checkpoint_sm,
2903 		    msp->ms_checkpointing, SM_FREE, SM_NO_VDEVID, tx);
2904 		mutex_enter(&msp->ms_lock);
2905 
2906 		spa->spa_checkpoint_info.sci_dspace +=
2907 		    range_tree_space(msp->ms_checkpointing);
2908 		vd->vdev_stat.vs_checkpoint_space +=
2909 		    range_tree_space(msp->ms_checkpointing);
2910 		ASSERT3U(vd->vdev_stat.vs_checkpoint_space, ==,
2911 		    -space_map_allocated(vd->vdev_checkpoint_sm));
2912 
2913 		range_tree_vacate(msp->ms_checkpointing, NULL, NULL);
2914 	}
2915 
2916 	if (msp->ms_loaded) {
2917 		/*
2918 		 * When the space map is loaded, we have an accurate
2919 		 * histogram in the range tree. This gives us an opportunity
2920 		 * to bring the space map's histogram up-to-date so we clear
2921 		 * it first before updating it.
2922 		 */
2923 		space_map_histogram_clear(msp->ms_sm);
2924 		space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
2925 
2926 		/*
2927 		 * Since we've cleared the histogram we need to add back
2928 		 * any free space that has already been processed, plus
2929 		 * any deferred space. This allows the on-disk histogram
2930 		 * to accurately reflect all free space even if some space
2931 		 * is not yet available for allocation (i.e. deferred).
2932 		 */
2933 		space_map_histogram_add(msp->ms_sm, msp->ms_freed, tx);
2934 
2935 		/*
2936 		 * Add back any deferred free space that has not been
2937 		 * added back into the in-core free tree yet. This will
2938 		 * ensure that we don't end up with a space map histogram
2939 		 * that is completely empty unless the metaslab is fully
2940 		 * allocated.
2941 		 */
2942 		for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2943 			space_map_histogram_add(msp->ms_sm,
2944 			    msp->ms_defer[t], tx);
2945 		}
2946 	}
2947 
2948 	/*
2949 	 * Always add the free space from this sync pass to the space
2950 	 * map histogram. We want to make sure that the on-disk histogram
2951 	 * accounts for all free space. If the space map is not loaded,
2952 	 * then we will lose some accuracy but will correct it the next
2953 	 * time we load the space map.
2954 	 */
2955 	space_map_histogram_add(msp->ms_sm, msp->ms_freeing, tx);
2956 	metaslab_aux_histograms_update(msp);
2957 
2958 	metaslab_group_histogram_add(mg, msp);
2959 	metaslab_group_histogram_verify(mg);
2960 	metaslab_class_histogram_verify(mg->mg_class);
2961 
2962 	/*
2963 	 * For sync pass 1, we avoid traversing this txg's free range tree
2964 	 * and instead will just swap the pointers for freeing and freed.
2965 	 * We can safely do this since the freed_tree is guaranteed to be
2966 	 * empty on the initial pass.
2967 	 */
2968 	if (spa_sync_pass(spa) == 1) {
2969 		range_tree_swap(&msp->ms_freeing, &msp->ms_freed);
2970 		ASSERT0(msp->ms_allocated_this_txg);
2971 	} else {
2972 		range_tree_vacate(msp->ms_freeing,
2973 		    range_tree_add, msp->ms_freed);
2974 	}
2975 	msp->ms_allocated_this_txg += range_tree_space(alloctree);
2976 	range_tree_vacate(alloctree, NULL, NULL);
2977 
2978 	ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
2979 	ASSERT0(range_tree_space(msp->ms_allocating[TXG_CLEAN(txg)
2980 	    & TXG_MASK]));
2981 	ASSERT0(range_tree_space(msp->ms_freeing));
2982 	ASSERT0(range_tree_space(msp->ms_checkpointing));
2983 
2984 	mutex_exit(&msp->ms_lock);
2985 
2986 	if (object != space_map_object(msp->ms_sm)) {
2987 		object = space_map_object(msp->ms_sm);
2988 		dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
2989 		    msp->ms_id, sizeof (uint64_t), &object, tx);
2990 	}
2991 	mutex_exit(&msp->ms_sync_lock);
2992 	dmu_tx_commit(tx);
2993 }
2994 
2995 /*
2996  * Called after a transaction group has completely synced to mark
2997  * all of the metaslab's free space as usable.
2998  */
2999 void
metaslab_sync_done(metaslab_t * msp,uint64_t txg)3000 metaslab_sync_done(metaslab_t *msp, uint64_t txg)
3001 {
3002 	metaslab_group_t *mg = msp->ms_group;
3003 	vdev_t *vd = mg->mg_vd;
3004 	spa_t *spa = vd->vdev_spa;
3005 	range_tree_t **defer_tree;
3006 	int64_t alloc_delta, defer_delta;
3007 	boolean_t defer_allowed = B_TRUE;
3008 
3009 	ASSERT(!vd->vdev_ishole);
3010 
3011 	mutex_enter(&msp->ms_lock);
3012 
3013 	/*
3014 	 * If this metaslab is just becoming available, initialize its
3015 	 * range trees and add its capacity to the vdev.
3016 	 */
3017 	if (msp->ms_freed == NULL) {
3018 		for (int t = 0; t < TXG_SIZE; t++) {
3019 			ASSERT(msp->ms_allocating[t] == NULL);
3020 
3021 			msp->ms_allocating[t] = range_tree_create(NULL, NULL);
3022 		}
3023 
3024 		ASSERT3P(msp->ms_freeing, ==, NULL);
3025 		msp->ms_freeing = range_tree_create(NULL, NULL);
3026 
3027 		ASSERT3P(msp->ms_freed, ==, NULL);
3028 		msp->ms_freed = range_tree_create(NULL, NULL);
3029 
3030 		for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3031 			ASSERT(msp->ms_defer[t] == NULL);
3032 
3033 			msp->ms_defer[t] = range_tree_create(NULL, NULL);
3034 		}
3035 
3036 		ASSERT3P(msp->ms_checkpointing, ==, NULL);
3037 		msp->ms_checkpointing = range_tree_create(NULL, NULL);
3038 
3039 		metaslab_space_update(vd, mg->mg_class, 0, 0, msp->ms_size);
3040 	}
3041 	ASSERT0(range_tree_space(msp->ms_freeing));
3042 	ASSERT0(range_tree_space(msp->ms_checkpointing));
3043 
3044 	defer_tree = &msp->ms_defer[txg % TXG_DEFER_SIZE];
3045 
3046 	uint64_t free_space = metaslab_class_get_space(spa_normal_class(spa)) -
3047 	    metaslab_class_get_alloc(spa_normal_class(spa));
3048 	if (free_space <= spa_get_slop_space(spa) || vd->vdev_removing) {
3049 		defer_allowed = B_FALSE;
3050 	}
3051 
3052 	defer_delta = 0;
3053 	alloc_delta = msp->ms_allocated_this_txg -
3054 	    range_tree_space(msp->ms_freed);
3055 	if (defer_allowed) {
3056 		defer_delta = range_tree_space(msp->ms_freed) -
3057 		    range_tree_space(*defer_tree);
3058 	} else {
3059 		defer_delta -= range_tree_space(*defer_tree);
3060 	}
3061 
3062 	metaslab_space_update(vd, mg->mg_class, alloc_delta + defer_delta,
3063 	    defer_delta, 0);
3064 
3065 	/*
3066 	 * If there's a metaslab_load() in progress, wait for it to complete
3067 	 * so that we have a consistent view of the in-core space map.
3068 	 */
3069 	metaslab_load_wait(msp);
3070 
3071 	/*
3072 	 * Move the frees from the defer_tree back to the free
3073 	 * range tree (if it's loaded). Swap the freed_tree and
3074 	 * the defer_tree -- this is safe to do because we've
3075 	 * just emptied out the defer_tree.
3076 	 */
3077 	range_tree_vacate(*defer_tree,
3078 	    msp->ms_loaded ? range_tree_add : NULL, msp->ms_allocatable);
3079 	if (defer_allowed) {
3080 		range_tree_swap(&msp->ms_freed, defer_tree);
3081 	} else {
3082 		range_tree_vacate(msp->ms_freed,
3083 		    msp->ms_loaded ? range_tree_add : NULL,
3084 		    msp->ms_allocatable);
3085 	}
3086 
3087 	msp->ms_synced_length = space_map_length(msp->ms_sm);
3088 
3089 	msp->ms_deferspace += defer_delta;
3090 	ASSERT3S(msp->ms_deferspace, >=, 0);
3091 	ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
3092 	if (msp->ms_deferspace != 0) {
3093 		/*
3094 		 * Keep syncing this metaslab until all deferred frees
3095 		 * are back in circulation.
3096 		 */
3097 		vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
3098 	}
3099 	metaslab_aux_histograms_update_done(msp, defer_allowed);
3100 
3101 	if (msp->ms_new) {
3102 		msp->ms_new = B_FALSE;
3103 		mutex_enter(&mg->mg_lock);
3104 		mg->mg_ms_ready++;
3105 		mutex_exit(&mg->mg_lock);
3106 	}
3107 
3108 	/*
3109 	 * Re-sort metaslab within its group now that we've adjusted
3110 	 * its allocatable space.
3111 	 */
3112 	metaslab_recalculate_weight_and_sort(msp);
3113 
3114 	/*
3115 	 * If the metaslab is loaded and we've not tried to load or allocate
3116 	 * from it in 'metaslab_unload_delay' txgs, then unload it.
3117 	 */
3118 	if (msp->ms_loaded &&
3119 	    msp->ms_initializing == 0 &&
3120 	    msp->ms_selected_txg + metaslab_unload_delay < txg) {
3121 		for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
3122 			VERIFY0(range_tree_space(
3123 			    msp->ms_allocating[(txg + t) & TXG_MASK]));
3124 		}
3125 		if (msp->ms_allocator != -1) {
3126 			metaslab_passivate(msp, msp->ms_weight &
3127 			    ~METASLAB_ACTIVE_MASK);
3128 		}
3129 
3130 		if (!metaslab_debug_unload)
3131 			metaslab_unload(msp);
3132 	}
3133 
3134 	ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
3135 	ASSERT0(range_tree_space(msp->ms_freeing));
3136 	ASSERT0(range_tree_space(msp->ms_freed));
3137 	ASSERT0(range_tree_space(msp->ms_checkpointing));
3138 
3139 	msp->ms_allocated_this_txg = 0;
3140 	mutex_exit(&msp->ms_lock);
3141 }
3142 
3143 void
metaslab_sync_reassess(metaslab_group_t * mg)3144 metaslab_sync_reassess(metaslab_group_t *mg)
3145 {
3146 	spa_t *spa = mg->mg_class->mc_spa;
3147 
3148 	spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
3149 	metaslab_group_alloc_update(mg);
3150 	mg->mg_fragmentation = metaslab_group_fragmentation(mg);
3151 
3152 	/*
3153 	 * Preload the next potential metaslabs but only on active
3154 	 * metaslab groups. We can get into a state where the metaslab
3155 	 * is no longer active since we dirty metaslabs as we remove a
3156 	 * a device, thus potentially making the metaslab group eligible
3157 	 * for preloading.
3158 	 */
3159 	if (mg->mg_activation_count > 0) {
3160 		metaslab_group_preload(mg);
3161 	}
3162 	spa_config_exit(spa, SCL_ALLOC, FTAG);
3163 }
3164 
3165 /*
3166  * When writing a ditto block (i.e. more than one DVA for a given BP) on
3167  * the same vdev as an existing DVA of this BP, then try to allocate it
3168  * on a different metaslab than existing DVAs (i.e. a unique metaslab).
3169  */
3170 static boolean_t
metaslab_is_unique(metaslab_t * msp,dva_t * dva)3171 metaslab_is_unique(metaslab_t *msp, dva_t *dva)
3172 {
3173 	uint64_t dva_ms_id;
3174 
3175 	if (DVA_GET_ASIZE(dva) == 0)
3176 		return (B_TRUE);
3177 
3178 	if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
3179 		return (B_TRUE);
3180 
3181 	dva_ms_id = DVA_GET_OFFSET(dva) >> msp->ms_group->mg_vd->vdev_ms_shift;
3182 
3183 	return (msp->ms_id != dva_ms_id);
3184 }
3185 
3186 /*
3187  * ==========================================================================
3188  * Metaslab allocation tracing facility
3189  * ==========================================================================
3190  */
3191 #ifdef _METASLAB_TRACING
3192 kstat_t *metaslab_trace_ksp;
3193 kstat_named_t metaslab_trace_over_limit;
3194 
3195 void
metaslab_alloc_trace_init(void)3196 metaslab_alloc_trace_init(void)
3197 {
3198 	ASSERT(metaslab_alloc_trace_cache == NULL);
3199 	metaslab_alloc_trace_cache = kmem_cache_create(
3200 	    "metaslab_alloc_trace_cache", sizeof (metaslab_alloc_trace_t),
3201 	    0, NULL, NULL, NULL, NULL, NULL, 0);
3202 	metaslab_trace_ksp = kstat_create("zfs", 0, "metaslab_trace_stats",
3203 	    "misc", KSTAT_TYPE_NAMED, 1, KSTAT_FLAG_VIRTUAL);
3204 	if (metaslab_trace_ksp != NULL) {
3205 		metaslab_trace_ksp->ks_data = &metaslab_trace_over_limit;
3206 		kstat_named_init(&metaslab_trace_over_limit,
3207 		    "metaslab_trace_over_limit", KSTAT_DATA_UINT64);
3208 		kstat_install(metaslab_trace_ksp);
3209 	}
3210 }
3211 
3212 void
metaslab_alloc_trace_fini(void)3213 metaslab_alloc_trace_fini(void)
3214 {
3215 	if (metaslab_trace_ksp != NULL) {
3216 		kstat_delete(metaslab_trace_ksp);
3217 		metaslab_trace_ksp = NULL;
3218 	}
3219 	kmem_cache_destroy(metaslab_alloc_trace_cache);
3220 	metaslab_alloc_trace_cache = NULL;
3221 }
3222 
3223 /*
3224  * Add an allocation trace element to the allocation tracing list.
3225  */
3226 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)3227 metaslab_trace_add(zio_alloc_list_t *zal, metaslab_group_t *mg,
3228     metaslab_t *msp, uint64_t psize, uint32_t dva_id, uint64_t offset,
3229     int allocator)
3230 {
3231 	if (!metaslab_trace_enabled)
3232 		return;
3233 
3234 	/*
3235 	 * When the tracing list reaches its maximum we remove
3236 	 * the second element in the list before adding a new one.
3237 	 * By removing the second element we preserve the original
3238 	 * entry as a clue to what allocations steps have already been
3239 	 * performed.
3240 	 */
3241 	if (zal->zal_size == metaslab_trace_max_entries) {
3242 		metaslab_alloc_trace_t *mat_next;
3243 #ifdef DEBUG
3244 		panic("too many entries in allocation list");
3245 #endif
3246 		atomic_inc_64(&metaslab_trace_over_limit.value.ui64);
3247 		zal->zal_size--;
3248 		mat_next = list_next(&zal->zal_list, list_head(&zal->zal_list));
3249 		list_remove(&zal->zal_list, mat_next);
3250 		kmem_cache_free(metaslab_alloc_trace_cache, mat_next);
3251 	}
3252 
3253 	metaslab_alloc_trace_t *mat =
3254 	    kmem_cache_alloc(metaslab_alloc_trace_cache, KM_SLEEP);
3255 	list_link_init(&mat->mat_list_node);
3256 	mat->mat_mg = mg;
3257 	mat->mat_msp = msp;
3258 	mat->mat_size = psize;
3259 	mat->mat_dva_id = dva_id;
3260 	mat->mat_offset = offset;
3261 	mat->mat_weight = 0;
3262 	mat->mat_allocator = allocator;
3263 
3264 	if (msp != NULL)
3265 		mat->mat_weight = msp->ms_weight;
3266 
3267 	/*
3268 	 * The list is part of the zio so locking is not required. Only
3269 	 * a single thread will perform allocations for a given zio.
3270 	 */
3271 	list_insert_tail(&zal->zal_list, mat);
3272 	zal->zal_size++;
3273 
3274 	ASSERT3U(zal->zal_size, <=, metaslab_trace_max_entries);
3275 }
3276 
3277 void
metaslab_trace_init(zio_alloc_list_t * zal)3278 metaslab_trace_init(zio_alloc_list_t *zal)
3279 {
3280 	list_create(&zal->zal_list, sizeof (metaslab_alloc_trace_t),
3281 	    offsetof(metaslab_alloc_trace_t, mat_list_node));
3282 	zal->zal_size = 0;
3283 }
3284 
3285 void
metaslab_trace_fini(zio_alloc_list_t * zal)3286 metaslab_trace_fini(zio_alloc_list_t *zal)
3287 {
3288 	metaslab_alloc_trace_t *mat;
3289 
3290 	while ((mat = list_remove_head(&zal->zal_list)) != NULL)
3291 		kmem_cache_free(metaslab_alloc_trace_cache, mat);
3292 	list_destroy(&zal->zal_list);
3293 	zal->zal_size = 0;
3294 }
3295 
3296 #else
3297 
3298 #define	metaslab_trace_add(zal, mg, msp, psize, id, off, alloc)
3299 
3300 void
metaslab_alloc_trace_init(void)3301 metaslab_alloc_trace_init(void)
3302 {
3303 }
3304 
3305 void
metaslab_alloc_trace_fini(void)3306 metaslab_alloc_trace_fini(void)
3307 {
3308 }
3309 
3310 void
metaslab_trace_init(zio_alloc_list_t * zal)3311 metaslab_trace_init(zio_alloc_list_t *zal)
3312 {
3313 }
3314 
3315 void
metaslab_trace_fini(zio_alloc_list_t * zal)3316 metaslab_trace_fini(zio_alloc_list_t *zal)
3317 {
3318 }
3319 
3320 #endif /* _METASLAB_TRACING */
3321 
3322 /*
3323  * ==========================================================================
3324  * Metaslab block operations
3325  * ==========================================================================
3326  */
3327 
3328 static void
metaslab_group_alloc_increment(spa_t * spa,uint64_t vdev,void * tag,int flags,int allocator)3329 metaslab_group_alloc_increment(spa_t *spa, uint64_t vdev, void *tag, int flags,
3330     int allocator)
3331 {
3332 	if (!(flags & METASLAB_ASYNC_ALLOC) ||
3333 	    (flags & METASLAB_DONT_THROTTLE))
3334 		return;
3335 
3336 	metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
3337 	if (!mg->mg_class->mc_alloc_throttle_enabled)
3338 		return;
3339 
3340 	(void) zfs_refcount_add(&mg->mg_alloc_queue_depth[allocator], tag);
3341 }
3342 
3343 static void
metaslab_group_increment_qdepth(metaslab_group_t * mg,int allocator)3344 metaslab_group_increment_qdepth(metaslab_group_t *mg, int allocator)
3345 {
3346 	uint64_t max = mg->mg_max_alloc_queue_depth;
3347 	uint64_t cur = mg->mg_cur_max_alloc_queue_depth[allocator];
3348 	while (cur < max) {
3349 		if (atomic_cas_64(&mg->mg_cur_max_alloc_queue_depth[allocator],
3350 		    cur, cur + 1) == cur) {
3351 			atomic_inc_64(
3352 			    &mg->mg_class->mc_alloc_max_slots[allocator]);
3353 			return;
3354 		}
3355 		cur = mg->mg_cur_max_alloc_queue_depth[allocator];
3356 	}
3357 }
3358 
3359 void
metaslab_group_alloc_decrement(spa_t * spa,uint64_t vdev,void * tag,int flags,int allocator,boolean_t io_complete)3360 metaslab_group_alloc_decrement(spa_t *spa, uint64_t vdev, void *tag, int flags,
3361     int allocator, boolean_t io_complete)
3362 {
3363 	if (!(flags & METASLAB_ASYNC_ALLOC) ||
3364 	    (flags & METASLAB_DONT_THROTTLE))
3365 		return;
3366 
3367 	metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
3368 	if (!mg->mg_class->mc_alloc_throttle_enabled)
3369 		return;
3370 
3371 	(void) zfs_refcount_remove(&mg->mg_alloc_queue_depth[allocator], tag);
3372 	if (io_complete)
3373 		metaslab_group_increment_qdepth(mg, allocator);
3374 }
3375 
3376 void
metaslab_group_alloc_verify(spa_t * spa,const blkptr_t * bp,void * tag,int allocator)3377 metaslab_group_alloc_verify(spa_t *spa, const blkptr_t *bp, void *tag,
3378     int allocator)
3379 {
3380 #ifdef ZFS_DEBUG
3381 	const dva_t *dva = bp->blk_dva;
3382 	int ndvas = BP_GET_NDVAS(bp);
3383 
3384 	for (int d = 0; d < ndvas; d++) {
3385 		uint64_t vdev = DVA_GET_VDEV(&dva[d]);
3386 		metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
3387 		VERIFY(zfs_refcount_not_held(
3388 		    &mg->mg_alloc_queue_depth[allocator], tag));
3389 	}
3390 #endif
3391 }
3392 
3393 static uint64_t
metaslab_block_alloc(metaslab_t * msp,uint64_t size,uint64_t txg)3394 metaslab_block_alloc(metaslab_t *msp, uint64_t size, uint64_t txg)
3395 {
3396 	uint64_t start;
3397 	range_tree_t *rt = msp->ms_allocatable;
3398 	metaslab_class_t *mc = msp->ms_group->mg_class;
3399 
3400 	VERIFY(!msp->ms_condensing);
3401 	VERIFY0(msp->ms_initializing);
3402 
3403 	start = mc->mc_ops->msop_alloc(msp, size);
3404 	if (start != -1ULL) {
3405 		metaslab_group_t *mg = msp->ms_group;
3406 		vdev_t *vd = mg->mg_vd;
3407 
3408 		VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
3409 		VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
3410 		VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
3411 		range_tree_remove(rt, start, size);
3412 
3413 		if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
3414 			vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
3415 
3416 		range_tree_add(msp->ms_allocating[txg & TXG_MASK], start, size);
3417 
3418 		/* Track the last successful allocation */
3419 		msp->ms_alloc_txg = txg;
3420 		metaslab_verify_space(msp, txg);
3421 	}
3422 
3423 	/*
3424 	 * Now that we've attempted the allocation we need to update the
3425 	 * metaslab's maximum block size since it may have changed.
3426 	 */
3427 	msp->ms_max_size = metaslab_block_maxsize(msp);
3428 	return (start);
3429 }
3430 
3431 /*
3432  * Find the metaslab with the highest weight that is less than what we've
3433  * already tried.  In the common case, this means that we will examine each
3434  * metaslab at most once. Note that concurrent callers could reorder metaslabs
3435  * by activation/passivation once we have dropped the mg_lock. If a metaslab is
3436  * activated by another thread, and we fail to allocate from the metaslab we
3437  * have selected, we may not try the newly-activated metaslab, and instead
3438  * activate another metaslab.  This is not optimal, but generally does not cause
3439  * any problems (a possible exception being if every metaslab is completely full
3440  * except for the the newly-activated metaslab which we fail to examine).
3441  */
3442 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,zio_alloc_list_t * zal,metaslab_t * search,boolean_t * was_active)3443 find_valid_metaslab(metaslab_group_t *mg, uint64_t activation_weight,
3444     dva_t *dva, int d, boolean_t want_unique, uint64_t asize, int allocator,
3445     zio_alloc_list_t *zal, metaslab_t *search, boolean_t *was_active)
3446 {
3447 	avl_index_t idx;
3448 	avl_tree_t *t = &mg->mg_metaslab_tree;
3449 	metaslab_t *msp = avl_find(t, search, &idx);
3450 	if (msp == NULL)
3451 		msp = avl_nearest(t, idx, AVL_AFTER);
3452 
3453 	for (; msp != NULL; msp = AVL_NEXT(t, msp)) {
3454 		int i;
3455 		if (!metaslab_should_allocate(msp, asize)) {
3456 			metaslab_trace_add(zal, mg, msp, asize, d,
3457 			    TRACE_TOO_SMALL, allocator);
3458 			continue;
3459 		}
3460 
3461 		/*
3462 		 * If the selected metaslab is condensing or being
3463 		 * initialized, skip it.
3464 		 */
3465 		if (msp->ms_condensing || msp->ms_initializing > 0)
3466 			continue;
3467 
3468 		*was_active = msp->ms_allocator != -1;
3469 		/*
3470 		 * If we're activating as primary, this is our first allocation
3471 		 * from this disk, so we don't need to check how close we are.
3472 		 * If the metaslab under consideration was already active,
3473 		 * we're getting desperate enough to steal another allocator's
3474 		 * metaslab, so we still don't care about distances.
3475 		 */
3476 		if (activation_weight == METASLAB_WEIGHT_PRIMARY || *was_active)
3477 			break;
3478 
3479 		for (i = 0; i < d; i++) {
3480 			if (want_unique &&
3481 			    !metaslab_is_unique(msp, &dva[i]))
3482 				break;  /* try another metaslab */
3483 		}
3484 		if (i == d)
3485 			break;
3486 	}
3487 
3488 	if (msp != NULL) {
3489 		search->ms_weight = msp->ms_weight;
3490 		search->ms_start = msp->ms_start + 1;
3491 		search->ms_allocator = msp->ms_allocator;
3492 		search->ms_primary = msp->ms_primary;
3493 	}
3494 	return (msp);
3495 }
3496 
3497 /* ARGSUSED */
3498 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)3499 metaslab_group_alloc_normal(metaslab_group_t *mg, zio_alloc_list_t *zal,
3500     uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva,
3501     int d, int allocator)
3502 {
3503 	metaslab_t *msp = NULL;
3504 	uint64_t offset = -1ULL;
3505 	uint64_t activation_weight;
3506 
3507 	activation_weight = METASLAB_WEIGHT_PRIMARY;
3508 	for (int i = 0; i < d; i++) {
3509 		if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
3510 		    DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
3511 			activation_weight = METASLAB_WEIGHT_SECONDARY;
3512 		} else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
3513 		    DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
3514 			activation_weight = METASLAB_WEIGHT_CLAIM;
3515 			break;
3516 		}
3517 	}
3518 
3519 	/*
3520 	 * If we don't have enough metaslabs active to fill the entire array, we
3521 	 * just use the 0th slot.
3522 	 */
3523 	if (mg->mg_ms_ready < mg->mg_allocators * 3)
3524 		allocator = 0;
3525 
3526 	ASSERT3U(mg->mg_vd->vdev_ms_count, >=, 2);
3527 
3528 	metaslab_t *search = kmem_alloc(sizeof (*search), KM_SLEEP);
3529 	search->ms_weight = UINT64_MAX;
3530 	search->ms_start = 0;
3531 	/*
3532 	 * At the end of the metaslab tree are the already-active metaslabs,
3533 	 * first the primaries, then the secondaries. When we resume searching
3534 	 * through the tree, we need to consider ms_allocator and ms_primary so
3535 	 * we start in the location right after where we left off, and don't
3536 	 * accidentally loop forever considering the same metaslabs.
3537 	 */
3538 	search->ms_allocator = -1;
3539 	search->ms_primary = B_TRUE;
3540 	for (;;) {
3541 		boolean_t was_active = B_FALSE;
3542 
3543 		mutex_enter(&mg->mg_lock);
3544 
3545 		if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
3546 		    mg->mg_primaries[allocator] != NULL) {
3547 			msp = mg->mg_primaries[allocator];
3548 			was_active = B_TRUE;
3549 		} else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
3550 		    mg->mg_secondaries[allocator] != NULL) {
3551 			msp = mg->mg_secondaries[allocator];
3552 			was_active = B_TRUE;
3553 		} else {
3554 			msp = find_valid_metaslab(mg, activation_weight, dva, d,
3555 			    want_unique, asize, allocator, zal, search,
3556 			    &was_active);
3557 		}
3558 
3559 		mutex_exit(&mg->mg_lock);
3560 		if (msp == NULL) {
3561 			kmem_free(search, sizeof (*search));
3562 			return (-1ULL);
3563 		}
3564 
3565 		mutex_enter(&msp->ms_lock);
3566 		/*
3567 		 * Ensure that the metaslab we have selected is still
3568 		 * capable of handling our request. It's possible that
3569 		 * another thread may have changed the weight while we
3570 		 * were blocked on the metaslab lock. We check the
3571 		 * active status first to see if we need to reselect
3572 		 * a new metaslab.
3573 		 */
3574 		if (was_active && !(msp->ms_weight & METASLAB_ACTIVE_MASK)) {
3575 			mutex_exit(&msp->ms_lock);
3576 			continue;
3577 		}
3578 
3579 		/*
3580 		 * If the metaslab is freshly activated for an allocator that
3581 		 * isn't the one we're allocating from, or if it's a primary and
3582 		 * we're seeking a secondary (or vice versa), we go back and
3583 		 * select a new metaslab.
3584 		 */
3585 		if (!was_active && (msp->ms_weight & METASLAB_ACTIVE_MASK) &&
3586 		    (msp->ms_allocator != -1) &&
3587 		    (msp->ms_allocator != allocator || ((activation_weight ==
3588 		    METASLAB_WEIGHT_PRIMARY) != msp->ms_primary))) {
3589 			mutex_exit(&msp->ms_lock);
3590 			continue;
3591 		}
3592 
3593 		if (msp->ms_weight & METASLAB_WEIGHT_CLAIM &&
3594 		    activation_weight != METASLAB_WEIGHT_CLAIM) {
3595 			metaslab_passivate(msp, msp->ms_weight &
3596 			    ~METASLAB_WEIGHT_CLAIM);
3597 			mutex_exit(&msp->ms_lock);
3598 			continue;
3599 		}
3600 
3601 		if (metaslab_activate(msp, allocator, activation_weight) != 0) {
3602 			mutex_exit(&msp->ms_lock);
3603 			continue;
3604 		}
3605 
3606 		msp->ms_selected_txg = txg;
3607 
3608 		/*
3609 		 * Now that we have the lock, recheck to see if we should
3610 		 * continue to use this metaslab for this allocation. The
3611 		 * the metaslab is now loaded so metaslab_should_allocate() can
3612 		 * accurately determine if the allocation attempt should
3613 		 * proceed.
3614 		 */
3615 		if (!metaslab_should_allocate(msp, asize)) {
3616 			/* Passivate this metaslab and select a new one. */
3617 			metaslab_trace_add(zal, mg, msp, asize, d,
3618 			    TRACE_TOO_SMALL, allocator);
3619 			goto next;
3620 		}
3621 
3622 		/*
3623 		 * If this metaslab is currently condensing then pick again as
3624 		 * we can't manipulate this metaslab until it's committed
3625 		 * to disk. If this metaslab is being initialized, we shouldn't
3626 		 * allocate from it since the allocated region might be
3627 		 * overwritten after allocation.
3628 		 */
3629 		if (msp->ms_condensing) {
3630 			metaslab_trace_add(zal, mg, msp, asize, d,
3631 			    TRACE_CONDENSING, allocator);
3632 			metaslab_passivate(msp, msp->ms_weight &
3633 			    ~METASLAB_ACTIVE_MASK);
3634 			mutex_exit(&msp->ms_lock);
3635 			continue;
3636 		} else if (msp->ms_initializing > 0) {
3637 			metaslab_trace_add(zal, mg, msp, asize, d,
3638 			    TRACE_INITIALIZING, allocator);
3639 			metaslab_passivate(msp, msp->ms_weight &
3640 			    ~METASLAB_ACTIVE_MASK);
3641 			mutex_exit(&msp->ms_lock);
3642 			continue;
3643 		}
3644 
3645 		offset = metaslab_block_alloc(msp, asize, txg);
3646 		metaslab_trace_add(zal, mg, msp, asize, d, offset, allocator);
3647 
3648 		if (offset != -1ULL) {
3649 			/* Proactively passivate the metaslab, if needed */
3650 			metaslab_segment_may_passivate(msp);
3651 			break;
3652 		}
3653 next:
3654 		ASSERT(msp->ms_loaded);
3655 
3656 		/*
3657 		 * We were unable to allocate from this metaslab so determine
3658 		 * a new weight for this metaslab. Now that we have loaded
3659 		 * the metaslab we can provide a better hint to the metaslab
3660 		 * selector.
3661 		 *
3662 		 * For space-based metaslabs, we use the maximum block size.
3663 		 * This information is only available when the metaslab
3664 		 * is loaded and is more accurate than the generic free
3665 		 * space weight that was calculated by metaslab_weight().
3666 		 * This information allows us to quickly compare the maximum
3667 		 * available allocation in the metaslab to the allocation
3668 		 * size being requested.
3669 		 *
3670 		 * For segment-based metaslabs, determine the new weight
3671 		 * based on the highest bucket in the range tree. We
3672 		 * explicitly use the loaded segment weight (i.e. the range
3673 		 * tree histogram) since it contains the space that is
3674 		 * currently available for allocation and is accurate
3675 		 * even within a sync pass.
3676 		 */
3677 		if (WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
3678 			uint64_t weight = metaslab_block_maxsize(msp);
3679 			WEIGHT_SET_SPACEBASED(weight);
3680 			metaslab_passivate(msp, weight);
3681 		} else {
3682 			metaslab_passivate(msp,
3683 			    metaslab_weight_from_range_tree(msp));
3684 		}
3685 
3686 		/*
3687 		 * We have just failed an allocation attempt, check
3688 		 * that metaslab_should_allocate() agrees. Otherwise,
3689 		 * we may end up in an infinite loop retrying the same
3690 		 * metaslab.
3691 		 */
3692 		ASSERT(!metaslab_should_allocate(msp, asize));
3693 
3694 		mutex_exit(&msp->ms_lock);
3695 	}
3696 	mutex_exit(&msp->ms_lock);
3697 	kmem_free(search, sizeof (*search));
3698 	return (offset);
3699 }
3700 
3701 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)3702 metaslab_group_alloc(metaslab_group_t *mg, zio_alloc_list_t *zal,
3703     uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva,
3704     int d, int allocator)
3705 {
3706 	uint64_t offset;
3707 	ASSERT(mg->mg_initialized);
3708 
3709 	offset = metaslab_group_alloc_normal(mg, zal, asize, txg, want_unique,
3710 	    dva, d, allocator);
3711 
3712 	mutex_enter(&mg->mg_lock);
3713 	if (offset == -1ULL) {
3714 		mg->mg_failed_allocations++;
3715 		metaslab_trace_add(zal, mg, NULL, asize, d,
3716 		    TRACE_GROUP_FAILURE, allocator);
3717 		if (asize == SPA_GANGBLOCKSIZE) {
3718 			/*
3719 			 * This metaslab group was unable to allocate
3720 			 * the minimum gang block size so it must be out of
3721 			 * space. We must notify the allocation throttle
3722 			 * to start skipping allocation attempts to this
3723 			 * metaslab group until more space becomes available.
3724 			 * Note: this failure cannot be caused by the
3725 			 * allocation throttle since the allocation throttle
3726 			 * is only responsible for skipping devices and
3727 			 * not failing block allocations.
3728 			 */
3729 			mg->mg_no_free_space = B_TRUE;
3730 		}
3731 	}
3732 	mg->mg_allocations++;
3733 	mutex_exit(&mg->mg_lock);
3734 	return (offset);
3735 }
3736 
3737 /*
3738  * Allocate a block for the specified i/o.
3739  */
3740 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)3741 metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
3742     dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags,
3743     zio_alloc_list_t *zal, int allocator)
3744 {
3745 	metaslab_group_t *mg, *rotor;
3746 	vdev_t *vd;
3747 	boolean_t try_hard = B_FALSE;
3748 
3749 	ASSERT(!DVA_IS_VALID(&dva[d]));
3750 
3751 	/*
3752 	 * For testing, make some blocks above a certain size be gang blocks.
3753 	 * This will also test spilling from special to normal.
3754 	 */
3755 	if (psize >= metaslab_force_ganging && (ddi_get_lbolt() & 3) == 0) {
3756 		metaslab_trace_add(zal, NULL, NULL, psize, d, TRACE_FORCE_GANG,
3757 		    allocator);
3758 		return (SET_ERROR(ENOSPC));
3759 	}
3760 
3761 	/*
3762 	 * Start at the rotor and loop through all mgs until we find something.
3763 	 * Note that there's no locking on mc_rotor or mc_aliquot because
3764 	 * nothing actually breaks if we miss a few updates -- we just won't
3765 	 * allocate quite as evenly.  It all balances out over time.
3766 	 *
3767 	 * If we are doing ditto or log blocks, try to spread them across
3768 	 * consecutive vdevs.  If we're forced to reuse a vdev before we've
3769 	 * allocated all of our ditto blocks, then try and spread them out on
3770 	 * that vdev as much as possible.  If it turns out to not be possible,
3771 	 * gradually lower our standards until anything becomes acceptable.
3772 	 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
3773 	 * gives us hope of containing our fault domains to something we're
3774 	 * able to reason about.  Otherwise, any two top-level vdev failures
3775 	 * will guarantee the loss of data.  With consecutive allocation,
3776 	 * only two adjacent top-level vdev failures will result in data loss.
3777 	 *
3778 	 * If we are doing gang blocks (hintdva is non-NULL), try to keep
3779 	 * ourselves on the same vdev as our gang block header.  That
3780 	 * way, we can hope for locality in vdev_cache, plus it makes our
3781 	 * fault domains something tractable.
3782 	 */
3783 	if (hintdva) {
3784 		vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
3785 
3786 		/*
3787 		 * It's possible the vdev we're using as the hint no
3788 		 * longer exists or its mg has been closed (e.g. by
3789 		 * device removal).  Consult the rotor when
3790 		 * all else fails.
3791 		 */
3792 		if (vd != NULL && vd->vdev_mg != NULL) {
3793 			mg = vd->vdev_mg;
3794 
3795 			if (flags & METASLAB_HINTBP_AVOID &&
3796 			    mg->mg_next != NULL)
3797 				mg = mg->mg_next;
3798 		} else {
3799 			mg = mc->mc_rotor;
3800 		}
3801 	} else if (d != 0) {
3802 		vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
3803 		mg = vd->vdev_mg->mg_next;
3804 	} else {
3805 		ASSERT(mc->mc_rotor != NULL);
3806 		mg = mc->mc_rotor;
3807 	}
3808 
3809 	/*
3810 	 * If the hint put us into the wrong metaslab class, or into a
3811 	 * metaslab group that has been passivated, just follow the rotor.
3812 	 */
3813 	if (mg->mg_class != mc || mg->mg_activation_count <= 0)
3814 		mg = mc->mc_rotor;
3815 
3816 	rotor = mg;
3817 top:
3818 	do {
3819 		boolean_t allocatable;
3820 
3821 		ASSERT(mg->mg_activation_count == 1);
3822 		vd = mg->mg_vd;
3823 
3824 		/*
3825 		 * Don't allocate from faulted devices.
3826 		 */
3827 		if (try_hard) {
3828 			spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
3829 			allocatable = vdev_allocatable(vd);
3830 			spa_config_exit(spa, SCL_ZIO, FTAG);
3831 		} else {
3832 			allocatable = vdev_allocatable(vd);
3833 		}
3834 
3835 		/*
3836 		 * Determine if the selected metaslab group is eligible
3837 		 * for allocations. If we're ganging then don't allow
3838 		 * this metaslab group to skip allocations since that would
3839 		 * inadvertently return ENOSPC and suspend the pool
3840 		 * even though space is still available.
3841 		 */
3842 		if (allocatable && !GANG_ALLOCATION(flags) && !try_hard) {
3843 			allocatable = metaslab_group_allocatable(mg, rotor,
3844 			    psize, allocator, d);
3845 		}
3846 
3847 		if (!allocatable) {
3848 			metaslab_trace_add(zal, mg, NULL, psize, d,
3849 			    TRACE_NOT_ALLOCATABLE, allocator);
3850 			goto next;
3851 		}
3852 
3853 		ASSERT(mg->mg_initialized);
3854 
3855 		/*
3856 		 * Avoid writing single-copy data to a failing,
3857 		 * non-redundant vdev, unless we've already tried all
3858 		 * other vdevs.
3859 		 */
3860 		if ((vd->vdev_stat.vs_write_errors > 0 ||
3861 		    vd->vdev_state < VDEV_STATE_HEALTHY) &&
3862 		    d == 0 && !try_hard && vd->vdev_children == 0) {
3863 			metaslab_trace_add(zal, mg, NULL, psize, d,
3864 			    TRACE_VDEV_ERROR, allocator);
3865 			goto next;
3866 		}
3867 
3868 		ASSERT(mg->mg_class == mc);
3869 
3870 		uint64_t asize = vdev_psize_to_asize(vd, psize);
3871 		ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
3872 
3873 		/*
3874 		 * If we don't need to try hard, then require that the
3875 		 * block be on an different metaslab from any other DVAs
3876 		 * in this BP (unique=true).  If we are trying hard, then
3877 		 * allow any metaslab to be used (unique=false).
3878 		 */
3879 		uint64_t offset = metaslab_group_alloc(mg, zal, asize, txg,
3880 		    !try_hard, dva, d, allocator);
3881 
3882 		if (offset != -1ULL) {
3883 			/*
3884 			 * If we've just selected this metaslab group,
3885 			 * figure out whether the corresponding vdev is
3886 			 * over- or under-used relative to the pool,
3887 			 * and set an allocation bias to even it out.
3888 			 */
3889 			if (mc->mc_aliquot == 0 && metaslab_bias_enabled) {
3890 				vdev_stat_t *vs = &vd->vdev_stat;
3891 				int64_t vu, cu;
3892 
3893 				vu = (vs->vs_alloc * 100) / (vs->vs_space + 1);
3894 				cu = (mc->mc_alloc * 100) / (mc->mc_space + 1);
3895 
3896 				/*
3897 				 * Calculate how much more or less we should
3898 				 * try to allocate from this device during
3899 				 * this iteration around the rotor.
3900 				 * For example, if a device is 80% full
3901 				 * and the pool is 20% full then we should
3902 				 * reduce allocations by 60% on this device.
3903 				 *
3904 				 * mg_bias = (20 - 80) * 512K / 100 = -307K
3905 				 *
3906 				 * This reduces allocations by 307K for this
3907 				 * iteration.
3908 				 */
3909 				mg->mg_bias = ((cu - vu) *
3910 				    (int64_t)mg->mg_aliquot) / 100;
3911 			} else if (!metaslab_bias_enabled) {
3912 				mg->mg_bias = 0;
3913 			}
3914 
3915 			if (atomic_add_64_nv(&mc->mc_aliquot, asize) >=
3916 			    mg->mg_aliquot + mg->mg_bias) {
3917 				mc->mc_rotor = mg->mg_next;
3918 				mc->mc_aliquot = 0;
3919 			}
3920 
3921 			DVA_SET_VDEV(&dva[d], vd->vdev_id);
3922 			DVA_SET_OFFSET(&dva[d], offset);
3923 			DVA_SET_GANG(&dva[d], !!(flags & METASLAB_GANG_HEADER));
3924 			DVA_SET_ASIZE(&dva[d], asize);
3925 
3926 			return (0);
3927 		}
3928 next:
3929 		mc->mc_rotor = mg->mg_next;
3930 		mc->mc_aliquot = 0;
3931 	} while ((mg = mg->mg_next) != rotor);
3932 
3933 	/*
3934 	 * If we haven't tried hard, do so now.
3935 	 */
3936 	if (!try_hard) {
3937 		try_hard = B_TRUE;
3938 		goto top;
3939 	}
3940 
3941 	bzero(&dva[d], sizeof (dva_t));
3942 
3943 	metaslab_trace_add(zal, rotor, NULL, psize, d, TRACE_ENOSPC, allocator);
3944 	return (SET_ERROR(ENOSPC));
3945 }
3946 
3947 void
metaslab_free_concrete(vdev_t * vd,uint64_t offset,uint64_t asize,boolean_t checkpoint)3948 metaslab_free_concrete(vdev_t *vd, uint64_t offset, uint64_t asize,
3949     boolean_t checkpoint)
3950 {
3951 	metaslab_t *msp;
3952 	spa_t *spa = vd->vdev_spa;
3953 
3954 	ASSERT(vdev_is_concrete(vd));
3955 	ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
3956 	ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
3957 
3958 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3959 
3960 	VERIFY(!msp->ms_condensing);
3961 	VERIFY3U(offset, >=, msp->ms_start);
3962 	VERIFY3U(offset + asize, <=, msp->ms_start + msp->ms_size);
3963 	VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
3964 	VERIFY0(P2PHASE(asize, 1ULL << vd->vdev_ashift));
3965 
3966 	metaslab_check_free_impl(vd, offset, asize);
3967 
3968 	mutex_enter(&msp->ms_lock);
3969 	if (range_tree_is_empty(msp->ms_freeing) &&
3970 	    range_tree_is_empty(msp->ms_checkpointing)) {
3971 		vdev_dirty(vd, VDD_METASLAB, msp, spa_syncing_txg(spa));
3972 	}
3973 
3974 	if (checkpoint) {
3975 		ASSERT(spa_has_checkpoint(spa));
3976 		range_tree_add(msp->ms_checkpointing, offset, asize);
3977 	} else {
3978 		range_tree_add(msp->ms_freeing, offset, asize);
3979 	}
3980 	mutex_exit(&msp->ms_lock);
3981 }
3982 
3983 /* ARGSUSED */
3984 void
metaslab_free_impl_cb(uint64_t inner_offset,vdev_t * vd,uint64_t offset,uint64_t size,void * arg)3985 metaslab_free_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
3986     uint64_t size, void *arg)
3987 {
3988 	boolean_t *checkpoint = arg;
3989 
3990 	ASSERT3P(checkpoint, !=, NULL);
3991 
3992 	if (vd->vdev_ops->vdev_op_remap != NULL)
3993 		vdev_indirect_mark_obsolete(vd, offset, size);
3994 	else
3995 		metaslab_free_impl(vd, offset, size, *checkpoint);
3996 }
3997 
3998 static void
metaslab_free_impl(vdev_t * vd,uint64_t offset,uint64_t size,boolean_t checkpoint)3999 metaslab_free_impl(vdev_t *vd, uint64_t offset, uint64_t size,
4000     boolean_t checkpoint)
4001 {
4002 	spa_t *spa = vd->vdev_spa;
4003 
4004 	ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
4005 
4006 	if (spa_syncing_txg(spa) > spa_freeze_txg(spa))
4007 		return;
4008 
4009 	if (spa->spa_vdev_removal != NULL &&
4010 	    spa->spa_vdev_removal->svr_vdev_id == vd->vdev_id &&
4011 	    vdev_is_concrete(vd)) {
4012 		/*
4013 		 * Note: we check if the vdev is concrete because when
4014 		 * we complete the removal, we first change the vdev to be
4015 		 * an indirect vdev (in open context), and then (in syncing
4016 		 * context) clear spa_vdev_removal.
4017 		 */
4018 		free_from_removing_vdev(vd, offset, size);
4019 	} else if (vd->vdev_ops->vdev_op_remap != NULL) {
4020 		vdev_indirect_mark_obsolete(vd, offset, size);
4021 		vd->vdev_ops->vdev_op_remap(vd, offset, size,
4022 		    metaslab_free_impl_cb, &checkpoint);
4023 	} else {
4024 		metaslab_free_concrete(vd, offset, size, checkpoint);
4025 	}
4026 }
4027 
4028 typedef struct remap_blkptr_cb_arg {
4029 	blkptr_t *rbca_bp;
4030 	spa_remap_cb_t rbca_cb;
4031 	vdev_t *rbca_remap_vd;
4032 	uint64_t rbca_remap_offset;
4033 	void *rbca_cb_arg;
4034 } remap_blkptr_cb_arg_t;
4035 
4036 void
remap_blkptr_cb(uint64_t inner_offset,vdev_t * vd,uint64_t offset,uint64_t size,void * arg)4037 remap_blkptr_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
4038     uint64_t size, void *arg)
4039 {
4040 	remap_blkptr_cb_arg_t *rbca = arg;
4041 	blkptr_t *bp = rbca->rbca_bp;
4042 
4043 	/* We can not remap split blocks. */
4044 	if (size != DVA_GET_ASIZE(&bp->blk_dva[0]))
4045 		return;
4046 	ASSERT0(inner_offset);
4047 
4048 	if (rbca->rbca_cb != NULL) {
4049 		/*
4050 		 * At this point we know that we are not handling split
4051 		 * blocks and we invoke the callback on the previous
4052 		 * vdev which must be indirect.
4053 		 */
4054 		ASSERT3P(rbca->rbca_remap_vd->vdev_ops, ==, &vdev_indirect_ops);
4055 
4056 		rbca->rbca_cb(rbca->rbca_remap_vd->vdev_id,
4057 		    rbca->rbca_remap_offset, size, rbca->rbca_cb_arg);
4058 
4059 		/* set up remap_blkptr_cb_arg for the next call */
4060 		rbca->rbca_remap_vd = vd;
4061 		rbca->rbca_remap_offset = offset;
4062 	}
4063 
4064 	/*
4065 	 * The phys birth time is that of dva[0].  This ensures that we know
4066 	 * when each dva was written, so that resilver can determine which
4067 	 * blocks need to be scrubbed (i.e. those written during the time
4068 	 * the vdev was offline).  It also ensures that the key used in
4069 	 * the ARC hash table is unique (i.e. dva[0] + phys_birth).  If
4070 	 * we didn't change the phys_birth, a lookup in the ARC for a
4071 	 * remapped BP could find the data that was previously stored at
4072 	 * this vdev + offset.
4073 	 */
4074 	vdev_t *oldvd = vdev_lookup_top(vd->vdev_spa,
4075 	    DVA_GET_VDEV(&bp->blk_dva[0]));
4076 	vdev_indirect_births_t *vib = oldvd->vdev_indirect_births;
4077 	bp->blk_phys_birth = vdev_indirect_births_physbirth(vib,
4078 	    DVA_GET_OFFSET(&bp->blk_dva[0]), DVA_GET_ASIZE(&bp->blk_dva[0]));
4079 
4080 	DVA_SET_VDEV(&bp->blk_dva[0], vd->vdev_id);
4081 	DVA_SET_OFFSET(&bp->blk_dva[0], offset);
4082 }
4083 
4084 /*
4085  * If the block pointer contains any indirect DVAs, modify them to refer to
4086  * concrete DVAs.  Note that this will sometimes not be possible, leaving
4087  * the indirect DVA in place.  This happens if the indirect DVA spans multiple
4088  * segments in the mapping (i.e. it is a "split block").
4089  *
4090  * If the BP was remapped, calls the callback on the original dva (note the
4091  * callback can be called multiple times if the original indirect DVA refers
4092  * to another indirect DVA, etc).
4093  *
4094  * Returns TRUE if the BP was remapped.
4095  */
4096 boolean_t
spa_remap_blkptr(spa_t * spa,blkptr_t * bp,spa_remap_cb_t callback,void * arg)4097 spa_remap_blkptr(spa_t *spa, blkptr_t *bp, spa_remap_cb_t callback, void *arg)
4098 {
4099 	remap_blkptr_cb_arg_t rbca;
4100 
4101 	if (!zfs_remap_blkptr_enable)
4102 		return (B_FALSE);
4103 
4104 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS))
4105 		return (B_FALSE);
4106 
4107 	/*
4108 	 * Dedup BP's can not be remapped, because ddt_phys_select() depends
4109 	 * on DVA[0] being the same in the BP as in the DDT (dedup table).
4110 	 */
4111 	if (BP_GET_DEDUP(bp))
4112 		return (B_FALSE);
4113 
4114 	/*
4115 	 * Gang blocks can not be remapped, because
4116 	 * zio_checksum_gang_verifier() depends on the DVA[0] that's in
4117 	 * the BP used to read the gang block header (GBH) being the same
4118 	 * as the DVA[0] that we allocated for the GBH.
4119 	 */
4120 	if (BP_IS_GANG(bp))
4121 		return (B_FALSE);
4122 
4123 	/*
4124 	 * Embedded BP's have no DVA to remap.
4125 	 */
4126 	if (BP_GET_NDVAS(bp) < 1)
4127 		return (B_FALSE);
4128 
4129 	/*
4130 	 * Note: we only remap dva[0].  If we remapped other dvas, we
4131 	 * would no longer know what their phys birth txg is.
4132 	 */
4133 	dva_t *dva = &bp->blk_dva[0];
4134 
4135 	uint64_t offset = DVA_GET_OFFSET(dva);
4136 	uint64_t size = DVA_GET_ASIZE(dva);
4137 	vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
4138 
4139 	if (vd->vdev_ops->vdev_op_remap == NULL)
4140 		return (B_FALSE);
4141 
4142 	rbca.rbca_bp = bp;
4143 	rbca.rbca_cb = callback;
4144 	rbca.rbca_remap_vd = vd;
4145 	rbca.rbca_remap_offset = offset;
4146 	rbca.rbca_cb_arg = arg;
4147 
4148 	/*
4149 	 * remap_blkptr_cb() will be called in order for each level of
4150 	 * indirection, until a concrete vdev is reached or a split block is
4151 	 * encountered. old_vd and old_offset are updated within the callback
4152 	 * as we go from the one indirect vdev to the next one (either concrete
4153 	 * or indirect again) in that order.
4154 	 */
4155 	vd->vdev_ops->vdev_op_remap(vd, offset, size, remap_blkptr_cb, &rbca);
4156 
4157 	/* Check if the DVA wasn't remapped because it is a split block */
4158 	if (DVA_GET_VDEV(&rbca.rbca_bp->blk_dva[0]) == vd->vdev_id)
4159 		return (B_FALSE);
4160 
4161 	return (B_TRUE);
4162 }
4163 
4164 /*
4165  * Undo the allocation of a DVA which happened in the given transaction group.
4166  */
4167 void
metaslab_unalloc_dva(spa_t * spa,const dva_t * dva,uint64_t txg)4168 metaslab_unalloc_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
4169 {
4170 	metaslab_t *msp;
4171 	vdev_t *vd;
4172 	uint64_t vdev = DVA_GET_VDEV(dva);
4173 	uint64_t offset = DVA_GET_OFFSET(dva);
4174 	uint64_t size = DVA_GET_ASIZE(dva);
4175 
4176 	ASSERT(DVA_IS_VALID(dva));
4177 	ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
4178 
4179 	if (txg > spa_freeze_txg(spa))
4180 		return;
4181 
4182 	if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
4183 	    (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
4184 		cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
4185 		    (u_longlong_t)vdev, (u_longlong_t)offset);
4186 		ASSERT(0);
4187 		return;
4188 	}
4189 
4190 	ASSERT(!vd->vdev_removing);
4191 	ASSERT(vdev_is_concrete(vd));
4192 	ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
4193 	ASSERT3P(vd->vdev_indirect_mapping, ==, NULL);
4194 
4195 	if (DVA_GET_GANG(dva))
4196 		size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
4197 
4198 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
4199 
4200 	mutex_enter(&msp->ms_lock);
4201 	range_tree_remove(msp->ms_allocating[txg & TXG_MASK],
4202 	    offset, size);
4203 
4204 	VERIFY(!msp->ms_condensing);
4205 	VERIFY3U(offset, >=, msp->ms_start);
4206 	VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
4207 	VERIFY3U(range_tree_space(msp->ms_allocatable) + size, <=,
4208 	    msp->ms_size);
4209 	VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
4210 	VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
4211 	range_tree_add(msp->ms_allocatable, offset, size);
4212 	mutex_exit(&msp->ms_lock);
4213 }
4214 
4215 /*
4216  * Free the block represented by the given DVA.
4217  */
4218 void
metaslab_free_dva(spa_t * spa,const dva_t * dva,boolean_t checkpoint)4219 metaslab_free_dva(spa_t *spa, const dva_t *dva, boolean_t checkpoint)
4220 {
4221 	uint64_t vdev = DVA_GET_VDEV(dva);
4222 	uint64_t offset = DVA_GET_OFFSET(dva);
4223 	uint64_t size = DVA_GET_ASIZE(dva);
4224 	vdev_t *vd = vdev_lookup_top(spa, vdev);
4225 
4226 	ASSERT(DVA_IS_VALID(dva));
4227 	ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
4228 
4229 	if (DVA_GET_GANG(dva)) {
4230 		size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
4231 	}
4232 
4233 	metaslab_free_impl(vd, offset, size, checkpoint);
4234 }
4235 
4236 /*
4237  * Reserve some allocation slots. The reservation system must be called
4238  * before we call into the allocator. If there aren't any available slots
4239  * then the I/O will be throttled until an I/O completes and its slots are
4240  * freed up. The function returns true if it was successful in placing
4241  * the reservation.
4242  */
4243 boolean_t
metaslab_class_throttle_reserve(metaslab_class_t * mc,int slots,int allocator,zio_t * zio,int flags)4244 metaslab_class_throttle_reserve(metaslab_class_t *mc, int slots, int allocator,
4245     zio_t *zio, int flags)
4246 {
4247 	uint64_t available_slots = 0;
4248 	boolean_t slot_reserved = B_FALSE;
4249 	uint64_t max = mc->mc_alloc_max_slots[allocator];
4250 
4251 	ASSERT(mc->mc_alloc_throttle_enabled);
4252 	mutex_enter(&mc->mc_lock);
4253 
4254 	uint64_t reserved_slots =
4255 	    zfs_refcount_count(&mc->mc_alloc_slots[allocator]);
4256 	if (reserved_slots < max)
4257 		available_slots = max - reserved_slots;
4258 
4259 	if (slots <= available_slots || GANG_ALLOCATION(flags) ||
4260 	    flags & METASLAB_MUST_RESERVE) {
4261 		/*
4262 		 * We reserve the slots individually so that we can unreserve
4263 		 * them individually when an I/O completes.
4264 		 */
4265 		for (int d = 0; d < slots; d++) {
4266 			reserved_slots =
4267 			    zfs_refcount_add(&mc->mc_alloc_slots[allocator],
4268 			    zio);
4269 		}
4270 		zio->io_flags |= ZIO_FLAG_IO_ALLOCATING;
4271 		slot_reserved = B_TRUE;
4272 	}
4273 
4274 	mutex_exit(&mc->mc_lock);
4275 	return (slot_reserved);
4276 }
4277 
4278 void
metaslab_class_throttle_unreserve(metaslab_class_t * mc,int slots,int allocator,zio_t * zio)4279 metaslab_class_throttle_unreserve(metaslab_class_t *mc, int slots,
4280     int allocator, zio_t *zio)
4281 {
4282 	ASSERT(mc->mc_alloc_throttle_enabled);
4283 	mutex_enter(&mc->mc_lock);
4284 	for (int d = 0; d < slots; d++) {
4285 		(void) zfs_refcount_remove(&mc->mc_alloc_slots[allocator],
4286 		    zio);
4287 	}
4288 	mutex_exit(&mc->mc_lock);
4289 }
4290 
4291 static int
metaslab_claim_concrete(vdev_t * vd,uint64_t offset,uint64_t size,uint64_t txg)4292 metaslab_claim_concrete(vdev_t *vd, uint64_t offset, uint64_t size,
4293     uint64_t txg)
4294 {
4295 	metaslab_t *msp;
4296 	spa_t *spa = vd->vdev_spa;
4297 	int error = 0;
4298 
4299 	if (offset >> vd->vdev_ms_shift >= vd->vdev_ms_count)
4300 		return (ENXIO);
4301 
4302 	ASSERT3P(vd->vdev_ms, !=, NULL);
4303 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
4304 
4305 	mutex_enter(&msp->ms_lock);
4306 
4307 	if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded)
4308 		error = metaslab_activate(msp, 0, METASLAB_WEIGHT_CLAIM);
4309 	/*
4310 	 * No need to fail in that case; someone else has activated the
4311 	 * metaslab, but that doesn't preclude us from using it.
4312 	 */
4313 	if (error == EBUSY)
4314 		error = 0;
4315 
4316 	if (error == 0 &&
4317 	    !range_tree_contains(msp->ms_allocatable, offset, size))
4318 		error = SET_ERROR(ENOENT);
4319 
4320 	if (error || txg == 0) {	/* txg == 0 indicates dry run */
4321 		mutex_exit(&msp->ms_lock);
4322 		return (error);
4323 	}
4324 
4325 	VERIFY(!msp->ms_condensing);
4326 	VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
4327 	VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
4328 	VERIFY3U(range_tree_space(msp->ms_allocatable) - size, <=,
4329 	    msp->ms_size);
4330 	range_tree_remove(msp->ms_allocatable, offset, size);
4331 
4332 	if (spa_writeable(spa)) {	/* don't dirty if we're zdb(1M) */
4333 		if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
4334 			vdev_dirty(vd, VDD_METASLAB, msp, txg);
4335 		range_tree_add(msp->ms_allocating[txg & TXG_MASK],
4336 		    offset, size);
4337 	}
4338 
4339 	mutex_exit(&msp->ms_lock);
4340 
4341 	return (0);
4342 }
4343 
4344 typedef struct metaslab_claim_cb_arg_t {
4345 	uint64_t	mcca_txg;
4346 	int		mcca_error;
4347 } metaslab_claim_cb_arg_t;
4348 
4349 /* ARGSUSED */
4350 static void
metaslab_claim_impl_cb(uint64_t inner_offset,vdev_t * vd,uint64_t offset,uint64_t size,void * arg)4351 metaslab_claim_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
4352     uint64_t size, void *arg)
4353 {
4354 	metaslab_claim_cb_arg_t *mcca_arg = arg;
4355 
4356 	if (mcca_arg->mcca_error == 0) {
4357 		mcca_arg->mcca_error = metaslab_claim_concrete(vd, offset,
4358 		    size, mcca_arg->mcca_txg);
4359 	}
4360 }
4361 
4362 int
metaslab_claim_impl(vdev_t * vd,uint64_t offset,uint64_t size,uint64_t txg)4363 metaslab_claim_impl(vdev_t *vd, uint64_t offset, uint64_t size, uint64_t txg)
4364 {
4365 	if (vd->vdev_ops->vdev_op_remap != NULL) {
4366 		metaslab_claim_cb_arg_t arg;
4367 
4368 		/*
4369 		 * Only zdb(1M) can claim on indirect vdevs.  This is used
4370 		 * to detect leaks of mapped space (that are not accounted
4371 		 * for in the obsolete counts, spacemap, or bpobj).
4372 		 */
4373 		ASSERT(!spa_writeable(vd->vdev_spa));
4374 		arg.mcca_error = 0;
4375 		arg.mcca_txg = txg;
4376 
4377 		vd->vdev_ops->vdev_op_remap(vd, offset, size,
4378 		    metaslab_claim_impl_cb, &arg);
4379 
4380 		if (arg.mcca_error == 0) {
4381 			arg.mcca_error = metaslab_claim_concrete(vd,
4382 			    offset, size, txg);
4383 		}
4384 		return (arg.mcca_error);
4385 	} else {
4386 		return (metaslab_claim_concrete(vd, offset, size, txg));
4387 	}
4388 }
4389 
4390 /*
4391  * Intent log support: upon opening the pool after a crash, notify the SPA
4392  * of blocks that the intent log has allocated for immediate write, but
4393  * which are still considered free by the SPA because the last transaction
4394  * group didn't commit yet.
4395  */
4396 static int
metaslab_claim_dva(spa_t * spa,const dva_t * dva,uint64_t txg)4397 metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
4398 {
4399 	uint64_t vdev = DVA_GET_VDEV(dva);
4400 	uint64_t offset = DVA_GET_OFFSET(dva);
4401 	uint64_t size = DVA_GET_ASIZE(dva);
4402 	vdev_t *vd;
4403 
4404 	if ((vd = vdev_lookup_top(spa, vdev)) == NULL) {
4405 		return (SET_ERROR(ENXIO));
4406 	}
4407 
4408 	ASSERT(DVA_IS_VALID(dva));
4409 
4410 	if (DVA_GET_GANG(dva))
4411 		size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
4412 
4413 	return (metaslab_claim_impl(vd, offset, size, txg));
4414 }
4415 
4416 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)4417 metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
4418     int ndvas, uint64_t txg, blkptr_t *hintbp, int flags,
4419     zio_alloc_list_t *zal, zio_t *zio, int allocator)
4420 {
4421 	dva_t *dva = bp->blk_dva;
4422 	dva_t *hintdva = (hintbp != NULL) ? hintbp->blk_dva : NULL;
4423 	int error = 0;
4424 
4425 	ASSERT(bp->blk_birth == 0);
4426 	ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
4427 
4428 	spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
4429 
4430 	if (mc->mc_rotor == NULL) {	/* no vdevs in this class */
4431 		spa_config_exit(spa, SCL_ALLOC, FTAG);
4432 		return (SET_ERROR(ENOSPC));
4433 	}
4434 
4435 	ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
4436 	ASSERT(BP_GET_NDVAS(bp) == 0);
4437 	ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
4438 	ASSERT3P(zal, !=, NULL);
4439 
4440 	for (int d = 0; d < ndvas; d++) {
4441 		error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
4442 		    txg, flags, zal, allocator);
4443 		if (error != 0) {
4444 			for (d--; d >= 0; d--) {
4445 				metaslab_unalloc_dva(spa, &dva[d], txg);
4446 				metaslab_group_alloc_decrement(spa,
4447 				    DVA_GET_VDEV(&dva[d]), zio, flags,
4448 				    allocator, B_FALSE);
4449 				bzero(&dva[d], sizeof (dva_t));
4450 			}
4451 			spa_config_exit(spa, SCL_ALLOC, FTAG);
4452 			return (error);
4453 		} else {
4454 			/*
4455 			 * Update the metaslab group's queue depth
4456 			 * based on the newly allocated dva.
4457 			 */
4458 			metaslab_group_alloc_increment(spa,
4459 			    DVA_GET_VDEV(&dva[d]), zio, flags, allocator);
4460 		}
4461 
4462 	}
4463 	ASSERT(error == 0);
4464 	ASSERT(BP_GET_NDVAS(bp) == ndvas);
4465 
4466 	spa_config_exit(spa, SCL_ALLOC, FTAG);
4467 
4468 	BP_SET_BIRTH(bp, txg, txg);
4469 
4470 	return (0);
4471 }
4472 
4473 void
metaslab_free(spa_t * spa,const blkptr_t * bp,uint64_t txg,boolean_t now)4474 metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
4475 {
4476 	const dva_t *dva = bp->blk_dva;
4477 	int ndvas = BP_GET_NDVAS(bp);
4478 
4479 	ASSERT(!BP_IS_HOLE(bp));
4480 	ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
4481 
4482 	/*
4483 	 * If we have a checkpoint for the pool we need to make sure that
4484 	 * the blocks that we free that are part of the checkpoint won't be
4485 	 * reused until the checkpoint is discarded or we revert to it.
4486 	 *
4487 	 * The checkpoint flag is passed down the metaslab_free code path
4488 	 * and is set whenever we want to add a block to the checkpoint's
4489 	 * accounting. That is, we "checkpoint" blocks that existed at the
4490 	 * time the checkpoint was created and are therefore referenced by
4491 	 * the checkpointed uberblock.
4492 	 *
4493 	 * Note that, we don't checkpoint any blocks if the current
4494 	 * syncing txg <= spa_checkpoint_txg. We want these frees to sync
4495 	 * normally as they will be referenced by the checkpointed uberblock.
4496 	 */
4497 	boolean_t checkpoint = B_FALSE;
4498 	if (bp->blk_birth <= spa->spa_checkpoint_txg &&
4499 	    spa_syncing_txg(spa) > spa->spa_checkpoint_txg) {
4500 		/*
4501 		 * At this point, if the block is part of the checkpoint
4502 		 * there is no way it was created in the current txg.
4503 		 */
4504 		ASSERT(!now);
4505 		ASSERT3U(spa_syncing_txg(spa), ==, txg);
4506 		checkpoint = B_TRUE;
4507 	}
4508 
4509 	spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
4510 
4511 	for (int d = 0; d < ndvas; d++) {
4512 		if (now) {
4513 			metaslab_unalloc_dva(spa, &dva[d], txg);
4514 		} else {
4515 			ASSERT3U(txg, ==, spa_syncing_txg(spa));
4516 			metaslab_free_dva(spa, &dva[d], checkpoint);
4517 		}
4518 	}
4519 
4520 	spa_config_exit(spa, SCL_FREE, FTAG);
4521 }
4522 
4523 int
metaslab_claim(spa_t * spa,const blkptr_t * bp,uint64_t txg)4524 metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
4525 {
4526 	const dva_t *dva = bp->blk_dva;
4527 	int ndvas = BP_GET_NDVAS(bp);
4528 	int error = 0;
4529 
4530 	ASSERT(!BP_IS_HOLE(bp));
4531 
4532 	if (txg != 0) {
4533 		/*
4534 		 * First do a dry run to make sure all DVAs are claimable,
4535 		 * so we don't have to unwind from partial failures below.
4536 		 */
4537 		if ((error = metaslab_claim(spa, bp, 0)) != 0)
4538 			return (error);
4539 	}
4540 
4541 	spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
4542 
4543 	for (int d = 0; d < ndvas; d++) {
4544 		error = metaslab_claim_dva(spa, &dva[d], txg);
4545 		if (error != 0)
4546 			break;
4547 	}
4548 
4549 	spa_config_exit(spa, SCL_ALLOC, FTAG);
4550 
4551 	ASSERT(error == 0 || txg == 0);
4552 
4553 	return (error);
4554 }
4555 
4556 /* ARGSUSED */
4557 static void
metaslab_check_free_impl_cb(uint64_t inner,vdev_t * vd,uint64_t offset,uint64_t size,void * arg)4558 metaslab_check_free_impl_cb(uint64_t inner, vdev_t *vd, uint64_t offset,
4559     uint64_t size, void *arg)
4560 {
4561 	if (vd->vdev_ops == &vdev_indirect_ops)
4562 		return;
4563 
4564 	metaslab_check_free_impl(vd, offset, size);
4565 }
4566 
4567 static void
metaslab_check_free_impl(vdev_t * vd,uint64_t offset,uint64_t size)4568 metaslab_check_free_impl(vdev_t *vd, uint64_t offset, uint64_t size)
4569 {
4570 	metaslab_t *msp;
4571 	spa_t *spa = vd->vdev_spa;
4572 
4573 	if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
4574 		return;
4575 
4576 	if (vd->vdev_ops->vdev_op_remap != NULL) {
4577 		vd->vdev_ops->vdev_op_remap(vd, offset, size,
4578 		    metaslab_check_free_impl_cb, NULL);
4579 		return;
4580 	}
4581 
4582 	ASSERT(vdev_is_concrete(vd));
4583 	ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
4584 	ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
4585 
4586 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
4587 
4588 	mutex_enter(&msp->ms_lock);
4589 	if (msp->ms_loaded) {
4590 		range_tree_verify_not_present(msp->ms_allocatable,
4591 		    offset, size);
4592 	}
4593 
4594 	range_tree_verify_not_present(msp->ms_freeing, offset, size);
4595 	range_tree_verify_not_present(msp->ms_checkpointing, offset, size);
4596 	range_tree_verify_not_present(msp->ms_freed, offset, size);
4597 	for (int j = 0; j < TXG_DEFER_SIZE; j++)
4598 		range_tree_verify_not_present(msp->ms_defer[j], offset, size);
4599 	mutex_exit(&msp->ms_lock);
4600 }
4601 
4602 void
metaslab_check_free(spa_t * spa,const blkptr_t * bp)4603 metaslab_check_free(spa_t *spa, const blkptr_t *bp)
4604 {
4605 	if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
4606 		return;
4607 
4608 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
4609 	for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
4610 		uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
4611 		vdev_t *vd = vdev_lookup_top(spa, vdev);
4612 		uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
4613 		uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
4614 
4615 		if (DVA_GET_GANG(&bp->blk_dva[i]))
4616 			size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
4617 
4618 		ASSERT3P(vd, !=, NULL);
4619 
4620 		metaslab_check_free_impl(vd, offset, size);
4621 	}
4622 	spa_config_exit(spa, SCL_VDEV, FTAG);
4623 }
4624