xref: /NextBSD/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/metaslab.c (revision 84d351007654069f9643c8e4b4802a7f5f08ee42)
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, 2015 by Delphix. All rights reserved.
24  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
25  */
26 
27 #include <sys/zfs_context.h>
28 #include <sys/dmu.h>
29 #include <sys/dmu_tx.h>
30 #include <sys/space_map.h>
31 #include <sys/metaslab_impl.h>
32 #include <sys/vdev_impl.h>
33 #include <sys/zio.h>
34 #include <sys/spa_impl.h>
35 #include <sys/zfeature.h>
36 
37 SYSCTL_DECL(_vfs_zfs);
38 SYSCTL_NODE(_vfs_zfs, OID_AUTO, metaslab, CTLFLAG_RW, 0, "ZFS metaslab");
39 
40 /*
41  * Allow allocations to switch to gang blocks quickly. We do this to
42  * avoid having to load lots of space_maps in a given txg. There are,
43  * however, some cases where we want to avoid "fast" ganging and instead
44  * we want to do an exhaustive search of all metaslabs on this device.
45  * Currently we don't allow any gang, slog, or dump device related allocations
46  * to "fast" gang.
47  */
48 #define	CAN_FASTGANG(flags) \
49 	(!((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER | \
50 	METASLAB_GANG_AVOID)))
51 
52 #define	METASLAB_WEIGHT_PRIMARY		(1ULL << 63)
53 #define	METASLAB_WEIGHT_SECONDARY	(1ULL << 62)
54 #define	METASLAB_ACTIVE_MASK		\
55 	(METASLAB_WEIGHT_PRIMARY | METASLAB_WEIGHT_SECONDARY)
56 
57 uint64_t metaslab_aliquot = 512ULL << 10;
58 uint64_t metaslab_gang_bang = SPA_MAXBLOCKSIZE + 1;	/* force gang blocks */
59 SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, gang_bang, CTLFLAG_RWTUN,
60     &metaslab_gang_bang, 0,
61     "Force gang block allocation for blocks larger than or equal to this value");
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 static uint64_t metaslab_fragmentation(metaslab_t *);
242 
243 /*
244  * ==========================================================================
245  * Metaslab classes
246  * ==========================================================================
247  */
248 metaslab_class_t *
metaslab_class_create(spa_t * spa,metaslab_ops_t * ops)249 metaslab_class_create(spa_t *spa, metaslab_ops_t *ops)
250 {
251 	metaslab_class_t *mc;
252 
253 	mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
254 
255 	mc->mc_spa = spa;
256 	mc->mc_rotor = NULL;
257 	mc->mc_ops = ops;
258 
259 	return (mc);
260 }
261 
262 void
metaslab_class_destroy(metaslab_class_t * mc)263 metaslab_class_destroy(metaslab_class_t *mc)
264 {
265 	ASSERT(mc->mc_rotor == NULL);
266 	ASSERT(mc->mc_alloc == 0);
267 	ASSERT(mc->mc_deferred == 0);
268 	ASSERT(mc->mc_space == 0);
269 	ASSERT(mc->mc_dspace == 0);
270 
271 	kmem_free(mc, sizeof (metaslab_class_t));
272 }
273 
274 int
metaslab_class_validate(metaslab_class_t * mc)275 metaslab_class_validate(metaslab_class_t *mc)
276 {
277 	metaslab_group_t *mg;
278 	vdev_t *vd;
279 
280 	/*
281 	 * Must hold one of the spa_config locks.
282 	 */
283 	ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
284 	    spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
285 
286 	if ((mg = mc->mc_rotor) == NULL)
287 		return (0);
288 
289 	do {
290 		vd = mg->mg_vd;
291 		ASSERT(vd->vdev_mg != NULL);
292 		ASSERT3P(vd->vdev_top, ==, vd);
293 		ASSERT3P(mg->mg_class, ==, mc);
294 		ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
295 	} while ((mg = mg->mg_next) != mc->mc_rotor);
296 
297 	return (0);
298 }
299 
300 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)301 metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
302     int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
303 {
304 	atomic_add_64(&mc->mc_alloc, alloc_delta);
305 	atomic_add_64(&mc->mc_deferred, defer_delta);
306 	atomic_add_64(&mc->mc_space, space_delta);
307 	atomic_add_64(&mc->mc_dspace, dspace_delta);
308 }
309 
310 void
metaslab_class_minblocksize_update(metaslab_class_t * mc)311 metaslab_class_minblocksize_update(metaslab_class_t *mc)
312 {
313 	metaslab_group_t *mg;
314 	vdev_t *vd;
315 	uint64_t minashift = UINT64_MAX;
316 
317 	if ((mg = mc->mc_rotor) == NULL) {
318 		mc->mc_minblocksize = SPA_MINBLOCKSIZE;
319 		return;
320 	}
321 
322 	do {
323 		vd = mg->mg_vd;
324 		if (vd->vdev_ashift < minashift)
325 			minashift = vd->vdev_ashift;
326 	} while ((mg = mg->mg_next) != mc->mc_rotor);
327 
328 	mc->mc_minblocksize = 1ULL << minashift;
329 }
330 
331 uint64_t
metaslab_class_get_alloc(metaslab_class_t * mc)332 metaslab_class_get_alloc(metaslab_class_t *mc)
333 {
334 	return (mc->mc_alloc);
335 }
336 
337 uint64_t
metaslab_class_get_deferred(metaslab_class_t * mc)338 metaslab_class_get_deferred(metaslab_class_t *mc)
339 {
340 	return (mc->mc_deferred);
341 }
342 
343 uint64_t
metaslab_class_get_space(metaslab_class_t * mc)344 metaslab_class_get_space(metaslab_class_t *mc)
345 {
346 	return (mc->mc_space);
347 }
348 
349 uint64_t
metaslab_class_get_dspace(metaslab_class_t * mc)350 metaslab_class_get_dspace(metaslab_class_t *mc)
351 {
352 	return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
353 }
354 
355 uint64_t
metaslab_class_get_minblocksize(metaslab_class_t * mc)356 metaslab_class_get_minblocksize(metaslab_class_t *mc)
357 {
358 	return (mc->mc_minblocksize);
359 }
360 
361 void
metaslab_class_histogram_verify(metaslab_class_t * mc)362 metaslab_class_histogram_verify(metaslab_class_t *mc)
363 {
364 	vdev_t *rvd = mc->mc_spa->spa_root_vdev;
365 	uint64_t *mc_hist;
366 	int i;
367 
368 	if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
369 		return;
370 
371 	mc_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
372 	    KM_SLEEP);
373 
374 	for (int c = 0; c < rvd->vdev_children; c++) {
375 		vdev_t *tvd = rvd->vdev_child[c];
376 		metaslab_group_t *mg = tvd->vdev_mg;
377 
378 		/*
379 		 * Skip any holes, uninitialized top-levels, or
380 		 * vdevs that are not in this metalab class.
381 		 */
382 		if (tvd->vdev_ishole || tvd->vdev_ms_shift == 0 ||
383 		    mg->mg_class != mc) {
384 			continue;
385 		}
386 
387 		for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
388 			mc_hist[i] += mg->mg_histogram[i];
389 	}
390 
391 	for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
392 		VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
393 
394 	kmem_free(mc_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
395 }
396 
397 /*
398  * Calculate the metaslab class's fragmentation metric. The metric
399  * is weighted based on the space contribution of each metaslab group.
400  * The return value will be a number between 0 and 100 (inclusive), or
401  * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
402  * zfs_frag_table for more information about the metric.
403  */
404 uint64_t
metaslab_class_fragmentation(metaslab_class_t * mc)405 metaslab_class_fragmentation(metaslab_class_t *mc)
406 {
407 	vdev_t *rvd = mc->mc_spa->spa_root_vdev;
408 	uint64_t fragmentation = 0;
409 
410 	spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
411 
412 	for (int c = 0; c < rvd->vdev_children; c++) {
413 		vdev_t *tvd = rvd->vdev_child[c];
414 		metaslab_group_t *mg = tvd->vdev_mg;
415 
416 		/*
417 		 * Skip any holes, uninitialized top-levels, or
418 		 * vdevs that are not in this metalab class.
419 		 */
420 		if (tvd->vdev_ishole || tvd->vdev_ms_shift == 0 ||
421 		    mg->mg_class != mc) {
422 			continue;
423 		}
424 
425 		/*
426 		 * If a metaslab group does not contain a fragmentation
427 		 * metric then just bail out.
428 		 */
429 		if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
430 			spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
431 			return (ZFS_FRAG_INVALID);
432 		}
433 
434 		/*
435 		 * Determine how much this metaslab_group is contributing
436 		 * to the overall pool fragmentation metric.
437 		 */
438 		fragmentation += mg->mg_fragmentation *
439 		    metaslab_group_get_space(mg);
440 	}
441 	fragmentation /= metaslab_class_get_space(mc);
442 
443 	ASSERT3U(fragmentation, <=, 100);
444 	spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
445 	return (fragmentation);
446 }
447 
448 /*
449  * Calculate the amount of expandable space that is available in
450  * this metaslab class. If a device is expanded then its expandable
451  * space will be the amount of allocatable space that is currently not
452  * part of this metaslab class.
453  */
454 uint64_t
metaslab_class_expandable_space(metaslab_class_t * mc)455 metaslab_class_expandable_space(metaslab_class_t *mc)
456 {
457 	vdev_t *rvd = mc->mc_spa->spa_root_vdev;
458 	uint64_t space = 0;
459 
460 	spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
461 	for (int c = 0; c < rvd->vdev_children; c++) {
462 		vdev_t *tvd = rvd->vdev_child[c];
463 		metaslab_group_t *mg = tvd->vdev_mg;
464 
465 		if (tvd->vdev_ishole || tvd->vdev_ms_shift == 0 ||
466 		    mg->mg_class != mc) {
467 			continue;
468 		}
469 
470 		space += tvd->vdev_max_asize - tvd->vdev_asize;
471 	}
472 	spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
473 	return (space);
474 }
475 
476 /*
477  * ==========================================================================
478  * Metaslab groups
479  * ==========================================================================
480  */
481 static int
metaslab_compare(const void * x1,const void * x2)482 metaslab_compare(const void *x1, const void *x2)
483 {
484 	const metaslab_t *m1 = x1;
485 	const metaslab_t *m2 = x2;
486 
487 	if (m1->ms_weight < m2->ms_weight)
488 		return (1);
489 	if (m1->ms_weight > m2->ms_weight)
490 		return (-1);
491 
492 	/*
493 	 * If the weights are identical, use the offset to force uniqueness.
494 	 */
495 	if (m1->ms_start < m2->ms_start)
496 		return (-1);
497 	if (m1->ms_start > m2->ms_start)
498 		return (1);
499 
500 	ASSERT3P(m1, ==, m2);
501 
502 	return (0);
503 }
504 
505 /*
506  * Update the allocatable flag and the metaslab group's capacity.
507  * The allocatable flag is set to true if the capacity is below
508  * the zfs_mg_noalloc_threshold. If a metaslab group transitions
509  * from allocatable to non-allocatable or vice versa then the metaslab
510  * group's class is updated to reflect the transition.
511  */
512 static void
metaslab_group_alloc_update(metaslab_group_t * mg)513 metaslab_group_alloc_update(metaslab_group_t *mg)
514 {
515 	vdev_t *vd = mg->mg_vd;
516 	metaslab_class_t *mc = mg->mg_class;
517 	vdev_stat_t *vs = &vd->vdev_stat;
518 	boolean_t was_allocatable;
519 
520 	ASSERT(vd == vd->vdev_top);
521 
522 	mutex_enter(&mg->mg_lock);
523 	was_allocatable = mg->mg_allocatable;
524 
525 	mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
526 	    (vs->vs_space + 1);
527 
528 	/*
529 	 * A metaslab group is considered allocatable if it has plenty
530 	 * of free space or is not heavily fragmented. We only take
531 	 * fragmentation into account if the metaslab group has a valid
532 	 * fragmentation metric (i.e. a value between 0 and 100).
533 	 */
534 	mg->mg_allocatable = (mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
535 	    (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
536 	    mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
537 
538 	/*
539 	 * The mc_alloc_groups maintains a count of the number of
540 	 * groups in this metaslab class that are still above the
541 	 * zfs_mg_noalloc_threshold. This is used by the allocating
542 	 * threads to determine if they should avoid allocations to
543 	 * a given group. The allocator will avoid allocations to a group
544 	 * if that group has reached or is below the zfs_mg_noalloc_threshold
545 	 * and there are still other groups that are above the threshold.
546 	 * When a group transitions from allocatable to non-allocatable or
547 	 * vice versa we update the metaslab class to reflect that change.
548 	 * When the mc_alloc_groups value drops to 0 that means that all
549 	 * groups have reached the zfs_mg_noalloc_threshold making all groups
550 	 * eligible for allocations. This effectively means that all devices
551 	 * are balanced again.
552 	 */
553 	if (was_allocatable && !mg->mg_allocatable)
554 		mc->mc_alloc_groups--;
555 	else if (!was_allocatable && mg->mg_allocatable)
556 		mc->mc_alloc_groups++;
557 
558 	mutex_exit(&mg->mg_lock);
559 }
560 
561 metaslab_group_t *
metaslab_group_create(metaslab_class_t * mc,vdev_t * vd)562 metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
563 {
564 	metaslab_group_t *mg;
565 
566 	mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
567 	mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
568 	avl_create(&mg->mg_metaslab_tree, metaslab_compare,
569 	    sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
570 	mg->mg_vd = vd;
571 	mg->mg_class = mc;
572 	mg->mg_activation_count = 0;
573 
574 	mg->mg_taskq = taskq_create("metaslab_group_taskq", metaslab_load_pct,
575 	    minclsyspri, 10, INT_MAX, TASKQ_THREADS_CPU_PCT);
576 
577 	return (mg);
578 }
579 
580 void
metaslab_group_destroy(metaslab_group_t * mg)581 metaslab_group_destroy(metaslab_group_t *mg)
582 {
583 	ASSERT(mg->mg_prev == NULL);
584 	ASSERT(mg->mg_next == NULL);
585 	/*
586 	 * We may have gone below zero with the activation count
587 	 * either because we never activated in the first place or
588 	 * because we're done, and possibly removing the vdev.
589 	 */
590 	ASSERT(mg->mg_activation_count <= 0);
591 
592 	taskq_destroy(mg->mg_taskq);
593 	avl_destroy(&mg->mg_metaslab_tree);
594 	mutex_destroy(&mg->mg_lock);
595 	kmem_free(mg, sizeof (metaslab_group_t));
596 }
597 
598 void
metaslab_group_activate(metaslab_group_t * mg)599 metaslab_group_activate(metaslab_group_t *mg)
600 {
601 	metaslab_class_t *mc = mg->mg_class;
602 	metaslab_group_t *mgprev, *mgnext;
603 
604 	ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
605 
606 	ASSERT(mc->mc_rotor != mg);
607 	ASSERT(mg->mg_prev == NULL);
608 	ASSERT(mg->mg_next == NULL);
609 	ASSERT(mg->mg_activation_count <= 0);
610 
611 	if (++mg->mg_activation_count <= 0)
612 		return;
613 
614 	mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
615 	metaslab_group_alloc_update(mg);
616 
617 	if ((mgprev = mc->mc_rotor) == NULL) {
618 		mg->mg_prev = mg;
619 		mg->mg_next = mg;
620 	} else {
621 		mgnext = mgprev->mg_next;
622 		mg->mg_prev = mgprev;
623 		mg->mg_next = mgnext;
624 		mgprev->mg_next = mg;
625 		mgnext->mg_prev = mg;
626 	}
627 	mc->mc_rotor = mg;
628 	metaslab_class_minblocksize_update(mc);
629 }
630 
631 void
metaslab_group_passivate(metaslab_group_t * mg)632 metaslab_group_passivate(metaslab_group_t *mg)
633 {
634 	metaslab_class_t *mc = mg->mg_class;
635 	metaslab_group_t *mgprev, *mgnext;
636 
637 	ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
638 
639 	if (--mg->mg_activation_count != 0) {
640 		ASSERT(mc->mc_rotor != mg);
641 		ASSERT(mg->mg_prev == NULL);
642 		ASSERT(mg->mg_next == NULL);
643 		ASSERT(mg->mg_activation_count < 0);
644 		return;
645 	}
646 
647 	taskq_wait(mg->mg_taskq);
648 	metaslab_group_alloc_update(mg);
649 
650 	mgprev = mg->mg_prev;
651 	mgnext = mg->mg_next;
652 
653 	if (mg == mgnext) {
654 		mc->mc_rotor = NULL;
655 	} else {
656 		mc->mc_rotor = mgnext;
657 		mgprev->mg_next = mgnext;
658 		mgnext->mg_prev = mgprev;
659 	}
660 
661 	mg->mg_prev = NULL;
662 	mg->mg_next = NULL;
663 	metaslab_class_minblocksize_update(mc);
664 }
665 
666 uint64_t
metaslab_group_get_space(metaslab_group_t * mg)667 metaslab_group_get_space(metaslab_group_t *mg)
668 {
669 	return ((1ULL << mg->mg_vd->vdev_ms_shift) * mg->mg_vd->vdev_ms_count);
670 }
671 
672 void
metaslab_group_histogram_verify(metaslab_group_t * mg)673 metaslab_group_histogram_verify(metaslab_group_t *mg)
674 {
675 	uint64_t *mg_hist;
676 	vdev_t *vd = mg->mg_vd;
677 	uint64_t ashift = vd->vdev_ashift;
678 	int i;
679 
680 	if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
681 		return;
682 
683 	mg_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
684 	    KM_SLEEP);
685 
686 	ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE, >=,
687 	    SPACE_MAP_HISTOGRAM_SIZE + ashift);
688 
689 	for (int m = 0; m < vd->vdev_ms_count; m++) {
690 		metaslab_t *msp = vd->vdev_ms[m];
691 
692 		if (msp->ms_sm == NULL)
693 			continue;
694 
695 		for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
696 			mg_hist[i + ashift] +=
697 			    msp->ms_sm->sm_phys->smp_histogram[i];
698 	}
699 
700 	for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i ++)
701 		VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
702 
703 	kmem_free(mg_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
704 }
705 
706 static void
metaslab_group_histogram_add(metaslab_group_t * mg,metaslab_t * msp)707 metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
708 {
709 	metaslab_class_t *mc = mg->mg_class;
710 	uint64_t ashift = mg->mg_vd->vdev_ashift;
711 
712 	ASSERT(MUTEX_HELD(&msp->ms_lock));
713 	if (msp->ms_sm == NULL)
714 		return;
715 
716 	mutex_enter(&mg->mg_lock);
717 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
718 		mg->mg_histogram[i + ashift] +=
719 		    msp->ms_sm->sm_phys->smp_histogram[i];
720 		mc->mc_histogram[i + ashift] +=
721 		    msp->ms_sm->sm_phys->smp_histogram[i];
722 	}
723 	mutex_exit(&mg->mg_lock);
724 }
725 
726 void
metaslab_group_histogram_remove(metaslab_group_t * mg,metaslab_t * msp)727 metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
728 {
729 	metaslab_class_t *mc = mg->mg_class;
730 	uint64_t ashift = mg->mg_vd->vdev_ashift;
731 
732 	ASSERT(MUTEX_HELD(&msp->ms_lock));
733 	if (msp->ms_sm == NULL)
734 		return;
735 
736 	mutex_enter(&mg->mg_lock);
737 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
738 		ASSERT3U(mg->mg_histogram[i + ashift], >=,
739 		    msp->ms_sm->sm_phys->smp_histogram[i]);
740 		ASSERT3U(mc->mc_histogram[i + ashift], >=,
741 		    msp->ms_sm->sm_phys->smp_histogram[i]);
742 
743 		mg->mg_histogram[i + ashift] -=
744 		    msp->ms_sm->sm_phys->smp_histogram[i];
745 		mc->mc_histogram[i + ashift] -=
746 		    msp->ms_sm->sm_phys->smp_histogram[i];
747 	}
748 	mutex_exit(&mg->mg_lock);
749 }
750 
751 static void
metaslab_group_add(metaslab_group_t * mg,metaslab_t * msp)752 metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
753 {
754 	ASSERT(msp->ms_group == NULL);
755 	mutex_enter(&mg->mg_lock);
756 	msp->ms_group = mg;
757 	msp->ms_weight = 0;
758 	avl_add(&mg->mg_metaslab_tree, msp);
759 	mutex_exit(&mg->mg_lock);
760 
761 	mutex_enter(&msp->ms_lock);
762 	metaslab_group_histogram_add(mg, msp);
763 	mutex_exit(&msp->ms_lock);
764 }
765 
766 static void
metaslab_group_remove(metaslab_group_t * mg,metaslab_t * msp)767 metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
768 {
769 	mutex_enter(&msp->ms_lock);
770 	metaslab_group_histogram_remove(mg, msp);
771 	mutex_exit(&msp->ms_lock);
772 
773 	mutex_enter(&mg->mg_lock);
774 	ASSERT(msp->ms_group == mg);
775 	avl_remove(&mg->mg_metaslab_tree, msp);
776 	msp->ms_group = NULL;
777 	mutex_exit(&mg->mg_lock);
778 }
779 
780 static void
metaslab_group_sort(metaslab_group_t * mg,metaslab_t * msp,uint64_t weight)781 metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
782 {
783 	/*
784 	 * Although in principle the weight can be any value, in
785 	 * practice we do not use values in the range [1, 511].
786 	 */
787 	ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
788 	ASSERT(MUTEX_HELD(&msp->ms_lock));
789 
790 	mutex_enter(&mg->mg_lock);
791 	ASSERT(msp->ms_group == mg);
792 	avl_remove(&mg->mg_metaslab_tree, msp);
793 	msp->ms_weight = weight;
794 	avl_add(&mg->mg_metaslab_tree, msp);
795 	mutex_exit(&mg->mg_lock);
796 }
797 
798 /*
799  * Calculate the fragmentation for a given metaslab group. We can use
800  * a simple average here since all metaslabs within the group must have
801  * the same size. The return value will be a value between 0 and 100
802  * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
803  * group have a fragmentation metric.
804  */
805 uint64_t
metaslab_group_fragmentation(metaslab_group_t * mg)806 metaslab_group_fragmentation(metaslab_group_t *mg)
807 {
808 	vdev_t *vd = mg->mg_vd;
809 	uint64_t fragmentation = 0;
810 	uint64_t valid_ms = 0;
811 
812 	for (int m = 0; m < vd->vdev_ms_count; m++) {
813 		metaslab_t *msp = vd->vdev_ms[m];
814 
815 		if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
816 			continue;
817 
818 		valid_ms++;
819 		fragmentation += msp->ms_fragmentation;
820 	}
821 
822 	if (valid_ms <= vd->vdev_ms_count / 2)
823 		return (ZFS_FRAG_INVALID);
824 
825 	fragmentation /= valid_ms;
826 	ASSERT3U(fragmentation, <=, 100);
827 	return (fragmentation);
828 }
829 
830 /*
831  * Determine if a given metaslab group should skip allocations. A metaslab
832  * group should avoid allocations if its free capacity is less than the
833  * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
834  * zfs_mg_fragmentation_threshold and there is at least one metaslab group
835  * that can still handle allocations.
836  */
837 static boolean_t
metaslab_group_allocatable(metaslab_group_t * mg)838 metaslab_group_allocatable(metaslab_group_t *mg)
839 {
840 	vdev_t *vd = mg->mg_vd;
841 	spa_t *spa = vd->vdev_spa;
842 	metaslab_class_t *mc = mg->mg_class;
843 
844 	/*
845 	 * We use two key metrics to determine if a metaslab group is
846 	 * considered allocatable -- free space and fragmentation. If
847 	 * the free space is greater than the free space threshold and
848 	 * the fragmentation is less than the fragmentation threshold then
849 	 * consider the group allocatable. There are two case when we will
850 	 * not consider these key metrics. The first is if the group is
851 	 * associated with a slog device and the second is if all groups
852 	 * in this metaslab class have already been consider ineligible
853 	 * for allocations.
854 	 */
855 	return ((mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
856 	    (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
857 	    mg->mg_fragmentation <= zfs_mg_fragmentation_threshold)) ||
858 	    mc != spa_normal_class(spa) || mc->mc_alloc_groups == 0);
859 }
860 
861 /*
862  * ==========================================================================
863  * Range tree callbacks
864  * ==========================================================================
865  */
866 
867 /*
868  * Comparison function for the private size-ordered tree. Tree is sorted
869  * by size, larger sizes at the end of the tree.
870  */
871 static int
metaslab_rangesize_compare(const void * x1,const void * x2)872 metaslab_rangesize_compare(const void *x1, const void *x2)
873 {
874 	const range_seg_t *r1 = x1;
875 	const range_seg_t *r2 = x2;
876 	uint64_t rs_size1 = r1->rs_end - r1->rs_start;
877 	uint64_t rs_size2 = r2->rs_end - r2->rs_start;
878 
879 	if (rs_size1 < rs_size2)
880 		return (-1);
881 	if (rs_size1 > rs_size2)
882 		return (1);
883 
884 	if (r1->rs_start < r2->rs_start)
885 		return (-1);
886 
887 	if (r1->rs_start > r2->rs_start)
888 		return (1);
889 
890 	return (0);
891 }
892 
893 /*
894  * Create any block allocator specific components. The current allocators
895  * rely on using both a size-ordered range_tree_t and an array of uint64_t's.
896  */
897 static void
metaslab_rt_create(range_tree_t * rt,void * arg)898 metaslab_rt_create(range_tree_t *rt, void *arg)
899 {
900 	metaslab_t *msp = arg;
901 
902 	ASSERT3P(rt->rt_arg, ==, msp);
903 	ASSERT(msp->ms_tree == NULL);
904 
905 	avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
906 	    sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
907 }
908 
909 /*
910  * Destroy the block allocator specific components.
911  */
912 static void
metaslab_rt_destroy(range_tree_t * rt,void * arg)913 metaslab_rt_destroy(range_tree_t *rt, void *arg)
914 {
915 	metaslab_t *msp = arg;
916 
917 	ASSERT3P(rt->rt_arg, ==, msp);
918 	ASSERT3P(msp->ms_tree, ==, rt);
919 	ASSERT0(avl_numnodes(&msp->ms_size_tree));
920 
921 	avl_destroy(&msp->ms_size_tree);
922 }
923 
924 static void
metaslab_rt_add(range_tree_t * rt,range_seg_t * rs,void * arg)925 metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg)
926 {
927 	metaslab_t *msp = arg;
928 
929 	ASSERT3P(rt->rt_arg, ==, msp);
930 	ASSERT3P(msp->ms_tree, ==, rt);
931 	VERIFY(!msp->ms_condensing);
932 	avl_add(&msp->ms_size_tree, rs);
933 }
934 
935 static void
metaslab_rt_remove(range_tree_t * rt,range_seg_t * rs,void * arg)936 metaslab_rt_remove(range_tree_t *rt, range_seg_t *rs, void *arg)
937 {
938 	metaslab_t *msp = arg;
939 
940 	ASSERT3P(rt->rt_arg, ==, msp);
941 	ASSERT3P(msp->ms_tree, ==, rt);
942 	VERIFY(!msp->ms_condensing);
943 	avl_remove(&msp->ms_size_tree, rs);
944 }
945 
946 static void
metaslab_rt_vacate(range_tree_t * rt,void * arg)947 metaslab_rt_vacate(range_tree_t *rt, void *arg)
948 {
949 	metaslab_t *msp = arg;
950 
951 	ASSERT3P(rt->rt_arg, ==, msp);
952 	ASSERT3P(msp->ms_tree, ==, rt);
953 
954 	/*
955 	 * Normally one would walk the tree freeing nodes along the way.
956 	 * Since the nodes are shared with the range trees we can avoid
957 	 * walking all nodes and just reinitialize the avl tree. The nodes
958 	 * will be freed by the range tree, so we don't want to free them here.
959 	 */
960 	avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
961 	    sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
962 }
963 
964 static range_tree_ops_t metaslab_rt_ops = {
965 	metaslab_rt_create,
966 	metaslab_rt_destroy,
967 	metaslab_rt_add,
968 	metaslab_rt_remove,
969 	metaslab_rt_vacate
970 };
971 
972 /*
973  * ==========================================================================
974  * Metaslab block operations
975  * ==========================================================================
976  */
977 
978 /*
979  * Return the maximum contiguous segment within the metaslab.
980  */
981 uint64_t
metaslab_block_maxsize(metaslab_t * msp)982 metaslab_block_maxsize(metaslab_t *msp)
983 {
984 	avl_tree_t *t = &msp->ms_size_tree;
985 	range_seg_t *rs;
986 
987 	if (t == NULL || (rs = avl_last(t)) == NULL)
988 		return (0ULL);
989 
990 	return (rs->rs_end - rs->rs_start);
991 }
992 
993 uint64_t
metaslab_block_alloc(metaslab_t * msp,uint64_t size)994 metaslab_block_alloc(metaslab_t *msp, uint64_t size)
995 {
996 	uint64_t start;
997 	range_tree_t *rt = msp->ms_tree;
998 
999 	VERIFY(!msp->ms_condensing);
1000 
1001 	start = msp->ms_ops->msop_alloc(msp, size);
1002 	if (start != -1ULL) {
1003 		vdev_t *vd = msp->ms_group->mg_vd;
1004 
1005 		VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
1006 		VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
1007 		VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
1008 		range_tree_remove(rt, start, size);
1009 	}
1010 	return (start);
1011 }
1012 
1013 /*
1014  * ==========================================================================
1015  * Common allocator routines
1016  * ==========================================================================
1017  */
1018 
1019 /*
1020  * This is a helper function that can be used by the allocator to find
1021  * a suitable block to allocate. This will search the specified AVL
1022  * tree looking for a block that matches the specified criteria.
1023  */
1024 static uint64_t
metaslab_block_picker(avl_tree_t * t,uint64_t * cursor,uint64_t size,uint64_t align)1025 metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
1026     uint64_t align)
1027 {
1028 	range_seg_t *rs, rsearch;
1029 	avl_index_t where;
1030 
1031 	rsearch.rs_start = *cursor;
1032 	rsearch.rs_end = *cursor + size;
1033 
1034 	rs = avl_find(t, &rsearch, &where);
1035 	if (rs == NULL)
1036 		rs = avl_nearest(t, where, AVL_AFTER);
1037 
1038 	while (rs != NULL) {
1039 		uint64_t offset = P2ROUNDUP(rs->rs_start, align);
1040 
1041 		if (offset + size <= rs->rs_end) {
1042 			*cursor = offset + size;
1043 			return (offset);
1044 		}
1045 		rs = AVL_NEXT(t, rs);
1046 	}
1047 
1048 	/*
1049 	 * If we know we've searched the whole map (*cursor == 0), give up.
1050 	 * Otherwise, reset the cursor to the beginning and try again.
1051 	 */
1052 	if (*cursor == 0)
1053 		return (-1ULL);
1054 
1055 	*cursor = 0;
1056 	return (metaslab_block_picker(t, cursor, size, align));
1057 }
1058 
1059 /*
1060  * ==========================================================================
1061  * The first-fit block allocator
1062  * ==========================================================================
1063  */
1064 static uint64_t
metaslab_ff_alloc(metaslab_t * msp,uint64_t size)1065 metaslab_ff_alloc(metaslab_t *msp, uint64_t size)
1066 {
1067 	/*
1068 	 * Find the largest power of 2 block size that evenly divides the
1069 	 * requested size. This is used to try to allocate blocks with similar
1070 	 * alignment from the same area of the metaslab (i.e. same cursor
1071 	 * bucket) but it does not guarantee that other allocations sizes
1072 	 * may exist in the same region.
1073 	 */
1074 	uint64_t align = size & -size;
1075 	uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
1076 	avl_tree_t *t = &msp->ms_tree->rt_root;
1077 
1078 	return (metaslab_block_picker(t, cursor, size, align));
1079 }
1080 
1081 static metaslab_ops_t metaslab_ff_ops = {
1082 	metaslab_ff_alloc
1083 };
1084 
1085 /*
1086  * ==========================================================================
1087  * Dynamic block allocator -
1088  * Uses the first fit allocation scheme until space get low and then
1089  * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
1090  * and metaslab_df_free_pct to determine when to switch the allocation scheme.
1091  * ==========================================================================
1092  */
1093 static uint64_t
metaslab_df_alloc(metaslab_t * msp,uint64_t size)1094 metaslab_df_alloc(metaslab_t *msp, uint64_t size)
1095 {
1096 	/*
1097 	 * Find the largest power of 2 block size that evenly divides the
1098 	 * requested size. This is used to try to allocate blocks with similar
1099 	 * alignment from the same area of the metaslab (i.e. same cursor
1100 	 * bucket) but it does not guarantee that other allocations sizes
1101 	 * may exist in the same region.
1102 	 */
1103 	uint64_t align = size & -size;
1104 	uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
1105 	range_tree_t *rt = msp->ms_tree;
1106 	avl_tree_t *t = &rt->rt_root;
1107 	uint64_t max_size = metaslab_block_maxsize(msp);
1108 	int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1109 
1110 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1111 	ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
1112 
1113 	if (max_size < size)
1114 		return (-1ULL);
1115 
1116 	/*
1117 	 * If we're running low on space switch to using the size
1118 	 * sorted AVL tree (best-fit).
1119 	 */
1120 	if (max_size < metaslab_df_alloc_threshold ||
1121 	    free_pct < metaslab_df_free_pct) {
1122 		t = &msp->ms_size_tree;
1123 		*cursor = 0;
1124 	}
1125 
1126 	return (metaslab_block_picker(t, cursor, size, 1ULL));
1127 }
1128 
1129 static metaslab_ops_t metaslab_df_ops = {
1130 	metaslab_df_alloc
1131 };
1132 
1133 /*
1134  * ==========================================================================
1135  * Cursor fit block allocator -
1136  * Select the largest region in the metaslab, set the cursor to the beginning
1137  * of the range and the cursor_end to the end of the range. As allocations
1138  * are made advance the cursor. Continue allocating from the cursor until
1139  * the range is exhausted and then find a new range.
1140  * ==========================================================================
1141  */
1142 static uint64_t
metaslab_cf_alloc(metaslab_t * msp,uint64_t size)1143 metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
1144 {
1145 	range_tree_t *rt = msp->ms_tree;
1146 	avl_tree_t *t = &msp->ms_size_tree;
1147 	uint64_t *cursor = &msp->ms_lbas[0];
1148 	uint64_t *cursor_end = &msp->ms_lbas[1];
1149 	uint64_t offset = 0;
1150 
1151 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1152 	ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&rt->rt_root));
1153 
1154 	ASSERT3U(*cursor_end, >=, *cursor);
1155 
1156 	if ((*cursor + size) > *cursor_end) {
1157 		range_seg_t *rs;
1158 
1159 		rs = avl_last(&msp->ms_size_tree);
1160 		if (rs == NULL || (rs->rs_end - rs->rs_start) < size)
1161 			return (-1ULL);
1162 
1163 		*cursor = rs->rs_start;
1164 		*cursor_end = rs->rs_end;
1165 	}
1166 
1167 	offset = *cursor;
1168 	*cursor += size;
1169 
1170 	return (offset);
1171 }
1172 
1173 static metaslab_ops_t metaslab_cf_ops = {
1174 	metaslab_cf_alloc
1175 };
1176 
1177 /*
1178  * ==========================================================================
1179  * New dynamic fit allocator -
1180  * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1181  * contiguous blocks. If no region is found then just use the largest segment
1182  * that remains.
1183  * ==========================================================================
1184  */
1185 
1186 /*
1187  * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1188  * to request from the allocator.
1189  */
1190 uint64_t metaslab_ndf_clump_shift = 4;
1191 
1192 static uint64_t
metaslab_ndf_alloc(metaslab_t * msp,uint64_t size)1193 metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
1194 {
1195 	avl_tree_t *t = &msp->ms_tree->rt_root;
1196 	avl_index_t where;
1197 	range_seg_t *rs, rsearch;
1198 	uint64_t hbit = highbit64(size);
1199 	uint64_t *cursor = &msp->ms_lbas[hbit - 1];
1200 	uint64_t max_size = metaslab_block_maxsize(msp);
1201 
1202 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1203 	ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
1204 
1205 	if (max_size < size)
1206 		return (-1ULL);
1207 
1208 	rsearch.rs_start = *cursor;
1209 	rsearch.rs_end = *cursor + size;
1210 
1211 	rs = avl_find(t, &rsearch, &where);
1212 	if (rs == NULL || (rs->rs_end - rs->rs_start) < size) {
1213 		t = &msp->ms_size_tree;
1214 
1215 		rsearch.rs_start = 0;
1216 		rsearch.rs_end = MIN(max_size,
1217 		    1ULL << (hbit + metaslab_ndf_clump_shift));
1218 		rs = avl_find(t, &rsearch, &where);
1219 		if (rs == NULL)
1220 			rs = avl_nearest(t, where, AVL_AFTER);
1221 		ASSERT(rs != NULL);
1222 	}
1223 
1224 	if ((rs->rs_end - rs->rs_start) >= size) {
1225 		*cursor = rs->rs_start + size;
1226 		return (rs->rs_start);
1227 	}
1228 	return (-1ULL);
1229 }
1230 
1231 static metaslab_ops_t metaslab_ndf_ops = {
1232 	metaslab_ndf_alloc
1233 };
1234 
1235 metaslab_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
1236 
1237 /*
1238  * ==========================================================================
1239  * Metaslabs
1240  * ==========================================================================
1241  */
1242 
1243 /*
1244  * Wait for any in-progress metaslab loads to complete.
1245  */
1246 void
metaslab_load_wait(metaslab_t * msp)1247 metaslab_load_wait(metaslab_t *msp)
1248 {
1249 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1250 
1251 	while (msp->ms_loading) {
1252 		ASSERT(!msp->ms_loaded);
1253 		cv_wait(&msp->ms_load_cv, &msp->ms_lock);
1254 	}
1255 }
1256 
1257 int
metaslab_load(metaslab_t * msp)1258 metaslab_load(metaslab_t *msp)
1259 {
1260 	int error = 0;
1261 
1262 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1263 	ASSERT(!msp->ms_loaded);
1264 	ASSERT(!msp->ms_loading);
1265 
1266 	msp->ms_loading = B_TRUE;
1267 
1268 	/*
1269 	 * If the space map has not been allocated yet, then treat
1270 	 * all the space in the metaslab as free and add it to the
1271 	 * ms_tree.
1272 	 */
1273 	if (msp->ms_sm != NULL)
1274 		error = space_map_load(msp->ms_sm, msp->ms_tree, SM_FREE);
1275 	else
1276 		range_tree_add(msp->ms_tree, msp->ms_start, msp->ms_size);
1277 
1278 	msp->ms_loaded = (error == 0);
1279 	msp->ms_loading = B_FALSE;
1280 
1281 	if (msp->ms_loaded) {
1282 		for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1283 			range_tree_walk(msp->ms_defertree[t],
1284 			    range_tree_remove, msp->ms_tree);
1285 		}
1286 	}
1287 	cv_broadcast(&msp->ms_load_cv);
1288 	return (error);
1289 }
1290 
1291 void
metaslab_unload(metaslab_t * msp)1292 metaslab_unload(metaslab_t *msp)
1293 {
1294 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1295 	range_tree_vacate(msp->ms_tree, NULL, NULL);
1296 	msp->ms_loaded = B_FALSE;
1297 	msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
1298 }
1299 
1300 int
metaslab_init(metaslab_group_t * mg,uint64_t id,uint64_t object,uint64_t txg,metaslab_t ** msp)1301 metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object, uint64_t txg,
1302     metaslab_t **msp)
1303 {
1304 	vdev_t *vd = mg->mg_vd;
1305 	objset_t *mos = vd->vdev_spa->spa_meta_objset;
1306 	metaslab_t *ms;
1307 	int error;
1308 
1309 	ms = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
1310 	mutex_init(&ms->ms_lock, NULL, MUTEX_DEFAULT, NULL);
1311 	cv_init(&ms->ms_load_cv, NULL, CV_DEFAULT, NULL);
1312 	ms->ms_id = id;
1313 	ms->ms_start = id << vd->vdev_ms_shift;
1314 	ms->ms_size = 1ULL << vd->vdev_ms_shift;
1315 
1316 	/*
1317 	 * We only open space map objects that already exist. All others
1318 	 * will be opened when we finally allocate an object for it.
1319 	 */
1320 	if (object != 0) {
1321 		error = space_map_open(&ms->ms_sm, mos, object, ms->ms_start,
1322 		    ms->ms_size, vd->vdev_ashift, &ms->ms_lock);
1323 
1324 		if (error != 0) {
1325 			kmem_free(ms, sizeof (metaslab_t));
1326 			return (error);
1327 		}
1328 
1329 		ASSERT(ms->ms_sm != NULL);
1330 	}
1331 
1332 	/*
1333 	 * We create the main range tree here, but we don't create the
1334 	 * alloctree and freetree until metaslab_sync_done().  This serves
1335 	 * two purposes: it allows metaslab_sync_done() to detect the
1336 	 * addition of new space; and for debugging, it ensures that we'd
1337 	 * data fault on any attempt to use this metaslab before it's ready.
1338 	 */
1339 	ms->ms_tree = range_tree_create(&metaslab_rt_ops, ms, &ms->ms_lock);
1340 	metaslab_group_add(mg, ms);
1341 
1342 	ms->ms_fragmentation = metaslab_fragmentation(ms);
1343 	ms->ms_ops = mg->mg_class->mc_ops;
1344 
1345 	/*
1346 	 * If we're opening an existing pool (txg == 0) or creating
1347 	 * a new one (txg == TXG_INITIAL), all space is available now.
1348 	 * If we're adding space to an existing pool, the new space
1349 	 * does not become available until after this txg has synced.
1350 	 */
1351 	if (txg <= TXG_INITIAL)
1352 		metaslab_sync_done(ms, 0);
1353 
1354 	/*
1355 	 * If metaslab_debug_load is set and we're initializing a metaslab
1356 	 * that has an allocated space_map object then load the its space
1357 	 * map so that can verify frees.
1358 	 */
1359 	if (metaslab_debug_load && ms->ms_sm != NULL) {
1360 		mutex_enter(&ms->ms_lock);
1361 		VERIFY0(metaslab_load(ms));
1362 		mutex_exit(&ms->ms_lock);
1363 	}
1364 
1365 	if (txg != 0) {
1366 		vdev_dirty(vd, 0, NULL, txg);
1367 		vdev_dirty(vd, VDD_METASLAB, ms, txg);
1368 	}
1369 
1370 	*msp = ms;
1371 
1372 	return (0);
1373 }
1374 
1375 void
metaslab_fini(metaslab_t * msp)1376 metaslab_fini(metaslab_t *msp)
1377 {
1378 	metaslab_group_t *mg = msp->ms_group;
1379 
1380 	metaslab_group_remove(mg, msp);
1381 
1382 	mutex_enter(&msp->ms_lock);
1383 
1384 	VERIFY(msp->ms_group == NULL);
1385 	vdev_space_update(mg->mg_vd, -space_map_allocated(msp->ms_sm),
1386 	    0, -msp->ms_size);
1387 	space_map_close(msp->ms_sm);
1388 
1389 	metaslab_unload(msp);
1390 	range_tree_destroy(msp->ms_tree);
1391 
1392 	for (int t = 0; t < TXG_SIZE; t++) {
1393 		range_tree_destroy(msp->ms_alloctree[t]);
1394 		range_tree_destroy(msp->ms_freetree[t]);
1395 	}
1396 
1397 	for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1398 		range_tree_destroy(msp->ms_defertree[t]);
1399 	}
1400 
1401 	ASSERT0(msp->ms_deferspace);
1402 
1403 	mutex_exit(&msp->ms_lock);
1404 	cv_destroy(&msp->ms_load_cv);
1405 	mutex_destroy(&msp->ms_lock);
1406 
1407 	kmem_free(msp, sizeof (metaslab_t));
1408 }
1409 
1410 #define	FRAGMENTATION_TABLE_SIZE	17
1411 
1412 /*
1413  * This table defines a segment size based fragmentation metric that will
1414  * allow each metaslab to derive its own fragmentation value. This is done
1415  * by calculating the space in each bucket of the spacemap histogram and
1416  * multiplying that by the fragmetation metric in this table. Doing
1417  * this for all buckets and dividing it by the total amount of free
1418  * space in this metaslab (i.e. the total free space in all buckets) gives
1419  * us the fragmentation metric. This means that a high fragmentation metric
1420  * equates to most of the free space being comprised of small segments.
1421  * Conversely, if the metric is low, then most of the free space is in
1422  * large segments. A 10% change in fragmentation equates to approximately
1423  * double the number of segments.
1424  *
1425  * This table defines 0% fragmented space using 16MB segments. Testing has
1426  * shown that segments that are greater than or equal to 16MB do not suffer
1427  * from drastic performance problems. Using this value, we derive the rest
1428  * of the table. Since the fragmentation value is never stored on disk, it
1429  * is possible to change these calculations in the future.
1430  */
1431 int zfs_frag_table[FRAGMENTATION_TABLE_SIZE] = {
1432 	100,	/* 512B	*/
1433 	100,	/* 1K	*/
1434 	98,	/* 2K	*/
1435 	95,	/* 4K	*/
1436 	90,	/* 8K	*/
1437 	80,	/* 16K	*/
1438 	70,	/* 32K	*/
1439 	60,	/* 64K	*/
1440 	50,	/* 128K	*/
1441 	40,	/* 256K	*/
1442 	30,	/* 512K	*/
1443 	20,	/* 1M	*/
1444 	15,	/* 2M	*/
1445 	10,	/* 4M	*/
1446 	5,	/* 8M	*/
1447 	0	/* 16M	*/
1448 };
1449 
1450 /*
1451  * Calclate the metaslab's fragmentation metric. A return value
1452  * of ZFS_FRAG_INVALID means that the metaslab has not been upgraded and does
1453  * not support this metric. Otherwise, the return value should be in the
1454  * range [0, 100].
1455  */
1456 static uint64_t
metaslab_fragmentation(metaslab_t * msp)1457 metaslab_fragmentation(metaslab_t *msp)
1458 {
1459 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1460 	uint64_t fragmentation = 0;
1461 	uint64_t total = 0;
1462 	boolean_t feature_enabled = spa_feature_is_enabled(spa,
1463 	    SPA_FEATURE_SPACEMAP_HISTOGRAM);
1464 
1465 	if (!feature_enabled)
1466 		return (ZFS_FRAG_INVALID);
1467 
1468 	/*
1469 	 * A null space map means that the entire metaslab is free
1470 	 * and thus is not fragmented.
1471 	 */
1472 	if (msp->ms_sm == NULL)
1473 		return (0);
1474 
1475 	/*
1476 	 * If this metaslab's space_map has not been upgraded, flag it
1477 	 * so that we upgrade next time we encounter it.
1478 	 */
1479 	if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
1480 		uint64_t txg = spa_syncing_txg(spa);
1481 		vdev_t *vd = msp->ms_group->mg_vd;
1482 
1483 		if (spa_writeable(spa)) {
1484 			msp->ms_condense_wanted = B_TRUE;
1485 			vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
1486 			spa_dbgmsg(spa, "txg %llu, requesting force condense: "
1487 			    "msp %p, vd %p", txg, msp, vd);
1488 		}
1489 		return (ZFS_FRAG_INVALID);
1490 	}
1491 
1492 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1493 		uint64_t space = 0;
1494 		uint8_t shift = msp->ms_sm->sm_shift;
1495 		int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
1496 		    FRAGMENTATION_TABLE_SIZE - 1);
1497 
1498 		if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
1499 			continue;
1500 
1501 		space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
1502 		total += space;
1503 
1504 		ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
1505 		fragmentation += space * zfs_frag_table[idx];
1506 	}
1507 
1508 	if (total > 0)
1509 		fragmentation /= total;
1510 	ASSERT3U(fragmentation, <=, 100);
1511 	return (fragmentation);
1512 }
1513 
1514 /*
1515  * Compute a weight -- a selection preference value -- for the given metaslab.
1516  * This is based on the amount of free space, the level of fragmentation,
1517  * the LBA range, and whether the metaslab is loaded.
1518  */
1519 static uint64_t
metaslab_weight(metaslab_t * msp)1520 metaslab_weight(metaslab_t *msp)
1521 {
1522 	metaslab_group_t *mg = msp->ms_group;
1523 	vdev_t *vd = mg->mg_vd;
1524 	uint64_t weight, space;
1525 
1526 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1527 
1528 	/*
1529 	 * This vdev is in the process of being removed so there is nothing
1530 	 * for us to do here.
1531 	 */
1532 	if (vd->vdev_removing) {
1533 		ASSERT0(space_map_allocated(msp->ms_sm));
1534 		ASSERT0(vd->vdev_ms_shift);
1535 		return (0);
1536 	}
1537 
1538 	/*
1539 	 * The baseline weight is the metaslab's free space.
1540 	 */
1541 	space = msp->ms_size - space_map_allocated(msp->ms_sm);
1542 
1543 	msp->ms_fragmentation = metaslab_fragmentation(msp);
1544 	if (metaslab_fragmentation_factor_enabled &&
1545 	    msp->ms_fragmentation != ZFS_FRAG_INVALID) {
1546 		/*
1547 		 * Use the fragmentation information to inversely scale
1548 		 * down the baseline weight. We need to ensure that we
1549 		 * don't exclude this metaslab completely when it's 100%
1550 		 * fragmented. To avoid this we reduce the fragmented value
1551 		 * by 1.
1552 		 */
1553 		space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
1554 
1555 		/*
1556 		 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
1557 		 * this metaslab again. The fragmentation metric may have
1558 		 * decreased the space to something smaller than
1559 		 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
1560 		 * so that we can consume any remaining space.
1561 		 */
1562 		if (space > 0 && space < SPA_MINBLOCKSIZE)
1563 			space = SPA_MINBLOCKSIZE;
1564 	}
1565 	weight = space;
1566 
1567 	/*
1568 	 * Modern disks have uniform bit density and constant angular velocity.
1569 	 * Therefore, the outer recording zones are faster (higher bandwidth)
1570 	 * than the inner zones by the ratio of outer to inner track diameter,
1571 	 * which is typically around 2:1.  We account for this by assigning
1572 	 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
1573 	 * In effect, this means that we'll select the metaslab with the most
1574 	 * free bandwidth rather than simply the one with the most free space.
1575 	 */
1576 	if (metaslab_lba_weighting_enabled) {
1577 		weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
1578 		ASSERT(weight >= space && weight <= 2 * space);
1579 	}
1580 
1581 	/*
1582 	 * If this metaslab is one we're actively using, adjust its
1583 	 * weight to make it preferable to any inactive metaslab so
1584 	 * we'll polish it off. If the fragmentation on this metaslab
1585 	 * has exceed our threshold, then don't mark it active.
1586 	 */
1587 	if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
1588 	    msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
1589 		weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
1590 	}
1591 
1592 	return (weight);
1593 }
1594 
1595 static int
metaslab_activate(metaslab_t * msp,uint64_t activation_weight)1596 metaslab_activate(metaslab_t *msp, uint64_t activation_weight)
1597 {
1598 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1599 
1600 	if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
1601 		metaslab_load_wait(msp);
1602 		if (!msp->ms_loaded) {
1603 			int error = metaslab_load(msp);
1604 			if (error) {
1605 				metaslab_group_sort(msp->ms_group, msp, 0);
1606 				return (error);
1607 			}
1608 		}
1609 
1610 		metaslab_group_sort(msp->ms_group, msp,
1611 		    msp->ms_weight | activation_weight);
1612 	}
1613 	ASSERT(msp->ms_loaded);
1614 	ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
1615 
1616 	return (0);
1617 }
1618 
1619 static void
metaslab_passivate(metaslab_t * msp,uint64_t size)1620 metaslab_passivate(metaslab_t *msp, uint64_t size)
1621 {
1622 	/*
1623 	 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
1624 	 * this metaslab again.  In that case, it had better be empty,
1625 	 * or we would be leaving space on the table.
1626 	 */
1627 	ASSERT(size >= SPA_MINBLOCKSIZE || range_tree_space(msp->ms_tree) == 0);
1628 	metaslab_group_sort(msp->ms_group, msp, MIN(msp->ms_weight, size));
1629 	ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
1630 }
1631 
1632 static void
metaslab_preload(void * arg)1633 metaslab_preload(void *arg)
1634 {
1635 	metaslab_t *msp = arg;
1636 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1637 
1638 	ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
1639 
1640 	mutex_enter(&msp->ms_lock);
1641 	metaslab_load_wait(msp);
1642 	if (!msp->ms_loaded)
1643 		(void) metaslab_load(msp);
1644 
1645 	/*
1646 	 * Set the ms_access_txg value so that we don't unload it right away.
1647 	 */
1648 	msp->ms_access_txg = spa_syncing_txg(spa) + metaslab_unload_delay + 1;
1649 	mutex_exit(&msp->ms_lock);
1650 }
1651 
1652 static void
metaslab_group_preload(metaslab_group_t * mg)1653 metaslab_group_preload(metaslab_group_t *mg)
1654 {
1655 	spa_t *spa = mg->mg_vd->vdev_spa;
1656 	metaslab_t *msp;
1657 	avl_tree_t *t = &mg->mg_metaslab_tree;
1658 	int m = 0;
1659 
1660 	if (spa_shutting_down(spa) || !metaslab_preload_enabled) {
1661 		taskq_wait(mg->mg_taskq);
1662 		return;
1663 	}
1664 
1665 	mutex_enter(&mg->mg_lock);
1666 	/*
1667 	 * Load the next potential metaslabs
1668 	 */
1669 	msp = avl_first(t);
1670 	while (msp != NULL) {
1671 		metaslab_t *msp_next = AVL_NEXT(t, msp);
1672 
1673 		/*
1674 		 * We preload only the maximum number of metaslabs specified
1675 		 * by metaslab_preload_limit. If a metaslab is being forced
1676 		 * to condense then we preload it too. This will ensure
1677 		 * that force condensing happens in the next txg.
1678 		 */
1679 		if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
1680 			msp = msp_next;
1681 			continue;
1682 		}
1683 
1684 		/*
1685 		 * We must drop the metaslab group lock here to preserve
1686 		 * lock ordering with the ms_lock (when grabbing both
1687 		 * the mg_lock and the ms_lock, the ms_lock must be taken
1688 		 * first).  As a result, it is possible that the ordering
1689 		 * of the metaslabs within the avl tree may change before
1690 		 * we reacquire the lock. The metaslab cannot be removed from
1691 		 * the tree while we're in syncing context so it is safe to
1692 		 * drop the mg_lock here. If the metaslabs are reordered
1693 		 * nothing will break -- we just may end up loading a
1694 		 * less than optimal one.
1695 		 */
1696 		mutex_exit(&mg->mg_lock);
1697 		VERIFY(taskq_dispatch(mg->mg_taskq, metaslab_preload,
1698 		    msp, TQ_SLEEP) != 0);
1699 		mutex_enter(&mg->mg_lock);
1700 		msp = msp_next;
1701 	}
1702 	mutex_exit(&mg->mg_lock);
1703 }
1704 
1705 /*
1706  * Determine if the space map's on-disk footprint is past our tolerance
1707  * for inefficiency. We would like to use the following criteria to make
1708  * our decision:
1709  *
1710  * 1. The size of the space map object should not dramatically increase as a
1711  * result of writing out the free space range tree.
1712  *
1713  * 2. The minimal on-disk space map representation is zfs_condense_pct/100
1714  * times the size than the free space range tree representation
1715  * (i.e. zfs_condense_pct = 110 and in-core = 1MB, minimal = 1.1.MB).
1716  *
1717  * 3. The on-disk size of the space map should actually decrease.
1718  *
1719  * Checking the first condition is tricky since we don't want to walk
1720  * the entire AVL tree calculating the estimated on-disk size. Instead we
1721  * use the size-ordered range tree in the metaslab and calculate the
1722  * size required to write out the largest segment in our free tree. If the
1723  * size required to represent that segment on disk is larger than the space
1724  * map object then we avoid condensing this map.
1725  *
1726  * To determine the second criterion we use a best-case estimate and assume
1727  * each segment can be represented on-disk as a single 64-bit entry. We refer
1728  * to this best-case estimate as the space map's minimal form.
1729  *
1730  * Unfortunately, we cannot compute the on-disk size of the space map in this
1731  * context because we cannot accurately compute the effects of compression, etc.
1732  * Instead, we apply the heuristic described in the block comment for
1733  * zfs_metaslab_condense_block_threshold - we only condense if the space used
1734  * is greater than a threshold number of blocks.
1735  */
1736 static boolean_t
metaslab_should_condense(metaslab_t * msp)1737 metaslab_should_condense(metaslab_t *msp)
1738 {
1739 	space_map_t *sm = msp->ms_sm;
1740 	range_seg_t *rs;
1741 	uint64_t size, entries, segsz, object_size, optimal_size, record_size;
1742 	dmu_object_info_t doi;
1743 	uint64_t vdev_blocksize = 1 << msp->ms_group->mg_vd->vdev_ashift;
1744 
1745 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1746 	ASSERT(msp->ms_loaded);
1747 
1748 	/*
1749 	 * Use the ms_size_tree range tree, which is ordered by size, to
1750 	 * obtain the largest segment in the free tree. We always condense
1751 	 * metaslabs that are empty and metaslabs for which a condense
1752 	 * request has been made.
1753 	 */
1754 	rs = avl_last(&msp->ms_size_tree);
1755 	if (rs == NULL || msp->ms_condense_wanted)
1756 		return (B_TRUE);
1757 
1758 	/*
1759 	 * Calculate the number of 64-bit entries this segment would
1760 	 * require when written to disk. If this single segment would be
1761 	 * larger on-disk than the entire current on-disk structure, then
1762 	 * clearly condensing will increase the on-disk structure size.
1763 	 */
1764 	size = (rs->rs_end - rs->rs_start) >> sm->sm_shift;
1765 	entries = size / (MIN(size, SM_RUN_MAX));
1766 	segsz = entries * sizeof (uint64_t);
1767 
1768 	optimal_size = sizeof (uint64_t) * avl_numnodes(&msp->ms_tree->rt_root);
1769 	object_size = space_map_length(msp->ms_sm);
1770 
1771 	dmu_object_info_from_db(sm->sm_dbuf, &doi);
1772 	record_size = MAX(doi.doi_data_block_size, vdev_blocksize);
1773 
1774 	return (segsz <= object_size &&
1775 	    object_size >= (optimal_size * zfs_condense_pct / 100) &&
1776 	    object_size > zfs_metaslab_condense_block_threshold * record_size);
1777 }
1778 
1779 /*
1780  * Condense the on-disk space map representation to its minimized form.
1781  * The minimized form consists of a small number of allocations followed by
1782  * the entries of the free range tree.
1783  */
1784 static void
metaslab_condense(metaslab_t * msp,uint64_t txg,dmu_tx_t * tx)1785 metaslab_condense(metaslab_t *msp, uint64_t txg, dmu_tx_t *tx)
1786 {
1787 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1788 	range_tree_t *freetree = msp->ms_freetree[txg & TXG_MASK];
1789 	range_tree_t *condense_tree;
1790 	space_map_t *sm = msp->ms_sm;
1791 
1792 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1793 	ASSERT3U(spa_sync_pass(spa), ==, 1);
1794 	ASSERT(msp->ms_loaded);
1795 
1796 
1797 	spa_dbgmsg(spa, "condensing: txg %llu, msp[%llu] %p, vdev id %llu, "
1798 	    "spa %s, smp size %llu, segments %lu, forcing condense=%s", txg,
1799 	    msp->ms_id, msp, msp->ms_group->mg_vd->vdev_id,
1800 	    msp->ms_group->mg_vd->vdev_spa->spa_name,
1801 	    space_map_length(msp->ms_sm), avl_numnodes(&msp->ms_tree->rt_root),
1802 	    msp->ms_condense_wanted ? "TRUE" : "FALSE");
1803 
1804 	msp->ms_condense_wanted = B_FALSE;
1805 
1806 	/*
1807 	 * Create an range tree that is 100% allocated. We remove segments
1808 	 * that have been freed in this txg, any deferred frees that exist,
1809 	 * and any allocation in the future. Removing segments should be
1810 	 * a relatively inexpensive operation since we expect these trees to
1811 	 * have a small number of nodes.
1812 	 */
1813 	condense_tree = range_tree_create(NULL, NULL, &msp->ms_lock);
1814 	range_tree_add(condense_tree, msp->ms_start, msp->ms_size);
1815 
1816 	/*
1817 	 * Remove what's been freed in this txg from the condense_tree.
1818 	 * Since we're in sync_pass 1, we know that all the frees from
1819 	 * this txg are in the freetree.
1820 	 */
1821 	range_tree_walk(freetree, range_tree_remove, condense_tree);
1822 
1823 	for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1824 		range_tree_walk(msp->ms_defertree[t],
1825 		    range_tree_remove, condense_tree);
1826 	}
1827 
1828 	for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
1829 		range_tree_walk(msp->ms_alloctree[(txg + t) & TXG_MASK],
1830 		    range_tree_remove, condense_tree);
1831 	}
1832 
1833 	/*
1834 	 * We're about to drop the metaslab's lock thus allowing
1835 	 * other consumers to change it's content. Set the
1836 	 * metaslab's ms_condensing flag to ensure that
1837 	 * allocations on this metaslab do not occur while we're
1838 	 * in the middle of committing it to disk. This is only critical
1839 	 * for the ms_tree as all other range trees use per txg
1840 	 * views of their content.
1841 	 */
1842 	msp->ms_condensing = B_TRUE;
1843 
1844 	mutex_exit(&msp->ms_lock);
1845 	space_map_truncate(sm, tx);
1846 	mutex_enter(&msp->ms_lock);
1847 
1848 	/*
1849 	 * While we would ideally like to create a space_map representation
1850 	 * that consists only of allocation records, doing so can be
1851 	 * prohibitively expensive because the in-core free tree can be
1852 	 * large, and therefore computationally expensive to subtract
1853 	 * from the condense_tree. Instead we sync out two trees, a cheap
1854 	 * allocation only tree followed by the in-core free tree. While not
1855 	 * optimal, this is typically close to optimal, and much cheaper to
1856 	 * compute.
1857 	 */
1858 	space_map_write(sm, condense_tree, SM_ALLOC, tx);
1859 	range_tree_vacate(condense_tree, NULL, NULL);
1860 	range_tree_destroy(condense_tree);
1861 
1862 	space_map_write(sm, msp->ms_tree, SM_FREE, tx);
1863 	msp->ms_condensing = B_FALSE;
1864 }
1865 
1866 /*
1867  * Write a metaslab to disk in the context of the specified transaction group.
1868  */
1869 void
metaslab_sync(metaslab_t * msp,uint64_t txg)1870 metaslab_sync(metaslab_t *msp, uint64_t txg)
1871 {
1872 	metaslab_group_t *mg = msp->ms_group;
1873 	vdev_t *vd = mg->mg_vd;
1874 	spa_t *spa = vd->vdev_spa;
1875 	objset_t *mos = spa_meta_objset(spa);
1876 	range_tree_t *alloctree = msp->ms_alloctree[txg & TXG_MASK];
1877 	range_tree_t **freetree = &msp->ms_freetree[txg & TXG_MASK];
1878 	range_tree_t **freed_tree =
1879 	    &msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK];
1880 	dmu_tx_t *tx;
1881 	uint64_t object = space_map_object(msp->ms_sm);
1882 
1883 	ASSERT(!vd->vdev_ishole);
1884 
1885 	/*
1886 	 * This metaslab has just been added so there's no work to do now.
1887 	 */
1888 	if (*freetree == NULL) {
1889 		ASSERT3P(alloctree, ==, NULL);
1890 		return;
1891 	}
1892 
1893 	ASSERT3P(alloctree, !=, NULL);
1894 	ASSERT3P(*freetree, !=, NULL);
1895 	ASSERT3P(*freed_tree, !=, NULL);
1896 
1897 	/*
1898 	 * Normally, we don't want to process a metaslab if there
1899 	 * are no allocations or frees to perform. However, if the metaslab
1900 	 * is being forced to condense we need to let it through.
1901 	 */
1902 	if (range_tree_space(alloctree) == 0 &&
1903 	    range_tree_space(*freetree) == 0 &&
1904 	    !msp->ms_condense_wanted)
1905 		return;
1906 
1907 	/*
1908 	 * The only state that can actually be changing concurrently with
1909 	 * metaslab_sync() is the metaslab's ms_tree.  No other thread can
1910 	 * be modifying this txg's alloctree, freetree, freed_tree, or
1911 	 * space_map_phys_t. Therefore, we only hold ms_lock to satify
1912 	 * space_map ASSERTs. We drop it whenever we call into the DMU,
1913 	 * because the DMU can call down to us (e.g. via zio_free()) at
1914 	 * any time.
1915 	 */
1916 
1917 	tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
1918 
1919 	if (msp->ms_sm == NULL) {
1920 		uint64_t new_object;
1921 
1922 		new_object = space_map_alloc(mos, tx);
1923 		VERIFY3U(new_object, !=, 0);
1924 
1925 		VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
1926 		    msp->ms_start, msp->ms_size, vd->vdev_ashift,
1927 		    &msp->ms_lock));
1928 		ASSERT(msp->ms_sm != NULL);
1929 	}
1930 
1931 	mutex_enter(&msp->ms_lock);
1932 
1933 	/*
1934 	 * Note: metaslab_condense() clears the space_map's histogram.
1935 	 * Therefore we must verify and remove this histogram before
1936 	 * condensing.
1937 	 */
1938 	metaslab_group_histogram_verify(mg);
1939 	metaslab_class_histogram_verify(mg->mg_class);
1940 	metaslab_group_histogram_remove(mg, msp);
1941 
1942 	if (msp->ms_loaded && spa_sync_pass(spa) == 1 &&
1943 	    metaslab_should_condense(msp)) {
1944 		metaslab_condense(msp, txg, tx);
1945 	} else {
1946 		space_map_write(msp->ms_sm, alloctree, SM_ALLOC, tx);
1947 		space_map_write(msp->ms_sm, *freetree, SM_FREE, tx);
1948 	}
1949 
1950 	if (msp->ms_loaded) {
1951 		/*
1952 		 * When the space map is loaded, we have an accruate
1953 		 * histogram in the range tree. This gives us an opportunity
1954 		 * to bring the space map's histogram up-to-date so we clear
1955 		 * it first before updating it.
1956 		 */
1957 		space_map_histogram_clear(msp->ms_sm);
1958 		space_map_histogram_add(msp->ms_sm, msp->ms_tree, tx);
1959 	} else {
1960 		/*
1961 		 * Since the space map is not loaded we simply update the
1962 		 * exisiting histogram with what was freed in this txg. This
1963 		 * means that the on-disk histogram may not have an accurate
1964 		 * view of the free space but it's close enough to allow
1965 		 * us to make allocation decisions.
1966 		 */
1967 		space_map_histogram_add(msp->ms_sm, *freetree, tx);
1968 	}
1969 	metaslab_group_histogram_add(mg, msp);
1970 	metaslab_group_histogram_verify(mg);
1971 	metaslab_class_histogram_verify(mg->mg_class);
1972 
1973 	/*
1974 	 * For sync pass 1, we avoid traversing this txg's free range tree
1975 	 * and instead will just swap the pointers for freetree and
1976 	 * freed_tree. We can safely do this since the freed_tree is
1977 	 * guaranteed to be empty on the initial pass.
1978 	 */
1979 	if (spa_sync_pass(spa) == 1) {
1980 		range_tree_swap(freetree, freed_tree);
1981 	} else {
1982 		range_tree_vacate(*freetree, range_tree_add, *freed_tree);
1983 	}
1984 	range_tree_vacate(alloctree, NULL, NULL);
1985 
1986 	ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
1987 	ASSERT0(range_tree_space(msp->ms_freetree[txg & TXG_MASK]));
1988 
1989 	mutex_exit(&msp->ms_lock);
1990 
1991 	if (object != space_map_object(msp->ms_sm)) {
1992 		object = space_map_object(msp->ms_sm);
1993 		dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
1994 		    msp->ms_id, sizeof (uint64_t), &object, tx);
1995 	}
1996 	dmu_tx_commit(tx);
1997 }
1998 
1999 /*
2000  * Called after a transaction group has completely synced to mark
2001  * all of the metaslab's free space as usable.
2002  */
2003 void
metaslab_sync_done(metaslab_t * msp,uint64_t txg)2004 metaslab_sync_done(metaslab_t *msp, uint64_t txg)
2005 {
2006 	metaslab_group_t *mg = msp->ms_group;
2007 	vdev_t *vd = mg->mg_vd;
2008 	range_tree_t **freed_tree;
2009 	range_tree_t **defer_tree;
2010 	int64_t alloc_delta, defer_delta;
2011 
2012 	ASSERT(!vd->vdev_ishole);
2013 
2014 	mutex_enter(&msp->ms_lock);
2015 
2016 	/*
2017 	 * If this metaslab is just becoming available, initialize its
2018 	 * alloctrees, freetrees, and defertree and add its capacity to
2019 	 * the vdev.
2020 	 */
2021 	if (msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK] == NULL) {
2022 		for (int t = 0; t < TXG_SIZE; t++) {
2023 			ASSERT(msp->ms_alloctree[t] == NULL);
2024 			ASSERT(msp->ms_freetree[t] == NULL);
2025 
2026 			msp->ms_alloctree[t] = range_tree_create(NULL, msp,
2027 			    &msp->ms_lock);
2028 			msp->ms_freetree[t] = range_tree_create(NULL, msp,
2029 			    &msp->ms_lock);
2030 		}
2031 
2032 		for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2033 			ASSERT(msp->ms_defertree[t] == NULL);
2034 
2035 			msp->ms_defertree[t] = range_tree_create(NULL, msp,
2036 			    &msp->ms_lock);
2037 		}
2038 
2039 		vdev_space_update(vd, 0, 0, msp->ms_size);
2040 	}
2041 
2042 	freed_tree = &msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK];
2043 	defer_tree = &msp->ms_defertree[txg % TXG_DEFER_SIZE];
2044 
2045 	alloc_delta = space_map_alloc_delta(msp->ms_sm);
2046 	defer_delta = range_tree_space(*freed_tree) -
2047 	    range_tree_space(*defer_tree);
2048 
2049 	vdev_space_update(vd, alloc_delta + defer_delta, defer_delta, 0);
2050 
2051 	ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
2052 	ASSERT0(range_tree_space(msp->ms_freetree[txg & TXG_MASK]));
2053 
2054 	/*
2055 	 * If there's a metaslab_load() in progress, wait for it to complete
2056 	 * so that we have a consistent view of the in-core space map.
2057 	 */
2058 	metaslab_load_wait(msp);
2059 
2060 	/*
2061 	 * Move the frees from the defer_tree back to the free
2062 	 * range tree (if it's loaded). Swap the freed_tree and the
2063 	 * defer_tree -- this is safe to do because we've just emptied out
2064 	 * the defer_tree.
2065 	 */
2066 	range_tree_vacate(*defer_tree,
2067 	    msp->ms_loaded ? range_tree_add : NULL, msp->ms_tree);
2068 	range_tree_swap(freed_tree, defer_tree);
2069 
2070 	space_map_update(msp->ms_sm);
2071 
2072 	msp->ms_deferspace += defer_delta;
2073 	ASSERT3S(msp->ms_deferspace, >=, 0);
2074 	ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
2075 	if (msp->ms_deferspace != 0) {
2076 		/*
2077 		 * Keep syncing this metaslab until all deferred frees
2078 		 * are back in circulation.
2079 		 */
2080 		vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
2081 	}
2082 
2083 	if (msp->ms_loaded && msp->ms_access_txg < txg) {
2084 		for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
2085 			VERIFY0(range_tree_space(
2086 			    msp->ms_alloctree[(txg + t) & TXG_MASK]));
2087 		}
2088 
2089 		if (!metaslab_debug_unload)
2090 			metaslab_unload(msp);
2091 	}
2092 
2093 	metaslab_group_sort(mg, msp, metaslab_weight(msp));
2094 	mutex_exit(&msp->ms_lock);
2095 }
2096 
2097 void
metaslab_sync_reassess(metaslab_group_t * mg)2098 metaslab_sync_reassess(metaslab_group_t *mg)
2099 {
2100 	metaslab_group_alloc_update(mg);
2101 	mg->mg_fragmentation = metaslab_group_fragmentation(mg);
2102 
2103 	/*
2104 	 * Preload the next potential metaslabs
2105 	 */
2106 	metaslab_group_preload(mg);
2107 }
2108 
2109 static uint64_t
metaslab_distance(metaslab_t * msp,dva_t * dva)2110 metaslab_distance(metaslab_t *msp, dva_t *dva)
2111 {
2112 	uint64_t ms_shift = msp->ms_group->mg_vd->vdev_ms_shift;
2113 	uint64_t offset = DVA_GET_OFFSET(dva) >> ms_shift;
2114 	uint64_t start = msp->ms_id;
2115 
2116 	if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
2117 		return (1ULL << 63);
2118 
2119 	if (offset < start)
2120 		return ((start - offset) << ms_shift);
2121 	if (offset > start)
2122 		return ((offset - start) << ms_shift);
2123 	return (0);
2124 }
2125 
2126 static uint64_t
metaslab_group_alloc(metaslab_group_t * mg,uint64_t psize,uint64_t asize,uint64_t txg,uint64_t min_distance,dva_t * dva,int d)2127 metaslab_group_alloc(metaslab_group_t *mg, uint64_t psize, uint64_t asize,
2128     uint64_t txg, uint64_t min_distance, dva_t *dva, int d)
2129 {
2130 	spa_t *spa = mg->mg_vd->vdev_spa;
2131 	metaslab_t *msp = NULL;
2132 	uint64_t offset = -1ULL;
2133 	avl_tree_t *t = &mg->mg_metaslab_tree;
2134 	uint64_t activation_weight;
2135 	uint64_t target_distance;
2136 	int i;
2137 
2138 	activation_weight = METASLAB_WEIGHT_PRIMARY;
2139 	for (i = 0; i < d; i++) {
2140 		if (DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
2141 			activation_weight = METASLAB_WEIGHT_SECONDARY;
2142 			break;
2143 		}
2144 	}
2145 
2146 	for (;;) {
2147 		boolean_t was_active;
2148 
2149 		mutex_enter(&mg->mg_lock);
2150 		for (msp = avl_first(t); msp; msp = AVL_NEXT(t, msp)) {
2151 			if (msp->ms_weight < asize) {
2152 				spa_dbgmsg(spa, "%s: failed to meet weight "
2153 				    "requirement: vdev %llu, txg %llu, mg %p, "
2154 				    "msp %p, psize %llu, asize %llu, "
2155 				    "weight %llu", spa_name(spa),
2156 				    mg->mg_vd->vdev_id, txg,
2157 				    mg, msp, psize, asize, msp->ms_weight);
2158 				mutex_exit(&mg->mg_lock);
2159 				return (-1ULL);
2160 			}
2161 
2162 			/*
2163 			 * If the selected metaslab is condensing, skip it.
2164 			 */
2165 			if (msp->ms_condensing)
2166 				continue;
2167 
2168 			was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
2169 			if (activation_weight == METASLAB_WEIGHT_PRIMARY)
2170 				break;
2171 
2172 			target_distance = min_distance +
2173 			    (space_map_allocated(msp->ms_sm) != 0 ? 0 :
2174 			    min_distance >> 1);
2175 
2176 			for (i = 0; i < d; i++)
2177 				if (metaslab_distance(msp, &dva[i]) <
2178 				    target_distance)
2179 					break;
2180 			if (i == d)
2181 				break;
2182 		}
2183 		mutex_exit(&mg->mg_lock);
2184 		if (msp == NULL)
2185 			return (-1ULL);
2186 
2187 		mutex_enter(&msp->ms_lock);
2188 
2189 		/*
2190 		 * Ensure that the metaslab we have selected is still
2191 		 * capable of handling our request. It's possible that
2192 		 * another thread may have changed the weight while we
2193 		 * were blocked on the metaslab lock.
2194 		 */
2195 		if (msp->ms_weight < asize || (was_active &&
2196 		    !(msp->ms_weight & METASLAB_ACTIVE_MASK) &&
2197 		    activation_weight == METASLAB_WEIGHT_PRIMARY)) {
2198 			mutex_exit(&msp->ms_lock);
2199 			continue;
2200 		}
2201 
2202 		if ((msp->ms_weight & METASLAB_WEIGHT_SECONDARY) &&
2203 		    activation_weight == METASLAB_WEIGHT_PRIMARY) {
2204 			metaslab_passivate(msp,
2205 			    msp->ms_weight & ~METASLAB_ACTIVE_MASK);
2206 			mutex_exit(&msp->ms_lock);
2207 			continue;
2208 		}
2209 
2210 		if (metaslab_activate(msp, activation_weight) != 0) {
2211 			mutex_exit(&msp->ms_lock);
2212 			continue;
2213 		}
2214 
2215 		/*
2216 		 * If this metaslab is currently condensing then pick again as
2217 		 * we can't manipulate this metaslab until it's committed
2218 		 * to disk.
2219 		 */
2220 		if (msp->ms_condensing) {
2221 			mutex_exit(&msp->ms_lock);
2222 			continue;
2223 		}
2224 
2225 		if ((offset = metaslab_block_alloc(msp, asize)) != -1ULL)
2226 			break;
2227 
2228 		metaslab_passivate(msp, metaslab_block_maxsize(msp));
2229 		mutex_exit(&msp->ms_lock);
2230 	}
2231 
2232 	if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
2233 		vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
2234 
2235 	range_tree_add(msp->ms_alloctree[txg & TXG_MASK], offset, asize);
2236 	msp->ms_access_txg = txg + metaslab_unload_delay;
2237 
2238 	mutex_exit(&msp->ms_lock);
2239 
2240 	return (offset);
2241 }
2242 
2243 /*
2244  * Allocate a block for the specified i/o.
2245  */
2246 static 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)2247 metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
2248     dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags)
2249 {
2250 	metaslab_group_t *mg, *rotor;
2251 	vdev_t *vd;
2252 	int dshift = 3;
2253 	int all_zero;
2254 	int zio_lock = B_FALSE;
2255 	boolean_t allocatable;
2256 	uint64_t offset = -1ULL;
2257 	uint64_t asize;
2258 	uint64_t distance;
2259 
2260 	ASSERT(!DVA_IS_VALID(&dva[d]));
2261 
2262 	/*
2263 	 * For testing, make some blocks above a certain size be gang blocks.
2264 	 */
2265 	if (psize >= metaslab_gang_bang && (ddi_get_lbolt() & 3) == 0)
2266 		return (SET_ERROR(ENOSPC));
2267 
2268 	/*
2269 	 * Start at the rotor and loop through all mgs until we find something.
2270 	 * Note that there's no locking on mc_rotor or mc_aliquot because
2271 	 * nothing actually breaks if we miss a few updates -- we just won't
2272 	 * allocate quite as evenly.  It all balances out over time.
2273 	 *
2274 	 * If we are doing ditto or log blocks, try to spread them across
2275 	 * consecutive vdevs.  If we're forced to reuse a vdev before we've
2276 	 * allocated all of our ditto blocks, then try and spread them out on
2277 	 * that vdev as much as possible.  If it turns out to not be possible,
2278 	 * gradually lower our standards until anything becomes acceptable.
2279 	 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
2280 	 * gives us hope of containing our fault domains to something we're
2281 	 * able to reason about.  Otherwise, any two top-level vdev failures
2282 	 * will guarantee the loss of data.  With consecutive allocation,
2283 	 * only two adjacent top-level vdev failures will result in data loss.
2284 	 *
2285 	 * If we are doing gang blocks (hintdva is non-NULL), try to keep
2286 	 * ourselves on the same vdev as our gang block header.  That
2287 	 * way, we can hope for locality in vdev_cache, plus it makes our
2288 	 * fault domains something tractable.
2289 	 */
2290 	if (hintdva) {
2291 		vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
2292 
2293 		/*
2294 		 * It's possible the vdev we're using as the hint no
2295 		 * longer exists (i.e. removed). Consult the rotor when
2296 		 * all else fails.
2297 		 */
2298 		if (vd != NULL) {
2299 			mg = vd->vdev_mg;
2300 
2301 			if (flags & METASLAB_HINTBP_AVOID &&
2302 			    mg->mg_next != NULL)
2303 				mg = mg->mg_next;
2304 		} else {
2305 			mg = mc->mc_rotor;
2306 		}
2307 	} else if (d != 0) {
2308 		vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
2309 		mg = vd->vdev_mg->mg_next;
2310 	} else {
2311 		mg = mc->mc_rotor;
2312 	}
2313 
2314 	/*
2315 	 * If the hint put us into the wrong metaslab class, or into a
2316 	 * metaslab group that has been passivated, just follow the rotor.
2317 	 */
2318 	if (mg->mg_class != mc || mg->mg_activation_count <= 0)
2319 		mg = mc->mc_rotor;
2320 
2321 	rotor = mg;
2322 top:
2323 	all_zero = B_TRUE;
2324 	do {
2325 		ASSERT(mg->mg_activation_count == 1);
2326 
2327 		vd = mg->mg_vd;
2328 
2329 		/*
2330 		 * Don't allocate from faulted devices.
2331 		 */
2332 		if (zio_lock) {
2333 			spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
2334 			allocatable = vdev_allocatable(vd);
2335 			spa_config_exit(spa, SCL_ZIO, FTAG);
2336 		} else {
2337 			allocatable = vdev_allocatable(vd);
2338 		}
2339 
2340 		/*
2341 		 * Determine if the selected metaslab group is eligible
2342 		 * for allocations. If we're ganging or have requested
2343 		 * an allocation for the smallest gang block size
2344 		 * then we don't want to avoid allocating to the this
2345 		 * metaslab group. If we're in this condition we should
2346 		 * try to allocate from any device possible so that we
2347 		 * don't inadvertently return ENOSPC and suspend the pool
2348 		 * even though space is still available.
2349 		 */
2350 		if (allocatable && CAN_FASTGANG(flags) &&
2351 		    psize > SPA_GANGBLOCKSIZE)
2352 			allocatable = metaslab_group_allocatable(mg);
2353 
2354 		if (!allocatable)
2355 			goto next;
2356 
2357 		/*
2358 		 * Avoid writing single-copy data to a failing vdev
2359 		 * unless the user instructs us that it is okay.
2360 		 */
2361 		if ((vd->vdev_stat.vs_write_errors > 0 ||
2362 		    vd->vdev_state < VDEV_STATE_HEALTHY) &&
2363 		    d == 0 && dshift == 3 && vd->vdev_children == 0) {
2364 			all_zero = B_FALSE;
2365 			goto next;
2366 		}
2367 
2368 		ASSERT(mg->mg_class == mc);
2369 
2370 		distance = vd->vdev_asize >> dshift;
2371 		if (distance <= (1ULL << vd->vdev_ms_shift))
2372 			distance = 0;
2373 		else
2374 			all_zero = B_FALSE;
2375 
2376 		asize = vdev_psize_to_asize(vd, psize);
2377 		ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
2378 
2379 		offset = metaslab_group_alloc(mg, psize, asize, txg, distance,
2380 		    dva, d);
2381 		if (offset != -1ULL) {
2382 			/*
2383 			 * If we've just selected this metaslab group,
2384 			 * figure out whether the corresponding vdev is
2385 			 * over- or under-used relative to the pool,
2386 			 * and set an allocation bias to even it out.
2387 			 */
2388 			if (mc->mc_aliquot == 0 && metaslab_bias_enabled) {
2389 				vdev_stat_t *vs = &vd->vdev_stat;
2390 				int64_t vu, cu;
2391 
2392 				vu = (vs->vs_alloc * 100) / (vs->vs_space + 1);
2393 				cu = (mc->mc_alloc * 100) / (mc->mc_space + 1);
2394 
2395 				/*
2396 				 * Calculate how much more or less we should
2397 				 * try to allocate from this device during
2398 				 * this iteration around the rotor.
2399 				 * For example, if a device is 80% full
2400 				 * and the pool is 20% full then we should
2401 				 * reduce allocations by 60% on this device.
2402 				 *
2403 				 * mg_bias = (20 - 80) * 512K / 100 = -307K
2404 				 *
2405 				 * This reduces allocations by 307K for this
2406 				 * iteration.
2407 				 */
2408 				mg->mg_bias = ((cu - vu) *
2409 				    (int64_t)mg->mg_aliquot) / 100;
2410 			} else if (!metaslab_bias_enabled) {
2411 				mg->mg_bias = 0;
2412 			}
2413 
2414 			if (atomic_add_64_nv(&mc->mc_aliquot, asize) >=
2415 			    mg->mg_aliquot + mg->mg_bias) {
2416 				mc->mc_rotor = mg->mg_next;
2417 				mc->mc_aliquot = 0;
2418 			}
2419 
2420 			DVA_SET_VDEV(&dva[d], vd->vdev_id);
2421 			DVA_SET_OFFSET(&dva[d], offset);
2422 			DVA_SET_GANG(&dva[d], !!(flags & METASLAB_GANG_HEADER));
2423 			DVA_SET_ASIZE(&dva[d], asize);
2424 
2425 			return (0);
2426 		}
2427 next:
2428 		mc->mc_rotor = mg->mg_next;
2429 		mc->mc_aliquot = 0;
2430 	} while ((mg = mg->mg_next) != rotor);
2431 
2432 	if (!all_zero) {
2433 		dshift++;
2434 		ASSERT(dshift < 64);
2435 		goto top;
2436 	}
2437 
2438 	if (!allocatable && !zio_lock) {
2439 		dshift = 3;
2440 		zio_lock = B_TRUE;
2441 		goto top;
2442 	}
2443 
2444 	bzero(&dva[d], sizeof (dva_t));
2445 
2446 	return (SET_ERROR(ENOSPC));
2447 }
2448 
2449 /*
2450  * Free the block represented by DVA in the context of the specified
2451  * transaction group.
2452  */
2453 static void
metaslab_free_dva(spa_t * spa,const dva_t * dva,uint64_t txg,boolean_t now)2454 metaslab_free_dva(spa_t *spa, const dva_t *dva, uint64_t txg, boolean_t now)
2455 {
2456 	uint64_t vdev = DVA_GET_VDEV(dva);
2457 	uint64_t offset = DVA_GET_OFFSET(dva);
2458 	uint64_t size = DVA_GET_ASIZE(dva);
2459 	vdev_t *vd;
2460 	metaslab_t *msp;
2461 
2462 	ASSERT(DVA_IS_VALID(dva));
2463 
2464 	if (txg > spa_freeze_txg(spa))
2465 		return;
2466 
2467 	if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
2468 	    (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
2469 		cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
2470 		    (u_longlong_t)vdev, (u_longlong_t)offset);
2471 		ASSERT(0);
2472 		return;
2473 	}
2474 
2475 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
2476 
2477 	if (DVA_GET_GANG(dva))
2478 		size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
2479 
2480 	mutex_enter(&msp->ms_lock);
2481 
2482 	if (now) {
2483 		range_tree_remove(msp->ms_alloctree[txg & TXG_MASK],
2484 		    offset, size);
2485 
2486 		VERIFY(!msp->ms_condensing);
2487 		VERIFY3U(offset, >=, msp->ms_start);
2488 		VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
2489 		VERIFY3U(range_tree_space(msp->ms_tree) + size, <=,
2490 		    msp->ms_size);
2491 		VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
2492 		VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
2493 		range_tree_add(msp->ms_tree, offset, size);
2494 	} else {
2495 		if (range_tree_space(msp->ms_freetree[txg & TXG_MASK]) == 0)
2496 			vdev_dirty(vd, VDD_METASLAB, msp, txg);
2497 		range_tree_add(msp->ms_freetree[txg & TXG_MASK],
2498 		    offset, size);
2499 	}
2500 
2501 	mutex_exit(&msp->ms_lock);
2502 }
2503 
2504 /*
2505  * Intent log support: upon opening the pool after a crash, notify the SPA
2506  * of blocks that the intent log has allocated for immediate write, but
2507  * which are still considered free by the SPA because the last transaction
2508  * group didn't commit yet.
2509  */
2510 static int
metaslab_claim_dva(spa_t * spa,const dva_t * dva,uint64_t txg)2511 metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
2512 {
2513 	uint64_t vdev = DVA_GET_VDEV(dva);
2514 	uint64_t offset = DVA_GET_OFFSET(dva);
2515 	uint64_t size = DVA_GET_ASIZE(dva);
2516 	vdev_t *vd;
2517 	metaslab_t *msp;
2518 	int error = 0;
2519 
2520 	ASSERT(DVA_IS_VALID(dva));
2521 
2522 	if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
2523 	    (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
2524 		return (SET_ERROR(ENXIO));
2525 
2526 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
2527 
2528 	if (DVA_GET_GANG(dva))
2529 		size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
2530 
2531 	mutex_enter(&msp->ms_lock);
2532 
2533 	if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded)
2534 		error = metaslab_activate(msp, METASLAB_WEIGHT_SECONDARY);
2535 
2536 	if (error == 0 && !range_tree_contains(msp->ms_tree, offset, size))
2537 		error = SET_ERROR(ENOENT);
2538 
2539 	if (error || txg == 0) {	/* txg == 0 indicates dry run */
2540 		mutex_exit(&msp->ms_lock);
2541 		return (error);
2542 	}
2543 
2544 	VERIFY(!msp->ms_condensing);
2545 	VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
2546 	VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
2547 	VERIFY3U(range_tree_space(msp->ms_tree) - size, <=, msp->ms_size);
2548 	range_tree_remove(msp->ms_tree, offset, size);
2549 
2550 	if (spa_writeable(spa)) {	/* don't dirty if we're zdb(1M) */
2551 		if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
2552 			vdev_dirty(vd, VDD_METASLAB, msp, txg);
2553 		range_tree_add(msp->ms_alloctree[txg & TXG_MASK], offset, size);
2554 	}
2555 
2556 	mutex_exit(&msp->ms_lock);
2557 
2558 	return (0);
2559 }
2560 
2561 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)2562 metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
2563     int ndvas, uint64_t txg, blkptr_t *hintbp, int flags)
2564 {
2565 	dva_t *dva = bp->blk_dva;
2566 	dva_t *hintdva = hintbp->blk_dva;
2567 	int error = 0;
2568 
2569 	ASSERT(bp->blk_birth == 0);
2570 	ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
2571 
2572 	spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
2573 
2574 	if (mc->mc_rotor == NULL) {	/* no vdevs in this class */
2575 		spa_config_exit(spa, SCL_ALLOC, FTAG);
2576 		return (SET_ERROR(ENOSPC));
2577 	}
2578 
2579 	ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
2580 	ASSERT(BP_GET_NDVAS(bp) == 0);
2581 	ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
2582 
2583 	for (int d = 0; d < ndvas; d++) {
2584 		error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
2585 		    txg, flags);
2586 		if (error != 0) {
2587 			for (d--; d >= 0; d--) {
2588 				metaslab_free_dva(spa, &dva[d], txg, B_TRUE);
2589 				bzero(&dva[d], sizeof (dva_t));
2590 			}
2591 			spa_config_exit(spa, SCL_ALLOC, FTAG);
2592 			return (error);
2593 		}
2594 	}
2595 	ASSERT(error == 0);
2596 	ASSERT(BP_GET_NDVAS(bp) == ndvas);
2597 
2598 	spa_config_exit(spa, SCL_ALLOC, FTAG);
2599 
2600 	BP_SET_BIRTH(bp, txg, txg);
2601 
2602 	return (0);
2603 }
2604 
2605 void
metaslab_free(spa_t * spa,const blkptr_t * bp,uint64_t txg,boolean_t now)2606 metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
2607 {
2608 	const dva_t *dva = bp->blk_dva;
2609 	int ndvas = BP_GET_NDVAS(bp);
2610 
2611 	ASSERT(!BP_IS_HOLE(bp));
2612 	ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
2613 
2614 	spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
2615 
2616 	for (int d = 0; d < ndvas; d++)
2617 		metaslab_free_dva(spa, &dva[d], txg, now);
2618 
2619 	spa_config_exit(spa, SCL_FREE, FTAG);
2620 }
2621 
2622 int
metaslab_claim(spa_t * spa,const blkptr_t * bp,uint64_t txg)2623 metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
2624 {
2625 	const dva_t *dva = bp->blk_dva;
2626 	int ndvas = BP_GET_NDVAS(bp);
2627 	int error = 0;
2628 
2629 	ASSERT(!BP_IS_HOLE(bp));
2630 
2631 	if (txg != 0) {
2632 		/*
2633 		 * First do a dry run to make sure all DVAs are claimable,
2634 		 * so we don't have to unwind from partial failures below.
2635 		 */
2636 		if ((error = metaslab_claim(spa, bp, 0)) != 0)
2637 			return (error);
2638 	}
2639 
2640 	spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
2641 
2642 	for (int d = 0; d < ndvas; d++)
2643 		if ((error = metaslab_claim_dva(spa, &dva[d], txg)) != 0)
2644 			break;
2645 
2646 	spa_config_exit(spa, SCL_ALLOC, FTAG);
2647 
2648 	ASSERT(error == 0 || txg == 0);
2649 
2650 	return (error);
2651 }
2652 
2653 void
metaslab_check_free(spa_t * spa,const blkptr_t * bp)2654 metaslab_check_free(spa_t *spa, const blkptr_t *bp)
2655 {
2656 	if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
2657 		return;
2658 
2659 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2660 	for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
2661 		uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
2662 		vdev_t *vd = vdev_lookup_top(spa, vdev);
2663 		uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
2664 		uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
2665 		metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
2666 
2667 		if (msp->ms_loaded)
2668 			range_tree_verify(msp->ms_tree, offset, size);
2669 
2670 		for (int j = 0; j < TXG_SIZE; j++)
2671 			range_tree_verify(msp->ms_freetree[j], offset, size);
2672 		for (int j = 0; j < TXG_DEFER_SIZE; j++)
2673 			range_tree_verify(msp->ms_defertree[j], offset, size);
2674 	}
2675 	spa_config_exit(spa, SCL_VDEV, FTAG);
2676 }
2677