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