xref: /titanic_44/usr/src/uts/common/fs/zfs/metaslab.c (revision 1e9bd7ec42f2d3bf854c2da35310901194833267)
1fa9e4066Sahrens /*
2fa9e4066Sahrens  * CDDL HEADER START
3fa9e4066Sahrens  *
4fa9e4066Sahrens  * The contents of this file are subject to the terms of the
5ea8dc4b6Seschrock  * Common Development and Distribution License (the "License").
6ea8dc4b6Seschrock  * You may not use this file except in compliance with the License.
7fa9e4066Sahrens  *
8fa9e4066Sahrens  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9fa9e4066Sahrens  * or http://www.opensolaris.org/os/licensing.
10fa9e4066Sahrens  * See the License for the specific language governing permissions
11fa9e4066Sahrens  * and limitations under the License.
12fa9e4066Sahrens  *
13fa9e4066Sahrens  * When distributing Covered Code, include this CDDL HEADER in each
14fa9e4066Sahrens  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15fa9e4066Sahrens  * If applicable, add the following below this CDDL HEADER, with the
16fa9e4066Sahrens  * fields enclosed by brackets "[]" replaced with your own identifying
17fa9e4066Sahrens  * information: Portions Copyright [yyyy] [name of copyright owner]
18fa9e4066Sahrens  *
19fa9e4066Sahrens  * CDDL HEADER END
20fa9e4066Sahrens  */
21fa9e4066Sahrens /*
228d18220dSMark J Musante  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23bf16b11eSMatthew Ahrens  * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
249dc3941cSSašo Kiselkov  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
25fa9e4066Sahrens  */
26fa9e4066Sahrens 
27fa9e4066Sahrens #include <sys/zfs_context.h>
28fa9e4066Sahrens #include <sys/dmu.h>
29fa9e4066Sahrens #include <sys/dmu_tx.h>
30fa9e4066Sahrens #include <sys/space_map.h>
31fa9e4066Sahrens #include <sys/metaslab_impl.h>
32fa9e4066Sahrens #include <sys/vdev_impl.h>
33fa9e4066Sahrens #include <sys/zio.h>
340713e232SGeorge Wilson #include <sys/spa_impl.h>
352e4c9986SGeorge Wilson #include <sys/zfeature.h>
36fa9e4066Sahrens 
3709c9d376SGeorge Wilson /*
3809c9d376SGeorge Wilson  * Allow allocations to switch to gang blocks quickly. We do this to
3909c9d376SGeorge Wilson  * avoid having to load lots of space_maps in a given txg. There are,
4009c9d376SGeorge Wilson  * however, some cases where we want to avoid "fast" ganging and instead
4109c9d376SGeorge Wilson  * we want to do an exhaustive search of all metaslabs on this device.
42b6240e83SGeorge Wilson  * Currently we don't allow any gang, slog, or dump device related allocations
4309c9d376SGeorge Wilson  * to "fast" gang.
4409c9d376SGeorge Wilson  */
4509c9d376SGeorge Wilson #define	CAN_FASTGANG(flags) \
4609c9d376SGeorge Wilson 	(!((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER | \
4709c9d376SGeorge Wilson 	METASLAB_GANG_AVOID)))
4809c9d376SGeorge Wilson 
490713e232SGeorge Wilson #define	METASLAB_WEIGHT_PRIMARY		(1ULL << 63)
500713e232SGeorge Wilson #define	METASLAB_WEIGHT_SECONDARY	(1ULL << 62)
510713e232SGeorge Wilson #define	METASLAB_ACTIVE_MASK		\
520713e232SGeorge Wilson 	(METASLAB_WEIGHT_PRIMARY | METASLAB_WEIGHT_SECONDARY)
530713e232SGeorge Wilson 
5413506d1eSmaybee uint64_t metaslab_aliquot = 512ULL << 10;
55e05725b1Sbonwick uint64_t metaslab_gang_bang = SPA_MAXBLOCKSIZE + 1;	/* force gang blocks */
5613506d1eSmaybee 
57fa9e4066Sahrens /*
5816a4a807SGeorge Wilson  * The in-core space map representation is more compact than its on-disk form.
5916a4a807SGeorge Wilson  * The zfs_condense_pct determines how much more compact the in-core
6016a4a807SGeorge Wilson  * space_map representation must be before we compact it on-disk.
6116a4a807SGeorge Wilson  * Values should be greater than or equal to 100.
6216a4a807SGeorge Wilson  */
6316a4a807SGeorge Wilson int zfs_condense_pct = 200;
6416a4a807SGeorge Wilson 
6516a4a807SGeorge Wilson /*
662a104a52SAlex Reece  * Condensing a metaslab is not guaranteed to actually reduce the amount of
672a104a52SAlex Reece  * space used on disk. In particular, a space map uses data in increments of
68b1be2892SMatthew Ahrens  * MAX(1 << ashift, space_map_blksize), so a metaslab might use the
692a104a52SAlex Reece  * same number of blocks after condensing. Since the goal of condensing is to
702a104a52SAlex Reece  * reduce the number of IOPs required to read the space map, we only want to
712a104a52SAlex Reece  * condense when we can be sure we will reduce the number of blocks used by the
722a104a52SAlex Reece  * space map. Unfortunately, we cannot precisely compute whether or not this is
732a104a52SAlex Reece  * the case in metaslab_should_condense since we are holding ms_lock. Instead,
742a104a52SAlex Reece  * we apply the following heuristic: do not condense a spacemap unless the
752a104a52SAlex Reece  * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
762a104a52SAlex Reece  * blocks.
772a104a52SAlex Reece  */
782a104a52SAlex Reece int zfs_metaslab_condense_block_threshold = 4;
792a104a52SAlex Reece 
802a104a52SAlex Reece /*
8122e30981SGeorge Wilson  * The zfs_mg_noalloc_threshold defines which metaslab groups should
8222e30981SGeorge Wilson  * be eligible for allocation. The value is defined as a percentage of
832e4c9986SGeorge Wilson  * free space. Metaslab groups that have more free space than
8422e30981SGeorge Wilson  * zfs_mg_noalloc_threshold are always eligible for allocations. Once
8522e30981SGeorge Wilson  * a metaslab group's free space is less than or equal to the
8622e30981SGeorge Wilson  * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
8722e30981SGeorge Wilson  * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
8822e30981SGeorge Wilson  * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
8922e30981SGeorge Wilson  * groups are allowed to accept allocations. Gang blocks are always
9022e30981SGeorge Wilson  * eligible to allocate on any metaslab group. The default value of 0 means
9122e30981SGeorge Wilson  * no metaslab group will be excluded based on this criterion.
9222e30981SGeorge Wilson  */
9322e30981SGeorge Wilson int zfs_mg_noalloc_threshold = 0;
9409c9d376SGeorge Wilson 
9509c9d376SGeorge Wilson /*
962e4c9986SGeorge Wilson  * Metaslab groups are considered eligible for allocations if their
972e4c9986SGeorge Wilson  * fragmenation metric (measured as a percentage) is less than or equal to
982e4c9986SGeorge Wilson  * zfs_mg_fragmentation_threshold. If a metaslab group exceeds this threshold
992e4c9986SGeorge Wilson  * then it will be skipped unless all metaslab groups within the metaslab
1002e4c9986SGeorge Wilson  * class have also crossed this threshold.
1012e4c9986SGeorge Wilson  */
1022e4c9986SGeorge Wilson int zfs_mg_fragmentation_threshold = 85;
1032e4c9986SGeorge Wilson 
1042e4c9986SGeorge Wilson /*
1052e4c9986SGeorge Wilson  * Allow metaslabs to keep their active state as long as their fragmentation
1062e4c9986SGeorge Wilson  * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
1072e4c9986SGeorge Wilson  * active metaslab that exceeds this threshold will no longer keep its active
1082e4c9986SGeorge Wilson  * status allowing better metaslabs to be selected.
1092e4c9986SGeorge Wilson  */
1102e4c9986SGeorge Wilson int zfs_metaslab_fragmentation_threshold = 70;
1112e4c9986SGeorge Wilson 
1122e4c9986SGeorge Wilson /*
1130713e232SGeorge Wilson  * When set will load all metaslabs when pool is first opened.
114b24ab676SJeff Bonwick  */
1150713e232SGeorge Wilson int metaslab_debug_load = 0;
1160713e232SGeorge Wilson 
1170713e232SGeorge Wilson /*
1180713e232SGeorge Wilson  * When set will prevent metaslabs from being unloaded.
1190713e232SGeorge Wilson  */
1200713e232SGeorge Wilson int metaslab_debug_unload = 0;
121b24ab676SJeff Bonwick 
122b24ab676SJeff Bonwick /*
123d6e555bdSGeorge Wilson  * Minimum size which forces the dynamic allocator to change
124d6e555bdSGeorge Wilson  * it's allocation strategy.  Once the space map cannot satisfy
125d6e555bdSGeorge Wilson  * an allocation of this size then it switches to using more
126d6e555bdSGeorge Wilson  * aggressive strategy (i.e search by size rather than offset).
127d6e555bdSGeorge Wilson  */
128b5152584SMatthew Ahrens uint64_t metaslab_df_alloc_threshold = SPA_OLD_MAXBLOCKSIZE;
129d6e555bdSGeorge Wilson 
130d6e555bdSGeorge Wilson /*
131d6e555bdSGeorge Wilson  * The minimum free space, in percent, which must be available
132d6e555bdSGeorge Wilson  * in a space map to continue allocations in a first-fit fashion.
133d6e555bdSGeorge Wilson  * Once the space_map's free space drops below this level we dynamically
134d6e555bdSGeorge Wilson  * switch to using best-fit allocations.
135d6e555bdSGeorge Wilson  */
13680eb36f2SGeorge Wilson int metaslab_df_free_pct = 4;
13780eb36f2SGeorge Wilson 
13880eb36f2SGeorge Wilson /*
13980eb36f2SGeorge Wilson  * A metaslab is considered "free" if it contains a contiguous
14080eb36f2SGeorge Wilson  * segment which is greater than metaslab_min_alloc_size.
14180eb36f2SGeorge Wilson  */
14280eb36f2SGeorge Wilson uint64_t metaslab_min_alloc_size = DMU_MAX_ACCESS;
14380eb36f2SGeorge Wilson 
14480eb36f2SGeorge Wilson /*
1450713e232SGeorge Wilson  * Percentage of all cpus that can be used by the metaslab taskq.
14680eb36f2SGeorge Wilson  */
1470713e232SGeorge Wilson int metaslab_load_pct = 50;
14880eb36f2SGeorge Wilson 
14980eb36f2SGeorge Wilson /*
1500713e232SGeorge Wilson  * Determines how many txgs a metaslab may remain loaded without having any
1510713e232SGeorge Wilson  * allocations from it. As long as a metaslab continues to be used we will
1520713e232SGeorge Wilson  * keep it loaded.
15380eb36f2SGeorge Wilson  */
1540713e232SGeorge Wilson int metaslab_unload_delay = TXG_SIZE * 2;
155d6e555bdSGeorge Wilson 
156d6e555bdSGeorge Wilson /*
1570713e232SGeorge Wilson  * Max number of metaslabs per group to preload.
1580713e232SGeorge Wilson  */
1590713e232SGeorge Wilson int metaslab_preload_limit = SPA_DVAS_PER_BP;
1600713e232SGeorge Wilson 
1610713e232SGeorge Wilson /*
1620713e232SGeorge Wilson  * Enable/disable preloading of metaslab.
1630713e232SGeorge Wilson  */
1640713e232SGeorge Wilson boolean_t metaslab_preload_enabled = B_TRUE;
1650713e232SGeorge Wilson 
1660713e232SGeorge Wilson /*
1672e4c9986SGeorge Wilson  * Enable/disable fragmentation weighting on metaslabs.
1680713e232SGeorge Wilson  */
1692e4c9986SGeorge Wilson boolean_t metaslab_fragmentation_factor_enabled = B_TRUE;
1700713e232SGeorge Wilson 
1712e4c9986SGeorge Wilson /*
1722e4c9986SGeorge Wilson  * Enable/disable lba weighting (i.e. outer tracks are given preference).
1732e4c9986SGeorge Wilson  */
1742e4c9986SGeorge Wilson boolean_t metaslab_lba_weighting_enabled = B_TRUE;
1752e4c9986SGeorge Wilson 
1762e4c9986SGeorge Wilson /*
1772e4c9986SGeorge Wilson  * Enable/disable metaslab group biasing.
1782e4c9986SGeorge Wilson  */
1792e4c9986SGeorge Wilson boolean_t metaslab_bias_enabled = B_TRUE;
1802e4c9986SGeorge Wilson 
1812e4c9986SGeorge Wilson static uint64_t metaslab_fragmentation(metaslab_t *);
1820713e232SGeorge Wilson 
1830713e232SGeorge Wilson /*
184fa9e4066Sahrens  * ==========================================================================
185fa9e4066Sahrens  * Metaslab classes
186fa9e4066Sahrens  * ==========================================================================
187fa9e4066Sahrens  */
188fa9e4066Sahrens metaslab_class_t *
metaslab_class_create(spa_t * spa,metaslab_ops_t * ops)1890713e232SGeorge Wilson metaslab_class_create(spa_t *spa, metaslab_ops_t *ops)
190fa9e4066Sahrens {
191fa9e4066Sahrens 	metaslab_class_t *mc;
192fa9e4066Sahrens 
193fa9e4066Sahrens 	mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
194fa9e4066Sahrens 
19588ecc943SGeorge Wilson 	mc->mc_spa = spa;
196fa9e4066Sahrens 	mc->mc_rotor = NULL;
197d6e555bdSGeorge Wilson 	mc->mc_ops = ops;
198fa9e4066Sahrens 
199fa9e4066Sahrens 	return (mc);
200fa9e4066Sahrens }
201fa9e4066Sahrens 
202fa9e4066Sahrens void
metaslab_class_destroy(metaslab_class_t * mc)203fa9e4066Sahrens metaslab_class_destroy(metaslab_class_t *mc)
204fa9e4066Sahrens {
205a1521560SJeff Bonwick 	ASSERT(mc->mc_rotor == NULL);
206a1521560SJeff Bonwick 	ASSERT(mc->mc_alloc == 0);
207a1521560SJeff Bonwick 	ASSERT(mc->mc_deferred == 0);
208a1521560SJeff Bonwick 	ASSERT(mc->mc_space == 0);
209a1521560SJeff Bonwick 	ASSERT(mc->mc_dspace == 0);
210fa9e4066Sahrens 
211fa9e4066Sahrens 	kmem_free(mc, sizeof (metaslab_class_t));
212fa9e4066Sahrens }
213fa9e4066Sahrens 
21488ecc943SGeorge Wilson int
metaslab_class_validate(metaslab_class_t * mc)21588ecc943SGeorge Wilson metaslab_class_validate(metaslab_class_t *mc)
21688ecc943SGeorge Wilson {
21788ecc943SGeorge Wilson 	metaslab_group_t *mg;
21888ecc943SGeorge Wilson 	vdev_t *vd;
21988ecc943SGeorge Wilson 
22088ecc943SGeorge Wilson 	/*
22188ecc943SGeorge Wilson 	 * Must hold one of the spa_config locks.
22288ecc943SGeorge Wilson 	 */
22388ecc943SGeorge Wilson 	ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
22488ecc943SGeorge Wilson 	    spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
22588ecc943SGeorge Wilson 
22688ecc943SGeorge Wilson 	if ((mg = mc->mc_rotor) == NULL)
22788ecc943SGeorge Wilson 		return (0);
22888ecc943SGeorge Wilson 
22988ecc943SGeorge Wilson 	do {
23088ecc943SGeorge Wilson 		vd = mg->mg_vd;
23188ecc943SGeorge Wilson 		ASSERT(vd->vdev_mg != NULL);
23288ecc943SGeorge Wilson 		ASSERT3P(vd->vdev_top, ==, vd);
23388ecc943SGeorge Wilson 		ASSERT3P(mg->mg_class, ==, mc);
23488ecc943SGeorge Wilson 		ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
23588ecc943SGeorge Wilson 	} while ((mg = mg->mg_next) != mc->mc_rotor);
23688ecc943SGeorge Wilson 
23788ecc943SGeorge Wilson 	return (0);
23888ecc943SGeorge Wilson }
23988ecc943SGeorge Wilson 
240b24ab676SJeff Bonwick 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)241b24ab676SJeff Bonwick metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
242b24ab676SJeff Bonwick     int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
243b24ab676SJeff Bonwick {
244b24ab676SJeff Bonwick 	atomic_add_64(&mc->mc_alloc, alloc_delta);
245b24ab676SJeff Bonwick 	atomic_add_64(&mc->mc_deferred, defer_delta);
246b24ab676SJeff Bonwick 	atomic_add_64(&mc->mc_space, space_delta);
247b24ab676SJeff Bonwick 	atomic_add_64(&mc->mc_dspace, dspace_delta);
248b24ab676SJeff Bonwick }
249b24ab676SJeff Bonwick 
250b24ab676SJeff Bonwick uint64_t
metaslab_class_get_alloc(metaslab_class_t * mc)251b24ab676SJeff Bonwick metaslab_class_get_alloc(metaslab_class_t *mc)
252b24ab676SJeff Bonwick {
253b24ab676SJeff Bonwick 	return (mc->mc_alloc);
254b24ab676SJeff Bonwick }
255b24ab676SJeff Bonwick 
256b24ab676SJeff Bonwick uint64_t
metaslab_class_get_deferred(metaslab_class_t * mc)257b24ab676SJeff Bonwick metaslab_class_get_deferred(metaslab_class_t *mc)
258b24ab676SJeff Bonwick {
259b24ab676SJeff Bonwick 	return (mc->mc_deferred);
260b24ab676SJeff Bonwick }
261b24ab676SJeff Bonwick 
262b24ab676SJeff Bonwick uint64_t
metaslab_class_get_space(metaslab_class_t * mc)263b24ab676SJeff Bonwick metaslab_class_get_space(metaslab_class_t *mc)
264b24ab676SJeff Bonwick {
265b24ab676SJeff Bonwick 	return (mc->mc_space);
266b24ab676SJeff Bonwick }
267b24ab676SJeff Bonwick 
268b24ab676SJeff Bonwick uint64_t
metaslab_class_get_dspace(metaslab_class_t * mc)269b24ab676SJeff Bonwick metaslab_class_get_dspace(metaslab_class_t *mc)
270b24ab676SJeff Bonwick {
271b24ab676SJeff Bonwick 	return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
272b24ab676SJeff Bonwick }
273b24ab676SJeff Bonwick 
2742e4c9986SGeorge Wilson void
metaslab_class_histogram_verify(metaslab_class_t * mc)2752e4c9986SGeorge Wilson metaslab_class_histogram_verify(metaslab_class_t *mc)
2762e4c9986SGeorge Wilson {
2772e4c9986SGeorge Wilson 	vdev_t *rvd = mc->mc_spa->spa_root_vdev;
2782e4c9986SGeorge Wilson 	uint64_t *mc_hist;
2792e4c9986SGeorge Wilson 	int i;
2802e4c9986SGeorge Wilson 
2812e4c9986SGeorge Wilson 	if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
2822e4c9986SGeorge Wilson 		return;
2832e4c9986SGeorge Wilson 
2842e4c9986SGeorge Wilson 	mc_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
2852e4c9986SGeorge Wilson 	    KM_SLEEP);
2862e4c9986SGeorge Wilson 
2872e4c9986SGeorge Wilson 	for (int c = 0; c < rvd->vdev_children; c++) {
2882e4c9986SGeorge Wilson 		vdev_t *tvd = rvd->vdev_child[c];
2892e4c9986SGeorge Wilson 		metaslab_group_t *mg = tvd->vdev_mg;
2902e4c9986SGeorge Wilson 
2912e4c9986SGeorge Wilson 		/*
2922e4c9986SGeorge Wilson 		 * Skip any holes, uninitialized top-levels, or
2932e4c9986SGeorge Wilson 		 * vdevs that are not in this metalab class.
2942e4c9986SGeorge Wilson 		 */
2952e4c9986SGeorge Wilson 		if (tvd->vdev_ishole || tvd->vdev_ms_shift == 0 ||
2962e4c9986SGeorge Wilson 		    mg->mg_class != mc) {
2972e4c9986SGeorge Wilson 			continue;
2982e4c9986SGeorge Wilson 		}
2992e4c9986SGeorge Wilson 
3002e4c9986SGeorge Wilson 		for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
3012e4c9986SGeorge Wilson 			mc_hist[i] += mg->mg_histogram[i];
3022e4c9986SGeorge Wilson 	}
3032e4c9986SGeorge Wilson 
3042e4c9986SGeorge Wilson 	for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
3052e4c9986SGeorge Wilson 		VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
3062e4c9986SGeorge Wilson 
3072e4c9986SGeorge Wilson 	kmem_free(mc_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
3082e4c9986SGeorge Wilson }
3092e4c9986SGeorge Wilson 
3102e4c9986SGeorge Wilson /*
3112e4c9986SGeorge Wilson  * Calculate the metaslab class's fragmentation metric. The metric
3122e4c9986SGeorge Wilson  * is weighted based on the space contribution of each metaslab group.
3132e4c9986SGeorge Wilson  * The return value will be a number between 0 and 100 (inclusive), or
3142e4c9986SGeorge Wilson  * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
3152e4c9986SGeorge Wilson  * zfs_frag_table for more information about the metric.
3162e4c9986SGeorge Wilson  */
3172e4c9986SGeorge Wilson uint64_t
metaslab_class_fragmentation(metaslab_class_t * mc)3182e4c9986SGeorge Wilson metaslab_class_fragmentation(metaslab_class_t *mc)
3192e4c9986SGeorge Wilson {
3202e4c9986SGeorge Wilson 	vdev_t *rvd = mc->mc_spa->spa_root_vdev;
3212e4c9986SGeorge Wilson 	uint64_t fragmentation = 0;
3222e4c9986SGeorge Wilson 
3232e4c9986SGeorge Wilson 	spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
3242e4c9986SGeorge Wilson 
3252e4c9986SGeorge Wilson 	for (int c = 0; c < rvd->vdev_children; c++) {
3262e4c9986SGeorge Wilson 		vdev_t *tvd = rvd->vdev_child[c];
3272e4c9986SGeorge Wilson 		metaslab_group_t *mg = tvd->vdev_mg;
3282e4c9986SGeorge Wilson 
3292e4c9986SGeorge Wilson 		/*
3302e4c9986SGeorge Wilson 		 * Skip any holes, uninitialized top-levels, or
3312e4c9986SGeorge Wilson 		 * vdevs that are not in this metalab class.
3322e4c9986SGeorge Wilson 		 */
3332e4c9986SGeorge Wilson 		if (tvd->vdev_ishole || tvd->vdev_ms_shift == 0 ||
3342e4c9986SGeorge Wilson 		    mg->mg_class != mc) {
3352e4c9986SGeorge Wilson 			continue;
3362e4c9986SGeorge Wilson 		}
3372e4c9986SGeorge Wilson 
3382e4c9986SGeorge Wilson 		/*
3392e4c9986SGeorge Wilson 		 * If a metaslab group does not contain a fragmentation
3402e4c9986SGeorge Wilson 		 * metric then just bail out.
3412e4c9986SGeorge Wilson 		 */
3422e4c9986SGeorge Wilson 		if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
3432e4c9986SGeorge Wilson 			spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
3442e4c9986SGeorge Wilson 			return (ZFS_FRAG_INVALID);
3452e4c9986SGeorge Wilson 		}
3462e4c9986SGeorge Wilson 
3472e4c9986SGeorge Wilson 		/*
3482e4c9986SGeorge Wilson 		 * Determine how much this metaslab_group is contributing
3492e4c9986SGeorge Wilson 		 * to the overall pool fragmentation metric.
3502e4c9986SGeorge Wilson 		 */
3512e4c9986SGeorge Wilson 		fragmentation += mg->mg_fragmentation *
3522e4c9986SGeorge Wilson 		    metaslab_group_get_space(mg);
3532e4c9986SGeorge Wilson 	}
3542e4c9986SGeorge Wilson 	fragmentation /= metaslab_class_get_space(mc);
3552e4c9986SGeorge Wilson 
3562e4c9986SGeorge Wilson 	ASSERT3U(fragmentation, <=, 100);
3572e4c9986SGeorge Wilson 	spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
3582e4c9986SGeorge Wilson 	return (fragmentation);
3592e4c9986SGeorge Wilson }
3602e4c9986SGeorge Wilson 
3612e4c9986SGeorge Wilson /*
3622e4c9986SGeorge Wilson  * Calculate the amount of expandable space that is available in
3632e4c9986SGeorge Wilson  * this metaslab class. If a device is expanded then its expandable
3642e4c9986SGeorge Wilson  * space will be the amount of allocatable space that is currently not
3652e4c9986SGeorge Wilson  * part of this metaslab class.
3662e4c9986SGeorge Wilson  */
3672e4c9986SGeorge Wilson uint64_t
metaslab_class_expandable_space(metaslab_class_t * mc)3682e4c9986SGeorge Wilson metaslab_class_expandable_space(metaslab_class_t *mc)
3692e4c9986SGeorge Wilson {
3702e4c9986SGeorge Wilson 	vdev_t *rvd = mc->mc_spa->spa_root_vdev;
3712e4c9986SGeorge Wilson 	uint64_t space = 0;
3722e4c9986SGeorge Wilson 
3732e4c9986SGeorge Wilson 	spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
3742e4c9986SGeorge Wilson 	for (int c = 0; c < rvd->vdev_children; c++) {
3752e4c9986SGeorge Wilson 		vdev_t *tvd = rvd->vdev_child[c];
3762e4c9986SGeorge Wilson 		metaslab_group_t *mg = tvd->vdev_mg;
3772e4c9986SGeorge Wilson 
3782e4c9986SGeorge Wilson 		if (tvd->vdev_ishole || tvd->vdev_ms_shift == 0 ||
3792e4c9986SGeorge Wilson 		    mg->mg_class != mc) {
3802e4c9986SGeorge Wilson 			continue;
3812e4c9986SGeorge Wilson 		}
3822e4c9986SGeorge Wilson 
3832e4c9986SGeorge Wilson 		space += tvd->vdev_max_asize - tvd->vdev_asize;
3842e4c9986SGeorge Wilson 	}
3852e4c9986SGeorge Wilson 	spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
3862e4c9986SGeorge Wilson 	return (space);
3872e4c9986SGeorge Wilson }
3882e4c9986SGeorge Wilson 
389fa9e4066Sahrens /*
390fa9e4066Sahrens  * ==========================================================================
391fa9e4066Sahrens  * Metaslab groups
392fa9e4066Sahrens  * ==========================================================================
393fa9e4066Sahrens  */
394fa9e4066Sahrens static int
metaslab_compare(const void * x1,const void * x2)395fa9e4066Sahrens metaslab_compare(const void *x1, const void *x2)
396fa9e4066Sahrens {
397fa9e4066Sahrens 	const metaslab_t *m1 = x1;
398fa9e4066Sahrens 	const metaslab_t *m2 = x2;
399fa9e4066Sahrens 
400fa9e4066Sahrens 	if (m1->ms_weight < m2->ms_weight)
401fa9e4066Sahrens 		return (1);
402fa9e4066Sahrens 	if (m1->ms_weight > m2->ms_weight)
403fa9e4066Sahrens 		return (-1);
404fa9e4066Sahrens 
405fa9e4066Sahrens 	/*
406fa9e4066Sahrens 	 * If the weights are identical, use the offset to force uniqueness.
407fa9e4066Sahrens 	 */
4080713e232SGeorge Wilson 	if (m1->ms_start < m2->ms_start)
409fa9e4066Sahrens 		return (-1);
4100713e232SGeorge Wilson 	if (m1->ms_start > m2->ms_start)
411fa9e4066Sahrens 		return (1);
412fa9e4066Sahrens 
413fa9e4066Sahrens 	ASSERT3P(m1, ==, m2);
414fa9e4066Sahrens 
415fa9e4066Sahrens 	return (0);
416fa9e4066Sahrens }
417fa9e4066Sahrens 
41822e30981SGeorge Wilson /*
41922e30981SGeorge Wilson  * Update the allocatable flag and the metaslab group's capacity.
42022e30981SGeorge Wilson  * The allocatable flag is set to true if the capacity is below
42122e30981SGeorge Wilson  * the zfs_mg_noalloc_threshold. If a metaslab group transitions
42222e30981SGeorge Wilson  * from allocatable to non-allocatable or vice versa then the metaslab
42322e30981SGeorge Wilson  * group's class is updated to reflect the transition.
42422e30981SGeorge Wilson  */
42522e30981SGeorge Wilson static void
metaslab_group_alloc_update(metaslab_group_t * mg)42622e30981SGeorge Wilson metaslab_group_alloc_update(metaslab_group_t *mg)
42722e30981SGeorge Wilson {
42822e30981SGeorge Wilson 	vdev_t *vd = mg->mg_vd;
42922e30981SGeorge Wilson 	metaslab_class_t *mc = mg->mg_class;
43022e30981SGeorge Wilson 	vdev_stat_t *vs = &vd->vdev_stat;
43122e30981SGeorge Wilson 	boolean_t was_allocatable;
43222e30981SGeorge Wilson 
43322e30981SGeorge Wilson 	ASSERT(vd == vd->vdev_top);
43422e30981SGeorge Wilson 
43522e30981SGeorge Wilson 	mutex_enter(&mg->mg_lock);
43622e30981SGeorge Wilson 	was_allocatable = mg->mg_allocatable;
43722e30981SGeorge Wilson 
43822e30981SGeorge Wilson 	mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
43922e30981SGeorge Wilson 	    (vs->vs_space + 1);
44022e30981SGeorge Wilson 
4412e4c9986SGeorge Wilson 	/*
4422e4c9986SGeorge Wilson 	 * A metaslab group is considered allocatable if it has plenty
4432e4c9986SGeorge Wilson 	 * of free space or is not heavily fragmented. We only take
4442e4c9986SGeorge Wilson 	 * fragmentation into account if the metaslab group has a valid
4452e4c9986SGeorge Wilson 	 * fragmentation metric (i.e. a value between 0 and 100).
4462e4c9986SGeorge Wilson 	 */
4472e4c9986SGeorge Wilson 	mg->mg_allocatable = (mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
4482e4c9986SGeorge Wilson 	    (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
4492e4c9986SGeorge Wilson 	    mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
45022e30981SGeorge Wilson 
45122e30981SGeorge Wilson 	/*
45222e30981SGeorge Wilson 	 * The mc_alloc_groups maintains a count of the number of
45322e30981SGeorge Wilson 	 * groups in this metaslab class that are still above the
45422e30981SGeorge Wilson 	 * zfs_mg_noalloc_threshold. This is used by the allocating
45522e30981SGeorge Wilson 	 * threads to determine if they should avoid allocations to
45622e30981SGeorge Wilson 	 * a given group. The allocator will avoid allocations to a group
45722e30981SGeorge Wilson 	 * if that group has reached or is below the zfs_mg_noalloc_threshold
45822e30981SGeorge Wilson 	 * and there are still other groups that are above the threshold.
45922e30981SGeorge Wilson 	 * When a group transitions from allocatable to non-allocatable or
46022e30981SGeorge Wilson 	 * vice versa we update the metaslab class to reflect that change.
46122e30981SGeorge Wilson 	 * When the mc_alloc_groups value drops to 0 that means that all
46222e30981SGeorge Wilson 	 * groups have reached the zfs_mg_noalloc_threshold making all groups
46322e30981SGeorge Wilson 	 * eligible for allocations. This effectively means that all devices
46422e30981SGeorge Wilson 	 * are balanced again.
46522e30981SGeorge Wilson 	 */
46622e30981SGeorge Wilson 	if (was_allocatable && !mg->mg_allocatable)
46722e30981SGeorge Wilson 		mc->mc_alloc_groups--;
46822e30981SGeorge Wilson 	else if (!was_allocatable && mg->mg_allocatable)
46922e30981SGeorge Wilson 		mc->mc_alloc_groups++;
4702e4c9986SGeorge Wilson 
47122e30981SGeorge Wilson 	mutex_exit(&mg->mg_lock);
47222e30981SGeorge Wilson }
47322e30981SGeorge Wilson 
474fa9e4066Sahrens metaslab_group_t *
metaslab_group_create(metaslab_class_t * mc,vdev_t * vd)475fa9e4066Sahrens metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
476fa9e4066Sahrens {
477fa9e4066Sahrens 	metaslab_group_t *mg;
478fa9e4066Sahrens 
479fa9e4066Sahrens 	mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
480fa9e4066Sahrens 	mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
481fa9e4066Sahrens 	avl_create(&mg->mg_metaslab_tree, metaslab_compare,
482fa9e4066Sahrens 	    sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
483fa9e4066Sahrens 	mg->mg_vd = vd;
484a1521560SJeff Bonwick 	mg->mg_class = mc;
485a1521560SJeff Bonwick 	mg->mg_activation_count = 0;
486fa9e4066Sahrens 
487be082110SGeorge Wilson 	mg->mg_taskq = taskq_create("metaslab_group_taskq", metaslab_load_pct,
4880713e232SGeorge Wilson 	    minclsyspri, 10, INT_MAX, TASKQ_THREADS_CPU_PCT);
4890713e232SGeorge Wilson 
490fa9e4066Sahrens 	return (mg);
491fa9e4066Sahrens }
492fa9e4066Sahrens 
493fa9e4066Sahrens void
metaslab_group_destroy(metaslab_group_t * mg)494fa9e4066Sahrens metaslab_group_destroy(metaslab_group_t *mg)
495fa9e4066Sahrens {
496a1521560SJeff Bonwick 	ASSERT(mg->mg_prev == NULL);
497a1521560SJeff Bonwick 	ASSERT(mg->mg_next == NULL);
498a33cae98STim Haley 	/*
499a33cae98STim Haley 	 * We may have gone below zero with the activation count
500a33cae98STim Haley 	 * either because we never activated in the first place or
501a33cae98STim Haley 	 * because we're done, and possibly removing the vdev.
502a33cae98STim Haley 	 */
503a33cae98STim Haley 	ASSERT(mg->mg_activation_count <= 0);
504a1521560SJeff Bonwick 
505be082110SGeorge Wilson 	taskq_destroy(mg->mg_taskq);
506fa9e4066Sahrens 	avl_destroy(&mg->mg_metaslab_tree);
507fa9e4066Sahrens 	mutex_destroy(&mg->mg_lock);
508fa9e4066Sahrens 	kmem_free(mg, sizeof (metaslab_group_t));
509fa9e4066Sahrens }
510fa9e4066Sahrens 
511a1521560SJeff Bonwick void
metaslab_group_activate(metaslab_group_t * mg)512a1521560SJeff Bonwick metaslab_group_activate(metaslab_group_t *mg)
513a1521560SJeff Bonwick {
514a1521560SJeff Bonwick 	metaslab_class_t *mc = mg->mg_class;
515a1521560SJeff Bonwick 	metaslab_group_t *mgprev, *mgnext;
516a1521560SJeff Bonwick 
517a1521560SJeff Bonwick 	ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
518a1521560SJeff Bonwick 
519a1521560SJeff Bonwick 	ASSERT(mc->mc_rotor != mg);
520a1521560SJeff Bonwick 	ASSERT(mg->mg_prev == NULL);
521a1521560SJeff Bonwick 	ASSERT(mg->mg_next == NULL);
522a1521560SJeff Bonwick 	ASSERT(mg->mg_activation_count <= 0);
523a1521560SJeff Bonwick 
524a1521560SJeff Bonwick 	if (++mg->mg_activation_count <= 0)
525a1521560SJeff Bonwick 		return;
526a1521560SJeff Bonwick 
527a1521560SJeff Bonwick 	mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
52822e30981SGeorge Wilson 	metaslab_group_alloc_update(mg);
529a1521560SJeff Bonwick 
530a1521560SJeff Bonwick 	if ((mgprev = mc->mc_rotor) == NULL) {
531a1521560SJeff Bonwick 		mg->mg_prev = mg;
532a1521560SJeff Bonwick 		mg->mg_next = mg;
533a1521560SJeff Bonwick 	} else {
534a1521560SJeff Bonwick 		mgnext = mgprev->mg_next;
535a1521560SJeff Bonwick 		mg->mg_prev = mgprev;
536a1521560SJeff Bonwick 		mg->mg_next = mgnext;
537a1521560SJeff Bonwick 		mgprev->mg_next = mg;
538a1521560SJeff Bonwick 		mgnext->mg_prev = mg;
539a1521560SJeff Bonwick 	}
540a1521560SJeff Bonwick 	mc->mc_rotor = mg;
541a1521560SJeff Bonwick }
542a1521560SJeff Bonwick 
543a1521560SJeff Bonwick void
metaslab_group_passivate(metaslab_group_t * mg)544a1521560SJeff Bonwick metaslab_group_passivate(metaslab_group_t *mg)
545a1521560SJeff Bonwick {
546a1521560SJeff Bonwick 	metaslab_class_t *mc = mg->mg_class;
547a1521560SJeff Bonwick 	metaslab_group_t *mgprev, *mgnext;
548a1521560SJeff Bonwick 
549a1521560SJeff Bonwick 	ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
550a1521560SJeff Bonwick 
551a1521560SJeff Bonwick 	if (--mg->mg_activation_count != 0) {
552a1521560SJeff Bonwick 		ASSERT(mc->mc_rotor != mg);
553a1521560SJeff Bonwick 		ASSERT(mg->mg_prev == NULL);
554a1521560SJeff Bonwick 		ASSERT(mg->mg_next == NULL);
555a1521560SJeff Bonwick 		ASSERT(mg->mg_activation_count < 0);
556a1521560SJeff Bonwick 		return;
557a1521560SJeff Bonwick 	}
558a1521560SJeff Bonwick 
5590713e232SGeorge Wilson 	taskq_wait(mg->mg_taskq);
5602e4c9986SGeorge Wilson 	metaslab_group_alloc_update(mg);
5610713e232SGeorge Wilson 
562a1521560SJeff Bonwick 	mgprev = mg->mg_prev;
563a1521560SJeff Bonwick 	mgnext = mg->mg_next;
564a1521560SJeff Bonwick 
565a1521560SJeff Bonwick 	if (mg == mgnext) {
566a1521560SJeff Bonwick 		mc->mc_rotor = NULL;
567a1521560SJeff Bonwick 	} else {
568a1521560SJeff Bonwick 		mc->mc_rotor = mgnext;
569a1521560SJeff Bonwick 		mgprev->mg_next = mgnext;
570a1521560SJeff Bonwick 		mgnext->mg_prev = mgprev;
571a1521560SJeff Bonwick 	}
572a1521560SJeff Bonwick 
573a1521560SJeff Bonwick 	mg->mg_prev = NULL;
574a1521560SJeff Bonwick 	mg->mg_next = NULL;
575a1521560SJeff Bonwick }
576a1521560SJeff Bonwick 
5772e4c9986SGeorge Wilson uint64_t
metaslab_group_get_space(metaslab_group_t * mg)5782e4c9986SGeorge Wilson metaslab_group_get_space(metaslab_group_t *mg)
5792e4c9986SGeorge Wilson {
5802e4c9986SGeorge Wilson 	return ((1ULL << mg->mg_vd->vdev_ms_shift) * mg->mg_vd->vdev_ms_count);
5812e4c9986SGeorge Wilson }
5822e4c9986SGeorge Wilson 
5832e4c9986SGeorge Wilson void
metaslab_group_histogram_verify(metaslab_group_t * mg)5842e4c9986SGeorge Wilson metaslab_group_histogram_verify(metaslab_group_t *mg)
5852e4c9986SGeorge Wilson {
5862e4c9986SGeorge Wilson 	uint64_t *mg_hist;
5872e4c9986SGeorge Wilson 	vdev_t *vd = mg->mg_vd;
5882e4c9986SGeorge Wilson 	uint64_t ashift = vd->vdev_ashift;
5892e4c9986SGeorge Wilson 	int i;
5902e4c9986SGeorge Wilson 
5912e4c9986SGeorge Wilson 	if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
5922e4c9986SGeorge Wilson 		return;
5932e4c9986SGeorge Wilson 
5942e4c9986SGeorge Wilson 	mg_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
5952e4c9986SGeorge Wilson 	    KM_SLEEP);
5962e4c9986SGeorge Wilson 
5972e4c9986SGeorge Wilson 	ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE, >=,
5982e4c9986SGeorge Wilson 	    SPACE_MAP_HISTOGRAM_SIZE + ashift);
5992e4c9986SGeorge Wilson 
6002e4c9986SGeorge Wilson 	for (int m = 0; m < vd->vdev_ms_count; m++) {
6012e4c9986SGeorge Wilson 		metaslab_t *msp = vd->vdev_ms[m];
6022e4c9986SGeorge Wilson 
6032e4c9986SGeorge Wilson 		if (msp->ms_sm == NULL)
6042e4c9986SGeorge Wilson 			continue;
6052e4c9986SGeorge Wilson 
6062e4c9986SGeorge Wilson 		for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
6072e4c9986SGeorge Wilson 			mg_hist[i + ashift] +=
6082e4c9986SGeorge Wilson 			    msp->ms_sm->sm_phys->smp_histogram[i];
6092e4c9986SGeorge Wilson 	}
6102e4c9986SGeorge Wilson 
6112e4c9986SGeorge Wilson 	for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i ++)
6122e4c9986SGeorge Wilson 		VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
6132e4c9986SGeorge Wilson 
6142e4c9986SGeorge Wilson 	kmem_free(mg_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
6152e4c9986SGeorge Wilson }
6162e4c9986SGeorge Wilson 
6172e4c9986SGeorge Wilson static void
metaslab_group_histogram_add(metaslab_group_t * mg,metaslab_t * msp)6182e4c9986SGeorge Wilson metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
6192e4c9986SGeorge Wilson {
6202e4c9986SGeorge Wilson 	metaslab_class_t *mc = mg->mg_class;
6212e4c9986SGeorge Wilson 	uint64_t ashift = mg->mg_vd->vdev_ashift;
6222e4c9986SGeorge Wilson 
6232e4c9986SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
6242e4c9986SGeorge Wilson 	if (msp->ms_sm == NULL)
6252e4c9986SGeorge Wilson 		return;
6262e4c9986SGeorge Wilson 
6272e4c9986SGeorge Wilson 	mutex_enter(&mg->mg_lock);
6282e4c9986SGeorge Wilson 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
6292e4c9986SGeorge Wilson 		mg->mg_histogram[i + ashift] +=
6302e4c9986SGeorge Wilson 		    msp->ms_sm->sm_phys->smp_histogram[i];
6312e4c9986SGeorge Wilson 		mc->mc_histogram[i + ashift] +=
6322e4c9986SGeorge Wilson 		    msp->ms_sm->sm_phys->smp_histogram[i];
6332e4c9986SGeorge Wilson 	}
6342e4c9986SGeorge Wilson 	mutex_exit(&mg->mg_lock);
6352e4c9986SGeorge Wilson }
6362e4c9986SGeorge Wilson 
6372e4c9986SGeorge Wilson void
metaslab_group_histogram_remove(metaslab_group_t * mg,metaslab_t * msp)6382e4c9986SGeorge Wilson metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
6392e4c9986SGeorge Wilson {
6402e4c9986SGeorge Wilson 	metaslab_class_t *mc = mg->mg_class;
6412e4c9986SGeorge Wilson 	uint64_t ashift = mg->mg_vd->vdev_ashift;
6422e4c9986SGeorge Wilson 
6432e4c9986SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
6442e4c9986SGeorge Wilson 	if (msp->ms_sm == NULL)
6452e4c9986SGeorge Wilson 		return;
6462e4c9986SGeorge Wilson 
6472e4c9986SGeorge Wilson 	mutex_enter(&mg->mg_lock);
6482e4c9986SGeorge Wilson 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
6492e4c9986SGeorge Wilson 		ASSERT3U(mg->mg_histogram[i + ashift], >=,
6502e4c9986SGeorge Wilson 		    msp->ms_sm->sm_phys->smp_histogram[i]);
6512e4c9986SGeorge Wilson 		ASSERT3U(mc->mc_histogram[i + ashift], >=,
6522e4c9986SGeorge Wilson 		    msp->ms_sm->sm_phys->smp_histogram[i]);
6532e4c9986SGeorge Wilson 
6542e4c9986SGeorge Wilson 		mg->mg_histogram[i + ashift] -=
6552e4c9986SGeorge Wilson 		    msp->ms_sm->sm_phys->smp_histogram[i];
6562e4c9986SGeorge Wilson 		mc->mc_histogram[i + ashift] -=
6572e4c9986SGeorge Wilson 		    msp->ms_sm->sm_phys->smp_histogram[i];
6582e4c9986SGeorge Wilson 	}
6592e4c9986SGeorge Wilson 	mutex_exit(&mg->mg_lock);
6602e4c9986SGeorge Wilson }
6612e4c9986SGeorge Wilson 
662ecc2d604Sbonwick static void
metaslab_group_add(metaslab_group_t * mg,metaslab_t * msp)663ecc2d604Sbonwick metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
664fa9e4066Sahrens {
665fa9e4066Sahrens 	ASSERT(msp->ms_group == NULL);
6662e4c9986SGeorge Wilson 	mutex_enter(&mg->mg_lock);
667fa9e4066Sahrens 	msp->ms_group = mg;
668ecc2d604Sbonwick 	msp->ms_weight = 0;
669fa9e4066Sahrens 	avl_add(&mg->mg_metaslab_tree, msp);
670fa9e4066Sahrens 	mutex_exit(&mg->mg_lock);
6712e4c9986SGeorge Wilson 
6722e4c9986SGeorge Wilson 	mutex_enter(&msp->ms_lock);
6732e4c9986SGeorge Wilson 	metaslab_group_histogram_add(mg, msp);
6742e4c9986SGeorge Wilson 	mutex_exit(&msp->ms_lock);
675fa9e4066Sahrens }
676fa9e4066Sahrens 
677ecc2d604Sbonwick static void
metaslab_group_remove(metaslab_group_t * mg,metaslab_t * msp)678fa9e4066Sahrens metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
679fa9e4066Sahrens {
6802e4c9986SGeorge Wilson 	mutex_enter(&msp->ms_lock);
6812e4c9986SGeorge Wilson 	metaslab_group_histogram_remove(mg, msp);
6822e4c9986SGeorge Wilson 	mutex_exit(&msp->ms_lock);
6832e4c9986SGeorge Wilson 
684fa9e4066Sahrens 	mutex_enter(&mg->mg_lock);
685fa9e4066Sahrens 	ASSERT(msp->ms_group == mg);
686fa9e4066Sahrens 	avl_remove(&mg->mg_metaslab_tree, msp);
687fa9e4066Sahrens 	msp->ms_group = NULL;
688fa9e4066Sahrens 	mutex_exit(&mg->mg_lock);
689fa9e4066Sahrens }
690fa9e4066Sahrens 
691ecc2d604Sbonwick static void
metaslab_group_sort(metaslab_group_t * mg,metaslab_t * msp,uint64_t weight)692fa9e4066Sahrens metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
693fa9e4066Sahrens {
6945f5f7a6fSahrens 	/*
6955f5f7a6fSahrens 	 * Although in principle the weight can be any value, in
6962e4c9986SGeorge Wilson 	 * practice we do not use values in the range [1, 511].
6975f5f7a6fSahrens 	 */
6982e4c9986SGeorge Wilson 	ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
699ecc2d604Sbonwick 	ASSERT(MUTEX_HELD(&msp->ms_lock));
700ecc2d604Sbonwick 
701fa9e4066Sahrens 	mutex_enter(&mg->mg_lock);
702fa9e4066Sahrens 	ASSERT(msp->ms_group == mg);
703fa9e4066Sahrens 	avl_remove(&mg->mg_metaslab_tree, msp);
704fa9e4066Sahrens 	msp->ms_weight = weight;
705fa9e4066Sahrens 	avl_add(&mg->mg_metaslab_tree, msp);
706fa9e4066Sahrens 	mutex_exit(&mg->mg_lock);
707fa9e4066Sahrens }
708fa9e4066Sahrens 
709fa9e4066Sahrens /*
7102e4c9986SGeorge Wilson  * Calculate the fragmentation for a given metaslab group. We can use
7112e4c9986SGeorge Wilson  * a simple average here since all metaslabs within the group must have
7122e4c9986SGeorge Wilson  * the same size. The return value will be a value between 0 and 100
7132e4c9986SGeorge Wilson  * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
7142e4c9986SGeorge Wilson  * group have a fragmentation metric.
7152e4c9986SGeorge Wilson  */
7162e4c9986SGeorge Wilson uint64_t
metaslab_group_fragmentation(metaslab_group_t * mg)7172e4c9986SGeorge Wilson metaslab_group_fragmentation(metaslab_group_t *mg)
7182e4c9986SGeorge Wilson {
7192e4c9986SGeorge Wilson 	vdev_t *vd = mg->mg_vd;
7202e4c9986SGeorge Wilson 	uint64_t fragmentation = 0;
7212e4c9986SGeorge Wilson 	uint64_t valid_ms = 0;
7222e4c9986SGeorge Wilson 
7232e4c9986SGeorge Wilson 	for (int m = 0; m < vd->vdev_ms_count; m++) {
7242e4c9986SGeorge Wilson 		metaslab_t *msp = vd->vdev_ms[m];
7252e4c9986SGeorge Wilson 
7262e4c9986SGeorge Wilson 		if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
7272e4c9986SGeorge Wilson 			continue;
7282e4c9986SGeorge Wilson 
7292e4c9986SGeorge Wilson 		valid_ms++;
7302e4c9986SGeorge Wilson 		fragmentation += msp->ms_fragmentation;
7312e4c9986SGeorge Wilson 	}
7322e4c9986SGeorge Wilson 
7332e4c9986SGeorge Wilson 	if (valid_ms <= vd->vdev_ms_count / 2)
7342e4c9986SGeorge Wilson 		return (ZFS_FRAG_INVALID);
7352e4c9986SGeorge Wilson 
7362e4c9986SGeorge Wilson 	fragmentation /= valid_ms;
7372e4c9986SGeorge Wilson 	ASSERT3U(fragmentation, <=, 100);
7382e4c9986SGeorge Wilson 	return (fragmentation);
7392e4c9986SGeorge Wilson }
7402e4c9986SGeorge Wilson 
7412e4c9986SGeorge Wilson /*
74222e30981SGeorge Wilson  * Determine if a given metaslab group should skip allocations. A metaslab
7432e4c9986SGeorge Wilson  * group should avoid allocations if its free capacity is less than the
7442e4c9986SGeorge Wilson  * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
7452e4c9986SGeorge Wilson  * zfs_mg_fragmentation_threshold and there is at least one metaslab group
74622e30981SGeorge Wilson  * that can still handle allocations.
74722e30981SGeorge Wilson  */
74822e30981SGeorge Wilson static boolean_t
metaslab_group_allocatable(metaslab_group_t * mg)74922e30981SGeorge Wilson metaslab_group_allocatable(metaslab_group_t *mg)
75022e30981SGeorge Wilson {
75122e30981SGeorge Wilson 	vdev_t *vd = mg->mg_vd;
75222e30981SGeorge Wilson 	spa_t *spa = vd->vdev_spa;
75322e30981SGeorge Wilson 	metaslab_class_t *mc = mg->mg_class;
75422e30981SGeorge Wilson 
75522e30981SGeorge Wilson 	/*
7562e4c9986SGeorge Wilson 	 * We use two key metrics to determine if a metaslab group is
7572e4c9986SGeorge Wilson 	 * considered allocatable -- free space and fragmentation. If
7582e4c9986SGeorge Wilson 	 * the free space is greater than the free space threshold and
7592e4c9986SGeorge Wilson 	 * the fragmentation is less than the fragmentation threshold then
7602e4c9986SGeorge Wilson 	 * consider the group allocatable. There are two case when we will
7612e4c9986SGeorge Wilson 	 * not consider these key metrics. The first is if the group is
7622e4c9986SGeorge Wilson 	 * associated with a slog device and the second is if all groups
7632e4c9986SGeorge Wilson 	 * in this metaslab class have already been consider ineligible
7642e4c9986SGeorge Wilson 	 * for allocations.
76522e30981SGeorge Wilson 	 */
7662e4c9986SGeorge Wilson 	return ((mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
7672e4c9986SGeorge Wilson 	    (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
7682e4c9986SGeorge Wilson 	    mg->mg_fragmentation <= zfs_mg_fragmentation_threshold)) ||
76922e30981SGeorge Wilson 	    mc != spa_normal_class(spa) || mc->mc_alloc_groups == 0);
77022e30981SGeorge Wilson }
77122e30981SGeorge Wilson 
77222e30981SGeorge Wilson /*
77380eb36f2SGeorge Wilson  * ==========================================================================
7740713e232SGeorge Wilson  * Range tree callbacks
77580eb36f2SGeorge Wilson  * ==========================================================================
77680eb36f2SGeorge Wilson  */
77780eb36f2SGeorge Wilson 
7780713e232SGeorge Wilson /*
7790713e232SGeorge Wilson  * Comparison function for the private size-ordered tree. Tree is sorted
7800713e232SGeorge Wilson  * by size, larger sizes at the end of the tree.
7810713e232SGeorge Wilson  */
7820713e232SGeorge Wilson static int
metaslab_rangesize_compare(const void * x1,const void * x2)7830713e232SGeorge Wilson metaslab_rangesize_compare(const void *x1, const void *x2)
7840713e232SGeorge Wilson {
7850713e232SGeorge Wilson 	const range_seg_t *r1 = x1;
7860713e232SGeorge Wilson 	const range_seg_t *r2 = x2;
7870713e232SGeorge Wilson 	uint64_t rs_size1 = r1->rs_end - r1->rs_start;
7880713e232SGeorge Wilson 	uint64_t rs_size2 = r2->rs_end - r2->rs_start;
7890713e232SGeorge Wilson 
7900713e232SGeorge Wilson 	if (rs_size1 < rs_size2)
79180eb36f2SGeorge Wilson 		return (-1);
7920713e232SGeorge Wilson 	if (rs_size1 > rs_size2)
79380eb36f2SGeorge Wilson 		return (1);
79480eb36f2SGeorge Wilson 
7950713e232SGeorge Wilson 	if (r1->rs_start < r2->rs_start)
79680eb36f2SGeorge Wilson 		return (-1);
7970713e232SGeorge Wilson 
7980713e232SGeorge Wilson 	if (r1->rs_start > r2->rs_start)
79980eb36f2SGeorge Wilson 		return (1);
80080eb36f2SGeorge Wilson 
80180eb36f2SGeorge Wilson 	return (0);
80280eb36f2SGeorge Wilson }
80380eb36f2SGeorge Wilson 
80480eb36f2SGeorge Wilson /*
8050713e232SGeorge Wilson  * Create any block allocator specific components. The current allocators
8060713e232SGeorge Wilson  * rely on using both a size-ordered range_tree_t and an array of uint64_t's.
8070713e232SGeorge Wilson  */
8080713e232SGeorge Wilson static void
metaslab_rt_create(range_tree_t * rt,void * arg)8090713e232SGeorge Wilson metaslab_rt_create(range_tree_t *rt, void *arg)
8100713e232SGeorge Wilson {
8110713e232SGeorge Wilson 	metaslab_t *msp = arg;
8120713e232SGeorge Wilson 
8130713e232SGeorge Wilson 	ASSERT3P(rt->rt_arg, ==, msp);
8140713e232SGeorge Wilson 	ASSERT(msp->ms_tree == NULL);
8150713e232SGeorge Wilson 
8160713e232SGeorge Wilson 	avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
8170713e232SGeorge Wilson 	    sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
8180713e232SGeorge Wilson }
8190713e232SGeorge Wilson 
8200713e232SGeorge Wilson /*
8210713e232SGeorge Wilson  * Destroy the block allocator specific components.
8220713e232SGeorge Wilson  */
8230713e232SGeorge Wilson static void
metaslab_rt_destroy(range_tree_t * rt,void * arg)8240713e232SGeorge Wilson metaslab_rt_destroy(range_tree_t *rt, void *arg)
8250713e232SGeorge Wilson {
8260713e232SGeorge Wilson 	metaslab_t *msp = arg;
8270713e232SGeorge Wilson 
8280713e232SGeorge Wilson 	ASSERT3P(rt->rt_arg, ==, msp);
8290713e232SGeorge Wilson 	ASSERT3P(msp->ms_tree, ==, rt);
8300713e232SGeorge Wilson 	ASSERT0(avl_numnodes(&msp->ms_size_tree));
8310713e232SGeorge Wilson 
8320713e232SGeorge Wilson 	avl_destroy(&msp->ms_size_tree);
8330713e232SGeorge Wilson }
8340713e232SGeorge Wilson 
8350713e232SGeorge Wilson static void
metaslab_rt_add(range_tree_t * rt,range_seg_t * rs,void * arg)8360713e232SGeorge Wilson metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg)
8370713e232SGeorge Wilson {
8380713e232SGeorge Wilson 	metaslab_t *msp = arg;
8390713e232SGeorge Wilson 
8400713e232SGeorge Wilson 	ASSERT3P(rt->rt_arg, ==, msp);
8410713e232SGeorge Wilson 	ASSERT3P(msp->ms_tree, ==, rt);
8420713e232SGeorge Wilson 	VERIFY(!msp->ms_condensing);
8430713e232SGeorge Wilson 	avl_add(&msp->ms_size_tree, rs);
8440713e232SGeorge Wilson }
8450713e232SGeorge Wilson 
8460713e232SGeorge Wilson static void
metaslab_rt_remove(range_tree_t * rt,range_seg_t * rs,void * arg)8470713e232SGeorge Wilson metaslab_rt_remove(range_tree_t *rt, range_seg_t *rs, void *arg)
8480713e232SGeorge Wilson {
8490713e232SGeorge Wilson 	metaslab_t *msp = arg;
8500713e232SGeorge Wilson 
8510713e232SGeorge Wilson 	ASSERT3P(rt->rt_arg, ==, msp);
8520713e232SGeorge Wilson 	ASSERT3P(msp->ms_tree, ==, rt);
8530713e232SGeorge Wilson 	VERIFY(!msp->ms_condensing);
8540713e232SGeorge Wilson 	avl_remove(&msp->ms_size_tree, rs);
8550713e232SGeorge Wilson }
8560713e232SGeorge Wilson 
8570713e232SGeorge Wilson static void
metaslab_rt_vacate(range_tree_t * rt,void * arg)8580713e232SGeorge Wilson metaslab_rt_vacate(range_tree_t *rt, void *arg)
8590713e232SGeorge Wilson {
8600713e232SGeorge Wilson 	metaslab_t *msp = arg;
8610713e232SGeorge Wilson 
8620713e232SGeorge Wilson 	ASSERT3P(rt->rt_arg, ==, msp);
8630713e232SGeorge Wilson 	ASSERT3P(msp->ms_tree, ==, rt);
8640713e232SGeorge Wilson 
8650713e232SGeorge Wilson 	/*
8660713e232SGeorge Wilson 	 * Normally one would walk the tree freeing nodes along the way.
8670713e232SGeorge Wilson 	 * Since the nodes are shared with the range trees we can avoid
8680713e232SGeorge Wilson 	 * walking all nodes and just reinitialize the avl tree. The nodes
8690713e232SGeorge Wilson 	 * will be freed by the range tree, so we don't want to free them here.
8700713e232SGeorge Wilson 	 */
8710713e232SGeorge Wilson 	avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
8720713e232SGeorge Wilson 	    sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
8730713e232SGeorge Wilson }
8740713e232SGeorge Wilson 
8750713e232SGeorge Wilson static range_tree_ops_t metaslab_rt_ops = {
8760713e232SGeorge Wilson 	metaslab_rt_create,
8770713e232SGeorge Wilson 	metaslab_rt_destroy,
8780713e232SGeorge Wilson 	metaslab_rt_add,
8790713e232SGeorge Wilson 	metaslab_rt_remove,
8800713e232SGeorge Wilson 	metaslab_rt_vacate
8810713e232SGeorge Wilson };
8820713e232SGeorge Wilson 
8830713e232SGeorge Wilson /*
8840713e232SGeorge Wilson  * ==========================================================================
8850713e232SGeorge Wilson  * Metaslab block operations
8860713e232SGeorge Wilson  * ==========================================================================
8870713e232SGeorge Wilson  */
8880713e232SGeorge Wilson 
8890713e232SGeorge Wilson /*
8900713e232SGeorge Wilson  * Return the maximum contiguous segment within the metaslab.
8910713e232SGeorge Wilson  */
8920713e232SGeorge Wilson uint64_t
metaslab_block_maxsize(metaslab_t * msp)8930713e232SGeorge Wilson metaslab_block_maxsize(metaslab_t *msp)
8940713e232SGeorge Wilson {
8950713e232SGeorge Wilson 	avl_tree_t *t = &msp->ms_size_tree;
8960713e232SGeorge Wilson 	range_seg_t *rs;
8970713e232SGeorge Wilson 
8980713e232SGeorge Wilson 	if (t == NULL || (rs = avl_last(t)) == NULL)
8990713e232SGeorge Wilson 		return (0ULL);
9000713e232SGeorge Wilson 
9010713e232SGeorge Wilson 	return (rs->rs_end - rs->rs_start);
9020713e232SGeorge Wilson }
9030713e232SGeorge Wilson 
9040713e232SGeorge Wilson uint64_t
metaslab_block_alloc(metaslab_t * msp,uint64_t size)9050713e232SGeorge Wilson metaslab_block_alloc(metaslab_t *msp, uint64_t size)
9060713e232SGeorge Wilson {
9070713e232SGeorge Wilson 	uint64_t start;
9080713e232SGeorge Wilson 	range_tree_t *rt = msp->ms_tree;
9090713e232SGeorge Wilson 
9100713e232SGeorge Wilson 	VERIFY(!msp->ms_condensing);
9110713e232SGeorge Wilson 
9120713e232SGeorge Wilson 	start = msp->ms_ops->msop_alloc(msp, size);
9130713e232SGeorge Wilson 	if (start != -1ULL) {
9140713e232SGeorge Wilson 		vdev_t *vd = msp->ms_group->mg_vd;
9150713e232SGeorge Wilson 
9160713e232SGeorge Wilson 		VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
9170713e232SGeorge Wilson 		VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
9180713e232SGeorge Wilson 		VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
9190713e232SGeorge Wilson 		range_tree_remove(rt, start, size);
9200713e232SGeorge Wilson 	}
9210713e232SGeorge Wilson 	return (start);
9220713e232SGeorge Wilson }
9230713e232SGeorge Wilson 
9240713e232SGeorge Wilson /*
9250713e232SGeorge Wilson  * ==========================================================================
9260713e232SGeorge Wilson  * Common allocator routines
9270713e232SGeorge Wilson  * ==========================================================================
9280713e232SGeorge Wilson  */
9290713e232SGeorge Wilson 
9300713e232SGeorge Wilson /*
931d6e555bdSGeorge Wilson  * This is a helper function that can be used by the allocator to find
932d6e555bdSGeorge Wilson  * a suitable block to allocate. This will search the specified AVL
933d6e555bdSGeorge Wilson  * tree looking for a block that matches the specified criteria.
934fa9e4066Sahrens  */
935fa9e4066Sahrens static uint64_t
metaslab_block_picker(avl_tree_t * t,uint64_t * cursor,uint64_t size,uint64_t align)936d6e555bdSGeorge Wilson metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
937d6e555bdSGeorge Wilson     uint64_t align)
938fa9e4066Sahrens {
9390713e232SGeorge Wilson 	range_seg_t *rs, rsearch;
940fa9e4066Sahrens 	avl_index_t where;
941fa9e4066Sahrens 
9420713e232SGeorge Wilson 	rsearch.rs_start = *cursor;
9430713e232SGeorge Wilson 	rsearch.rs_end = *cursor + size;
944fa9e4066Sahrens 
9450713e232SGeorge Wilson 	rs = avl_find(t, &rsearch, &where);
9460713e232SGeorge Wilson 	if (rs == NULL)
9470713e232SGeorge Wilson 		rs = avl_nearest(t, where, AVL_AFTER);
948fa9e4066Sahrens 
9490713e232SGeorge Wilson 	while (rs != NULL) {
9500713e232SGeorge Wilson 		uint64_t offset = P2ROUNDUP(rs->rs_start, align);
951fa9e4066Sahrens 
9520713e232SGeorge Wilson 		if (offset + size <= rs->rs_end) {
953fa9e4066Sahrens 			*cursor = offset + size;
954fa9e4066Sahrens 			return (offset);
955fa9e4066Sahrens 		}
9560713e232SGeorge Wilson 		rs = AVL_NEXT(t, rs);
957fa9e4066Sahrens 	}
958fa9e4066Sahrens 
959ecc2d604Sbonwick 	/*
960ecc2d604Sbonwick 	 * If we know we've searched the whole map (*cursor == 0), give up.
961ecc2d604Sbonwick 	 * Otherwise, reset the cursor to the beginning and try again.
962ecc2d604Sbonwick 	 */
963ecc2d604Sbonwick 	if (*cursor == 0)
964ecc2d604Sbonwick 		return (-1ULL);
965ecc2d604Sbonwick 
966fa9e4066Sahrens 	*cursor = 0;
967d6e555bdSGeorge Wilson 	return (metaslab_block_picker(t, cursor, size, align));
968d6e555bdSGeorge Wilson }
969d6e555bdSGeorge Wilson 
97080eb36f2SGeorge Wilson /*
97180eb36f2SGeorge Wilson  * ==========================================================================
97280eb36f2SGeorge Wilson  * The first-fit block allocator
97380eb36f2SGeorge Wilson  * ==========================================================================
97480eb36f2SGeorge Wilson  */
97580eb36f2SGeorge Wilson static uint64_t
metaslab_ff_alloc(metaslab_t * msp,uint64_t size)9760713e232SGeorge Wilson metaslab_ff_alloc(metaslab_t *msp, uint64_t size)
97780eb36f2SGeorge Wilson {
9780713e232SGeorge Wilson 	/*
9790713e232SGeorge Wilson 	 * Find the largest power of 2 block size that evenly divides the
9800713e232SGeorge Wilson 	 * requested size. This is used to try to allocate blocks with similar
9810713e232SGeorge Wilson 	 * alignment from the same area of the metaslab (i.e. same cursor
9820713e232SGeorge Wilson 	 * bucket) but it does not guarantee that other allocations sizes
9830713e232SGeorge Wilson 	 * may exist in the same region.
9840713e232SGeorge Wilson 	 */
98580eb36f2SGeorge Wilson 	uint64_t align = size & -size;
986bf16b11eSMatthew Ahrens 	uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
9870713e232SGeorge Wilson 	avl_tree_t *t = &msp->ms_tree->rt_root;
98880eb36f2SGeorge Wilson 
98980eb36f2SGeorge Wilson 	return (metaslab_block_picker(t, cursor, size, align));
99080eb36f2SGeorge Wilson }
99180eb36f2SGeorge Wilson 
9920713e232SGeorge Wilson static metaslab_ops_t metaslab_ff_ops = {
9932e4c9986SGeorge Wilson 	metaslab_ff_alloc
99480eb36f2SGeorge Wilson };
99580eb36f2SGeorge Wilson 
99680eb36f2SGeorge Wilson /*
99780eb36f2SGeorge Wilson  * ==========================================================================
99880eb36f2SGeorge Wilson  * Dynamic block allocator -
99980eb36f2SGeorge Wilson  * Uses the first fit allocation scheme until space get low and then
100080eb36f2SGeorge Wilson  * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
100180eb36f2SGeorge Wilson  * and metaslab_df_free_pct to determine when to switch the allocation scheme.
100280eb36f2SGeorge Wilson  * ==========================================================================
100380eb36f2SGeorge Wilson  */
1004d6e555bdSGeorge Wilson static uint64_t
metaslab_df_alloc(metaslab_t * msp,uint64_t size)10050713e232SGeorge Wilson metaslab_df_alloc(metaslab_t *msp, uint64_t size)
1006d6e555bdSGeorge Wilson {
10070713e232SGeorge Wilson 	/*
10080713e232SGeorge Wilson 	 * Find the largest power of 2 block size that evenly divides the
10090713e232SGeorge Wilson 	 * requested size. This is used to try to allocate blocks with similar
10100713e232SGeorge Wilson 	 * alignment from the same area of the metaslab (i.e. same cursor
10110713e232SGeorge Wilson 	 * bucket) but it does not guarantee that other allocations sizes
10120713e232SGeorge Wilson 	 * may exist in the same region.
10130713e232SGeorge Wilson 	 */
1014d6e555bdSGeorge Wilson 	uint64_t align = size & -size;
1015bf16b11eSMatthew Ahrens 	uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
10160713e232SGeorge Wilson 	range_tree_t *rt = msp->ms_tree;
10170713e232SGeorge Wilson 	avl_tree_t *t = &rt->rt_root;
10180713e232SGeorge Wilson 	uint64_t max_size = metaslab_block_maxsize(msp);
10190713e232SGeorge Wilson 	int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1020d6e555bdSGeorge Wilson 
10210713e232SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
10220713e232SGeorge Wilson 	ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
1023d6e555bdSGeorge Wilson 
1024d6e555bdSGeorge Wilson 	if (max_size < size)
1025d6e555bdSGeorge Wilson 		return (-1ULL);
1026d6e555bdSGeorge Wilson 
1027d6e555bdSGeorge Wilson 	/*
1028d6e555bdSGeorge Wilson 	 * If we're running low on space switch to using the size
1029d6e555bdSGeorge Wilson 	 * sorted AVL tree (best-fit).
1030d6e555bdSGeorge Wilson 	 */
1031d6e555bdSGeorge Wilson 	if (max_size < metaslab_df_alloc_threshold ||
1032d6e555bdSGeorge Wilson 	    free_pct < metaslab_df_free_pct) {
10330713e232SGeorge Wilson 		t = &msp->ms_size_tree;
1034d6e555bdSGeorge Wilson 		*cursor = 0;
1035d6e555bdSGeorge Wilson 	}
1036d6e555bdSGeorge Wilson 
1037d6e555bdSGeorge Wilson 	return (metaslab_block_picker(t, cursor, size, 1ULL));
1038d6e555bdSGeorge Wilson }
1039d6e555bdSGeorge Wilson 
10400713e232SGeorge Wilson static metaslab_ops_t metaslab_df_ops = {
10412e4c9986SGeorge Wilson 	metaslab_df_alloc
104280eb36f2SGeorge Wilson };
104380eb36f2SGeorge Wilson 
104480eb36f2SGeorge Wilson /*
104580eb36f2SGeorge Wilson  * ==========================================================================
10460713e232SGeorge Wilson  * Cursor fit block allocator -
10470713e232SGeorge Wilson  * Select the largest region in the metaslab, set the cursor to the beginning
10480713e232SGeorge Wilson  * of the range and the cursor_end to the end of the range. As allocations
10490713e232SGeorge Wilson  * are made advance the cursor. Continue allocating from the cursor until
10500713e232SGeorge Wilson  * the range is exhausted and then find a new range.
105180eb36f2SGeorge Wilson  * ==========================================================================
105280eb36f2SGeorge Wilson  */
105380eb36f2SGeorge Wilson static uint64_t
metaslab_cf_alloc(metaslab_t * msp,uint64_t size)10540713e232SGeorge Wilson metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
105580eb36f2SGeorge Wilson {
10560713e232SGeorge Wilson 	range_tree_t *rt = msp->ms_tree;
10570713e232SGeorge Wilson 	avl_tree_t *t = &msp->ms_size_tree;
10580713e232SGeorge Wilson 	uint64_t *cursor = &msp->ms_lbas[0];
10590713e232SGeorge Wilson 	uint64_t *cursor_end = &msp->ms_lbas[1];
106080eb36f2SGeorge Wilson 	uint64_t offset = 0;
106180eb36f2SGeorge Wilson 
10620713e232SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
10630713e232SGeorge Wilson 	ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&rt->rt_root));
106480eb36f2SGeorge Wilson 
10650713e232SGeorge Wilson 	ASSERT3U(*cursor_end, >=, *cursor);
10660713e232SGeorge Wilson 
10670713e232SGeorge Wilson 	if ((*cursor + size) > *cursor_end) {
10680713e232SGeorge Wilson 		range_seg_t *rs;
10690713e232SGeorge Wilson 
10700713e232SGeorge Wilson 		rs = avl_last(&msp->ms_size_tree);
10710713e232SGeorge Wilson 		if (rs == NULL || (rs->rs_end - rs->rs_start) < size)
107280eb36f2SGeorge Wilson 			return (-1ULL);
107380eb36f2SGeorge Wilson 
10740713e232SGeorge Wilson 		*cursor = rs->rs_start;
10750713e232SGeorge Wilson 		*cursor_end = rs->rs_end;
107680eb36f2SGeorge Wilson 	}
10770713e232SGeorge Wilson 
10780713e232SGeorge Wilson 	offset = *cursor;
10790713e232SGeorge Wilson 	*cursor += size;
10800713e232SGeorge Wilson 
108180eb36f2SGeorge Wilson 	return (offset);
108280eb36f2SGeorge Wilson }
108380eb36f2SGeorge Wilson 
10840713e232SGeorge Wilson static metaslab_ops_t metaslab_cf_ops = {
10852e4c9986SGeorge Wilson 	metaslab_cf_alloc
108680eb36f2SGeorge Wilson };
108780eb36f2SGeorge Wilson 
10880713e232SGeorge Wilson /*
10890713e232SGeorge Wilson  * ==========================================================================
10900713e232SGeorge Wilson  * New dynamic fit allocator -
10910713e232SGeorge Wilson  * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
10920713e232SGeorge Wilson  * contiguous blocks. If no region is found then just use the largest segment
10930713e232SGeorge Wilson  * that remains.
10940713e232SGeorge Wilson  * ==========================================================================
10950713e232SGeorge Wilson  */
10960713e232SGeorge Wilson 
10970713e232SGeorge Wilson /*
10980713e232SGeorge Wilson  * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
10990713e232SGeorge Wilson  * to request from the allocator.
11000713e232SGeorge Wilson  */
11018d18220dSMark J Musante uint64_t metaslab_ndf_clump_shift = 4;
11028d18220dSMark J Musante 
110380eb36f2SGeorge Wilson static uint64_t
metaslab_ndf_alloc(metaslab_t * msp,uint64_t size)11040713e232SGeorge Wilson metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
110580eb36f2SGeorge Wilson {
11060713e232SGeorge Wilson 	avl_tree_t *t = &msp->ms_tree->rt_root;
110780eb36f2SGeorge Wilson 	avl_index_t where;
11080713e232SGeorge Wilson 	range_seg_t *rs, rsearch;
1109bf16b11eSMatthew Ahrens 	uint64_t hbit = highbit64(size);
11100713e232SGeorge Wilson 	uint64_t *cursor = &msp->ms_lbas[hbit - 1];
11110713e232SGeorge Wilson 	uint64_t max_size = metaslab_block_maxsize(msp);
111280eb36f2SGeorge Wilson 
11130713e232SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
11140713e232SGeorge Wilson 	ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
111580eb36f2SGeorge Wilson 
111680eb36f2SGeorge Wilson 	if (max_size < size)
111780eb36f2SGeorge Wilson 		return (-1ULL);
111880eb36f2SGeorge Wilson 
11190713e232SGeorge Wilson 	rsearch.rs_start = *cursor;
11200713e232SGeorge Wilson 	rsearch.rs_end = *cursor + size;
112180eb36f2SGeorge Wilson 
11220713e232SGeorge Wilson 	rs = avl_find(t, &rsearch, &where);
11230713e232SGeorge Wilson 	if (rs == NULL || (rs->rs_end - rs->rs_start) < size) {
11240713e232SGeorge Wilson 		t = &msp->ms_size_tree;
112580eb36f2SGeorge Wilson 
11260713e232SGeorge Wilson 		rsearch.rs_start = 0;
11270713e232SGeorge Wilson 		rsearch.rs_end = MIN(max_size,
11288d18220dSMark J Musante 		    1ULL << (hbit + metaslab_ndf_clump_shift));
11290713e232SGeorge Wilson 		rs = avl_find(t, &rsearch, &where);
11300713e232SGeorge Wilson 		if (rs == NULL)
11310713e232SGeorge Wilson 			rs = avl_nearest(t, where, AVL_AFTER);
11320713e232SGeorge Wilson 		ASSERT(rs != NULL);
113380eb36f2SGeorge Wilson 	}
113480eb36f2SGeorge Wilson 
11350713e232SGeorge Wilson 	if ((rs->rs_end - rs->rs_start) >= size) {
11360713e232SGeorge Wilson 		*cursor = rs->rs_start + size;
11370713e232SGeorge Wilson 		return (rs->rs_start);
113880eb36f2SGeorge Wilson 	}
113980eb36f2SGeorge Wilson 	return (-1ULL);
114080eb36f2SGeorge Wilson }
114180eb36f2SGeorge Wilson 
11420713e232SGeorge Wilson static metaslab_ops_t metaslab_ndf_ops = {
11432e4c9986SGeorge Wilson 	metaslab_ndf_alloc
1144d6e555bdSGeorge Wilson };
1145d6e555bdSGeorge Wilson 
11460713e232SGeorge Wilson metaslab_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
1147d6e555bdSGeorge Wilson 
1148d6e555bdSGeorge Wilson /*
1149ecc2d604Sbonwick  * ==========================================================================
1150ecc2d604Sbonwick  * Metaslabs
1151ecc2d604Sbonwick  * ==========================================================================
1152ecc2d604Sbonwick  */
11530713e232SGeorge Wilson 
11540713e232SGeorge Wilson /*
11550713e232SGeorge Wilson  * Wait for any in-progress metaslab loads to complete.
11560713e232SGeorge Wilson  */
11570713e232SGeorge Wilson void
metaslab_load_wait(metaslab_t * msp)11580713e232SGeorge Wilson metaslab_load_wait(metaslab_t *msp)
11590713e232SGeorge Wilson {
11600713e232SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
11610713e232SGeorge Wilson 
11620713e232SGeorge Wilson 	while (msp->ms_loading) {
11630713e232SGeorge Wilson 		ASSERT(!msp->ms_loaded);
11640713e232SGeorge Wilson 		cv_wait(&msp->ms_load_cv, &msp->ms_lock);
11650713e232SGeorge Wilson 	}
11660713e232SGeorge Wilson }
11670713e232SGeorge Wilson 
11680713e232SGeorge Wilson int
metaslab_load(metaslab_t * msp)11690713e232SGeorge Wilson metaslab_load(metaslab_t *msp)
11700713e232SGeorge Wilson {
11710713e232SGeorge Wilson 	int error = 0;
11720713e232SGeorge Wilson 
11730713e232SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
11740713e232SGeorge Wilson 	ASSERT(!msp->ms_loaded);
11750713e232SGeorge Wilson 	ASSERT(!msp->ms_loading);
11760713e232SGeorge Wilson 
11770713e232SGeorge Wilson 	msp->ms_loading = B_TRUE;
11780713e232SGeorge Wilson 
11790713e232SGeorge Wilson 	/*
11800713e232SGeorge Wilson 	 * If the space map has not been allocated yet, then treat
11810713e232SGeorge Wilson 	 * all the space in the metaslab as free and add it to the
11820713e232SGeorge Wilson 	 * ms_tree.
11830713e232SGeorge Wilson 	 */
11840713e232SGeorge Wilson 	if (msp->ms_sm != NULL)
11850713e232SGeorge Wilson 		error = space_map_load(msp->ms_sm, msp->ms_tree, SM_FREE);
11860713e232SGeorge Wilson 	else
11870713e232SGeorge Wilson 		range_tree_add(msp->ms_tree, msp->ms_start, msp->ms_size);
11880713e232SGeorge Wilson 
11890713e232SGeorge Wilson 	msp->ms_loaded = (error == 0);
11900713e232SGeorge Wilson 	msp->ms_loading = B_FALSE;
11910713e232SGeorge Wilson 
11920713e232SGeorge Wilson 	if (msp->ms_loaded) {
11930713e232SGeorge Wilson 		for (int t = 0; t < TXG_DEFER_SIZE; t++) {
11940713e232SGeorge Wilson 			range_tree_walk(msp->ms_defertree[t],
11950713e232SGeorge Wilson 			    range_tree_remove, msp->ms_tree);
11960713e232SGeorge Wilson 		}
11970713e232SGeorge Wilson 	}
11980713e232SGeorge Wilson 	cv_broadcast(&msp->ms_load_cv);
11990713e232SGeorge Wilson 	return (error);
12000713e232SGeorge Wilson }
12010713e232SGeorge Wilson 
12020713e232SGeorge Wilson void
metaslab_unload(metaslab_t * msp)12030713e232SGeorge Wilson metaslab_unload(metaslab_t *msp)
12040713e232SGeorge Wilson {
12050713e232SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
12060713e232SGeorge Wilson 	range_tree_vacate(msp->ms_tree, NULL, NULL);
12070713e232SGeorge Wilson 	msp->ms_loaded = B_FALSE;
12080713e232SGeorge Wilson 	msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
12090713e232SGeorge Wilson }
12100713e232SGeorge Wilson 
1211*1e9bd7ecSPrakash Surya int
metaslab_init(metaslab_group_t * mg,uint64_t id,uint64_t object,uint64_t txg,metaslab_t ** msp)1212*1e9bd7ecSPrakash Surya metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object, uint64_t txg,
1213*1e9bd7ecSPrakash Surya     metaslab_t **msp)
1214ecc2d604Sbonwick {
1215ecc2d604Sbonwick 	vdev_t *vd = mg->mg_vd;
12160713e232SGeorge Wilson 	objset_t *mos = vd->vdev_spa->spa_meta_objset;
1217*1e9bd7ecSPrakash Surya 	metaslab_t *ms;
1218*1e9bd7ecSPrakash Surya 	int error;
1219ecc2d604Sbonwick 
1220*1e9bd7ecSPrakash Surya 	ms = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
1221*1e9bd7ecSPrakash Surya 	mutex_init(&ms->ms_lock, NULL, MUTEX_DEFAULT, NULL);
1222*1e9bd7ecSPrakash Surya 	cv_init(&ms->ms_load_cv, NULL, CV_DEFAULT, NULL);
1223*1e9bd7ecSPrakash Surya 	ms->ms_id = id;
1224*1e9bd7ecSPrakash Surya 	ms->ms_start = id << vd->vdev_ms_shift;
1225*1e9bd7ecSPrakash Surya 	ms->ms_size = 1ULL << vd->vdev_ms_shift;
1226ecc2d604Sbonwick 
1227ecc2d604Sbonwick 	/*
12280713e232SGeorge Wilson 	 * We only open space map objects that already exist. All others
12290713e232SGeorge Wilson 	 * will be opened when we finally allocate an object for it.
12300713e232SGeorge Wilson 	 */
12310713e232SGeorge Wilson 	if (object != 0) {
1232*1e9bd7ecSPrakash Surya 		error = space_map_open(&ms->ms_sm, mos, object, ms->ms_start,
1233*1e9bd7ecSPrakash Surya 		    ms->ms_size, vd->vdev_ashift, &ms->ms_lock);
1234*1e9bd7ecSPrakash Surya 
1235*1e9bd7ecSPrakash Surya 		if (error != 0) {
1236*1e9bd7ecSPrakash Surya 			kmem_free(ms, sizeof (metaslab_t));
1237*1e9bd7ecSPrakash Surya 			return (error);
1238*1e9bd7ecSPrakash Surya 		}
1239*1e9bd7ecSPrakash Surya 
1240*1e9bd7ecSPrakash Surya 		ASSERT(ms->ms_sm != NULL);
12410713e232SGeorge Wilson 	}
12420713e232SGeorge Wilson 
12430713e232SGeorge Wilson 	/*
12440713e232SGeorge Wilson 	 * We create the main range tree here, but we don't create the
12450713e232SGeorge Wilson 	 * alloctree and freetree until metaslab_sync_done().  This serves
1246ecc2d604Sbonwick 	 * two purposes: it allows metaslab_sync_done() to detect the
1247ecc2d604Sbonwick 	 * addition of new space; and for debugging, it ensures that we'd
1248ecc2d604Sbonwick 	 * data fault on any attempt to use this metaslab before it's ready.
1249ecc2d604Sbonwick 	 */
1250*1e9bd7ecSPrakash Surya 	ms->ms_tree = range_tree_create(&metaslab_rt_ops, ms, &ms->ms_lock);
1251*1e9bd7ecSPrakash Surya 	metaslab_group_add(mg, ms);
1252ecc2d604Sbonwick 
1253*1e9bd7ecSPrakash Surya 	ms->ms_fragmentation = metaslab_fragmentation(ms);
1254*1e9bd7ecSPrakash Surya 	ms->ms_ops = mg->mg_class->mc_ops;
1255b24ab676SJeff Bonwick 
1256ecc2d604Sbonwick 	/*
1257ecc2d604Sbonwick 	 * If we're opening an existing pool (txg == 0) or creating
1258ecc2d604Sbonwick 	 * a new one (txg == TXG_INITIAL), all space is available now.
1259ecc2d604Sbonwick 	 * If we're adding space to an existing pool, the new space
1260ecc2d604Sbonwick 	 * does not become available until after this txg has synced.
1261ecc2d604Sbonwick 	 */
1262ecc2d604Sbonwick 	if (txg <= TXG_INITIAL)
1263*1e9bd7ecSPrakash Surya 		metaslab_sync_done(ms, 0);
1264ecc2d604Sbonwick 
12650713e232SGeorge Wilson 	/*
12660713e232SGeorge Wilson 	 * If metaslab_debug_load is set and we're initializing a metaslab
12670713e232SGeorge Wilson 	 * that has an allocated space_map object then load the its space
12680713e232SGeorge Wilson 	 * map so that can verify frees.
12690713e232SGeorge Wilson 	 */
1270*1e9bd7ecSPrakash Surya 	if (metaslab_debug_load && ms->ms_sm != NULL) {
1271*1e9bd7ecSPrakash Surya 		mutex_enter(&ms->ms_lock);
1272*1e9bd7ecSPrakash Surya 		VERIFY0(metaslab_load(ms));
1273*1e9bd7ecSPrakash Surya 		mutex_exit(&ms->ms_lock);
12740713e232SGeorge Wilson 	}
12750713e232SGeorge Wilson 
1276ecc2d604Sbonwick 	if (txg != 0) {
1277ecc2d604Sbonwick 		vdev_dirty(vd, 0, NULL, txg);
1278*1e9bd7ecSPrakash Surya 		vdev_dirty(vd, VDD_METASLAB, ms, txg);
1279ecc2d604Sbonwick 	}
1280ecc2d604Sbonwick 
1281*1e9bd7ecSPrakash Surya 	*msp = ms;
1282*1e9bd7ecSPrakash Surya 
1283*1e9bd7ecSPrakash Surya 	return (0);
1284ecc2d604Sbonwick }
1285ecc2d604Sbonwick 
1286ecc2d604Sbonwick void
metaslab_fini(metaslab_t * msp)1287ecc2d604Sbonwick metaslab_fini(metaslab_t *msp)
1288ecc2d604Sbonwick {
1289ecc2d604Sbonwick 	metaslab_group_t *mg = msp->ms_group;
1290ecc2d604Sbonwick 
1291ecc2d604Sbonwick 	metaslab_group_remove(mg, msp);
1292ecc2d604Sbonwick 
1293ecc2d604Sbonwick 	mutex_enter(&msp->ms_lock);
1294ecc2d604Sbonwick 
12950713e232SGeorge Wilson 	VERIFY(msp->ms_group == NULL);
12960713e232SGeorge Wilson 	vdev_space_update(mg->mg_vd, -space_map_allocated(msp->ms_sm),
12970713e232SGeorge Wilson 	    0, -msp->ms_size);
12980713e232SGeorge Wilson 	space_map_close(msp->ms_sm);
12990713e232SGeorge Wilson 
13000713e232SGeorge Wilson 	metaslab_unload(msp);
13010713e232SGeorge Wilson 	range_tree_destroy(msp->ms_tree);
1302ecc2d604Sbonwick 
1303468c413aSTim Haley 	for (int t = 0; t < TXG_SIZE; t++) {
13040713e232SGeorge Wilson 		range_tree_destroy(msp->ms_alloctree[t]);
13050713e232SGeorge Wilson 		range_tree_destroy(msp->ms_freetree[t]);
1306ecc2d604Sbonwick 	}
1307ecc2d604Sbonwick 
130816a4a807SGeorge Wilson 	for (int t = 0; t < TXG_DEFER_SIZE; t++) {
13090713e232SGeorge Wilson 		range_tree_destroy(msp->ms_defertree[t]);
131016a4a807SGeorge Wilson 	}
1311468c413aSTim Haley 
1312fb09f5aaSMadhav Suresh 	ASSERT0(msp->ms_deferspace);
1313468c413aSTim Haley 
1314ecc2d604Sbonwick 	mutex_exit(&msp->ms_lock);
13150713e232SGeorge Wilson 	cv_destroy(&msp->ms_load_cv);
13165ad82045Snd150628 	mutex_destroy(&msp->ms_lock);
1317ecc2d604Sbonwick 
1318ecc2d604Sbonwick 	kmem_free(msp, sizeof (metaslab_t));
1319ecc2d604Sbonwick }
1320ecc2d604Sbonwick 
13212e4c9986SGeorge Wilson #define	FRAGMENTATION_TABLE_SIZE	17
13222e4c9986SGeorge Wilson 
13230713e232SGeorge Wilson /*
13242e4c9986SGeorge Wilson  * This table defines a segment size based fragmentation metric that will
13252e4c9986SGeorge Wilson  * allow each metaslab to derive its own fragmentation value. This is done
13262e4c9986SGeorge Wilson  * by calculating the space in each bucket of the spacemap histogram and
13272e4c9986SGeorge Wilson  * multiplying that by the fragmetation metric in this table. Doing
13282e4c9986SGeorge Wilson  * this for all buckets and dividing it by the total amount of free
13292e4c9986SGeorge Wilson  * space in this metaslab (i.e. the total free space in all buckets) gives
13302e4c9986SGeorge Wilson  * us the fragmentation metric. This means that a high fragmentation metric
13312e4c9986SGeorge Wilson  * equates to most of the free space being comprised of small segments.
13322e4c9986SGeorge Wilson  * Conversely, if the metric is low, then most of the free space is in
13332e4c9986SGeorge Wilson  * large segments. A 10% change in fragmentation equates to approximately
13342e4c9986SGeorge Wilson  * double the number of segments.
13350713e232SGeorge Wilson  *
13362e4c9986SGeorge Wilson  * This table defines 0% fragmented space using 16MB segments. Testing has
13372e4c9986SGeorge Wilson  * shown that segments that are greater than or equal to 16MB do not suffer
13382e4c9986SGeorge Wilson  * from drastic performance problems. Using this value, we derive the rest
13392e4c9986SGeorge Wilson  * of the table. Since the fragmentation value is never stored on disk, it
13402e4c9986SGeorge Wilson  * is possible to change these calculations in the future.
13412e4c9986SGeorge Wilson  */
13422e4c9986SGeorge Wilson int zfs_frag_table[FRAGMENTATION_TABLE_SIZE] = {
13432e4c9986SGeorge Wilson 	100,	/* 512B	*/
13442e4c9986SGeorge Wilson 	100,	/* 1K	*/
13452e4c9986SGeorge Wilson 	98,	/* 2K	*/
13462e4c9986SGeorge Wilson 	95,	/* 4K	*/
13472e4c9986SGeorge Wilson 	90,	/* 8K	*/
13482e4c9986SGeorge Wilson 	80,	/* 16K	*/
13492e4c9986SGeorge Wilson 	70,	/* 32K	*/
13502e4c9986SGeorge Wilson 	60,	/* 64K	*/
13512e4c9986SGeorge Wilson 	50,	/* 128K	*/
13522e4c9986SGeorge Wilson 	40,	/* 256K	*/
13532e4c9986SGeorge Wilson 	30,	/* 512K	*/
13542e4c9986SGeorge Wilson 	20,	/* 1M	*/
13552e4c9986SGeorge Wilson 	15,	/* 2M	*/
13562e4c9986SGeorge Wilson 	10,	/* 4M	*/
13572e4c9986SGeorge Wilson 	5,	/* 8M	*/
13582e4c9986SGeorge Wilson 	0	/* 16M	*/
13592e4c9986SGeorge Wilson };
13602e4c9986SGeorge Wilson 
13612e4c9986SGeorge Wilson /*
13622e4c9986SGeorge Wilson  * Calclate the metaslab's fragmentation metric. A return value
13632e4c9986SGeorge Wilson  * of ZFS_FRAG_INVALID means that the metaslab has not been upgraded and does
13642e4c9986SGeorge Wilson  * not support this metric. Otherwise, the return value should be in the
13652e4c9986SGeorge Wilson  * range [0, 100].
13660713e232SGeorge Wilson  */
13670713e232SGeorge Wilson static uint64_t
metaslab_fragmentation(metaslab_t * msp)13682e4c9986SGeorge Wilson metaslab_fragmentation(metaslab_t *msp)
13690713e232SGeorge Wilson {
13702e4c9986SGeorge Wilson 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
13712e4c9986SGeorge Wilson 	uint64_t fragmentation = 0;
13722e4c9986SGeorge Wilson 	uint64_t total = 0;
13732e4c9986SGeorge Wilson 	boolean_t feature_enabled = spa_feature_is_enabled(spa,
13742e4c9986SGeorge Wilson 	    SPA_FEATURE_SPACEMAP_HISTOGRAM);
13752e4c9986SGeorge Wilson 
13762e4c9986SGeorge Wilson 	if (!feature_enabled)
13772e4c9986SGeorge Wilson 		return (ZFS_FRAG_INVALID);
13780713e232SGeorge Wilson 
13790713e232SGeorge Wilson 	/*
13802e4c9986SGeorge Wilson 	 * A null space map means that the entire metaslab is free
13812e4c9986SGeorge Wilson 	 * and thus is not fragmented.
13820713e232SGeorge Wilson 	 */
13832e4c9986SGeorge Wilson 	if (msp->ms_sm == NULL)
13840713e232SGeorge Wilson 		return (0);
13850713e232SGeorge Wilson 
13862e4c9986SGeorge Wilson 	/*
13872e4c9986SGeorge Wilson 	 * If this metaslab's space_map has not been upgraded, flag it
13882e4c9986SGeorge Wilson 	 * so that we upgrade next time we encounter it.
13892e4c9986SGeorge Wilson 	 */
13902e4c9986SGeorge Wilson 	if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
13912e4c9986SGeorge Wilson 		uint64_t txg = spa_syncing_txg(spa);
13922e4c9986SGeorge Wilson 		vdev_t *vd = msp->ms_group->mg_vd;
13932e4c9986SGeorge Wilson 
1394b1be2892SMatthew Ahrens 		if (spa_writeable(spa)) {
13952e4c9986SGeorge Wilson 			msp->ms_condense_wanted = B_TRUE;
13962e4c9986SGeorge Wilson 			vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
13972e4c9986SGeorge Wilson 			spa_dbgmsg(spa, "txg %llu, requesting force condense: "
13982e4c9986SGeorge Wilson 			    "msp %p, vd %p", txg, msp, vd);
1399b1be2892SMatthew Ahrens 		}
14002e4c9986SGeorge Wilson 		return (ZFS_FRAG_INVALID);
14012e4c9986SGeorge Wilson 	}
14022e4c9986SGeorge Wilson 
14032e4c9986SGeorge Wilson 	for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
14042e4c9986SGeorge Wilson 		uint64_t space = 0;
14052e4c9986SGeorge Wilson 		uint8_t shift = msp->ms_sm->sm_shift;
14062e4c9986SGeorge Wilson 		int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
14072e4c9986SGeorge Wilson 		    FRAGMENTATION_TABLE_SIZE - 1);
14082e4c9986SGeorge Wilson 
14090713e232SGeorge Wilson 		if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
14100713e232SGeorge Wilson 			continue;
14110713e232SGeorge Wilson 
14122e4c9986SGeorge Wilson 		space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
14132e4c9986SGeorge Wilson 		total += space;
14142e4c9986SGeorge Wilson 
14152e4c9986SGeorge Wilson 		ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
14162e4c9986SGeorge Wilson 		fragmentation += space * zfs_frag_table[idx];
14170713e232SGeorge Wilson 	}
1418ecc2d604Sbonwick 
14192e4c9986SGeorge Wilson 	if (total > 0)
14202e4c9986SGeorge Wilson 		fragmentation /= total;
14212e4c9986SGeorge Wilson 	ASSERT3U(fragmentation, <=, 100);
14222e4c9986SGeorge Wilson 	return (fragmentation);
14232e4c9986SGeorge Wilson }
14242e4c9986SGeorge Wilson 
14252e4c9986SGeorge Wilson /*
14262e4c9986SGeorge Wilson  * Compute a weight -- a selection preference value -- for the given metaslab.
14272e4c9986SGeorge Wilson  * This is based on the amount of free space, the level of fragmentation,
14282e4c9986SGeorge Wilson  * the LBA range, and whether the metaslab is loaded.
14292e4c9986SGeorge Wilson  */
1430fa9e4066Sahrens static uint64_t
metaslab_weight(metaslab_t * msp)1431ecc2d604Sbonwick metaslab_weight(metaslab_t *msp)
1432fa9e4066Sahrens {
143344cd46caSbillm 	metaslab_group_t *mg = msp->ms_group;
143444cd46caSbillm 	vdev_t *vd = mg->mg_vd;
1435ecc2d604Sbonwick 	uint64_t weight, space;
1436fa9e4066Sahrens 
1437fa9e4066Sahrens 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1438fa9e4066Sahrens 
1439ecc2d604Sbonwick 	/*
14409eb57f7fSGeorge Wilson 	 * This vdev is in the process of being removed so there is nothing
14419eb57f7fSGeorge Wilson 	 * for us to do here.
14429eb57f7fSGeorge Wilson 	 */
14439eb57f7fSGeorge Wilson 	if (vd->vdev_removing) {
14440713e232SGeorge Wilson 		ASSERT0(space_map_allocated(msp->ms_sm));
14459eb57f7fSGeorge Wilson 		ASSERT0(vd->vdev_ms_shift);
14469eb57f7fSGeorge Wilson 		return (0);
14479eb57f7fSGeorge Wilson 	}
14489eb57f7fSGeorge Wilson 
14499eb57f7fSGeorge Wilson 	/*
1450ecc2d604Sbonwick 	 * The baseline weight is the metaslab's free space.
1451ecc2d604Sbonwick 	 */
14520713e232SGeorge Wilson 	space = msp->ms_size - space_map_allocated(msp->ms_sm);
14532e4c9986SGeorge Wilson 
14542e4c9986SGeorge Wilson 	msp->ms_fragmentation = metaslab_fragmentation(msp);
14552e4c9986SGeorge Wilson 	if (metaslab_fragmentation_factor_enabled &&
14562e4c9986SGeorge Wilson 	    msp->ms_fragmentation != ZFS_FRAG_INVALID) {
14572e4c9986SGeorge Wilson 		/*
14582e4c9986SGeorge Wilson 		 * Use the fragmentation information to inversely scale
14592e4c9986SGeorge Wilson 		 * down the baseline weight. We need to ensure that we
14602e4c9986SGeorge Wilson 		 * don't exclude this metaslab completely when it's 100%
14612e4c9986SGeorge Wilson 		 * fragmented. To avoid this we reduce the fragmented value
14622e4c9986SGeorge Wilson 		 * by 1.
14632e4c9986SGeorge Wilson 		 */
14642e4c9986SGeorge Wilson 		space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
14652e4c9986SGeorge Wilson 
14662e4c9986SGeorge Wilson 		/*
14672e4c9986SGeorge Wilson 		 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
14682e4c9986SGeorge Wilson 		 * this metaslab again. The fragmentation metric may have
14692e4c9986SGeorge Wilson 		 * decreased the space to something smaller than
14702e4c9986SGeorge Wilson 		 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
14712e4c9986SGeorge Wilson 		 * so that we can consume any remaining space.
14722e4c9986SGeorge Wilson 		 */
14732e4c9986SGeorge Wilson 		if (space > 0 && space < SPA_MINBLOCKSIZE)
14742e4c9986SGeorge Wilson 			space = SPA_MINBLOCKSIZE;
14752e4c9986SGeorge Wilson 	}
1476ecc2d604Sbonwick 	weight = space;
1477ecc2d604Sbonwick 
1478ecc2d604Sbonwick 	/*
1479ecc2d604Sbonwick 	 * Modern disks have uniform bit density and constant angular velocity.
1480ecc2d604Sbonwick 	 * Therefore, the outer recording zones are faster (higher bandwidth)
1481ecc2d604Sbonwick 	 * than the inner zones by the ratio of outer to inner track diameter,
1482ecc2d604Sbonwick 	 * which is typically around 2:1.  We account for this by assigning
1483ecc2d604Sbonwick 	 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
1484ecc2d604Sbonwick 	 * In effect, this means that we'll select the metaslab with the most
1485ecc2d604Sbonwick 	 * free bandwidth rather than simply the one with the most free space.
1486ecc2d604Sbonwick 	 */
14872e4c9986SGeorge Wilson 	if (metaslab_lba_weighting_enabled) {
14880713e232SGeorge Wilson 		weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
1489ecc2d604Sbonwick 		ASSERT(weight >= space && weight <= 2 * space);
14902e4c9986SGeorge Wilson 	}
1491ecc2d604Sbonwick 
1492ecc2d604Sbonwick 	/*
149380eb36f2SGeorge Wilson 	 * If this metaslab is one we're actively using, adjust its
149480eb36f2SGeorge Wilson 	 * weight to make it preferable to any inactive metaslab so
14952e4c9986SGeorge Wilson 	 * we'll polish it off. If the fragmentation on this metaslab
14962e4c9986SGeorge Wilson 	 * has exceed our threshold, then don't mark it active.
1497ecc2d604Sbonwick 	 */
14982e4c9986SGeorge Wilson 	if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
14992e4c9986SGeorge Wilson 	    msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
150044cd46caSbillm 		weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
150180eb36f2SGeorge Wilson 	}
15020713e232SGeorge Wilson 
1503ecc2d604Sbonwick 	return (weight);
1504fa9e4066Sahrens }
1505ecc2d604Sbonwick 
1506ecc2d604Sbonwick static int
metaslab_activate(metaslab_t * msp,uint64_t activation_weight)150709c9d376SGeorge Wilson metaslab_activate(metaslab_t *msp, uint64_t activation_weight)
1508ecc2d604Sbonwick {
1509ecc2d604Sbonwick 	ASSERT(MUTEX_HELD(&msp->ms_lock));
1510ecc2d604Sbonwick 
151144cd46caSbillm 	if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
15120713e232SGeorge Wilson 		metaslab_load_wait(msp);
15130713e232SGeorge Wilson 		if (!msp->ms_loaded) {
15140713e232SGeorge Wilson 			int error = metaslab_load(msp);
1515ecc2d604Sbonwick 			if (error) {
1516ecc2d604Sbonwick 				metaslab_group_sort(msp->ms_group, msp, 0);
1517ecc2d604Sbonwick 				return (error);
1518ecc2d604Sbonwick 			}
1519468c413aSTim Haley 		}
1520d6e555bdSGeorge Wilson 
1521ecc2d604Sbonwick 		metaslab_group_sort(msp->ms_group, msp,
152244cd46caSbillm 		    msp->ms_weight | activation_weight);
1523ecc2d604Sbonwick 	}
15240713e232SGeorge Wilson 	ASSERT(msp->ms_loaded);
152544cd46caSbillm 	ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
1526ecc2d604Sbonwick 
1527ecc2d604Sbonwick 	return (0);
1528ecc2d604Sbonwick }
1529ecc2d604Sbonwick 
1530ecc2d604Sbonwick static void
metaslab_passivate(metaslab_t * msp,uint64_t size)1531ecc2d604Sbonwick metaslab_passivate(metaslab_t *msp, uint64_t size)
1532ecc2d604Sbonwick {
15335f5f7a6fSahrens 	/*
15345f5f7a6fSahrens 	 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
15355f5f7a6fSahrens 	 * this metaslab again.  In that case, it had better be empty,
15365f5f7a6fSahrens 	 * or we would be leaving space on the table.
15375f5f7a6fSahrens 	 */
15380713e232SGeorge Wilson 	ASSERT(size >= SPA_MINBLOCKSIZE || range_tree_space(msp->ms_tree) == 0);
153944cd46caSbillm 	metaslab_group_sort(msp->ms_group, msp, MIN(msp->ms_weight, size));
154044cd46caSbillm 	ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
1541ecc2d604Sbonwick }
1542ecc2d604Sbonwick 
15430713e232SGeorge Wilson static void
metaslab_preload(void * arg)15440713e232SGeorge Wilson metaslab_preload(void *arg)
15450713e232SGeorge Wilson {
15460713e232SGeorge Wilson 	metaslab_t *msp = arg;
15470713e232SGeorge Wilson 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
15480713e232SGeorge Wilson 
154930beaff4SGeorge Wilson 	ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
155030beaff4SGeorge Wilson 
15510713e232SGeorge Wilson 	mutex_enter(&msp->ms_lock);
15520713e232SGeorge Wilson 	metaslab_load_wait(msp);
15530713e232SGeorge Wilson 	if (!msp->ms_loaded)
15540713e232SGeorge Wilson 		(void) metaslab_load(msp);
15550713e232SGeorge Wilson 
1556ecc2d604Sbonwick 	/*
15570713e232SGeorge Wilson 	 * Set the ms_access_txg value so that we don't unload it right away.
15580713e232SGeorge Wilson 	 */
15590713e232SGeorge Wilson 	msp->ms_access_txg = spa_syncing_txg(spa) + metaslab_unload_delay + 1;
15600713e232SGeorge Wilson 	mutex_exit(&msp->ms_lock);
15610713e232SGeorge Wilson }
15620713e232SGeorge Wilson 
15630713e232SGeorge Wilson static void
metaslab_group_preload(metaslab_group_t * mg)15640713e232SGeorge Wilson metaslab_group_preload(metaslab_group_t *mg)
15650713e232SGeorge Wilson {
15660713e232SGeorge Wilson 	spa_t *spa = mg->mg_vd->vdev_spa;
15670713e232SGeorge Wilson 	metaslab_t *msp;
15680713e232SGeorge Wilson 	avl_tree_t *t = &mg->mg_metaslab_tree;
15690713e232SGeorge Wilson 	int m = 0;
15700713e232SGeorge Wilson 
15710713e232SGeorge Wilson 	if (spa_shutting_down(spa) || !metaslab_preload_enabled) {
15720713e232SGeorge Wilson 		taskq_wait(mg->mg_taskq);
15730713e232SGeorge Wilson 		return;
15740713e232SGeorge Wilson 	}
15750713e232SGeorge Wilson 
157630beaff4SGeorge Wilson 	mutex_enter(&mg->mg_lock);
15770713e232SGeorge Wilson 	/*
157830beaff4SGeorge Wilson 	 * Load the next potential metaslabs
15790713e232SGeorge Wilson 	 */
158030beaff4SGeorge Wilson 	msp = avl_first(t);
158130beaff4SGeorge Wilson 	while (msp != NULL) {
158230beaff4SGeorge Wilson 		metaslab_t *msp_next = AVL_NEXT(t, msp);
15830713e232SGeorge Wilson 
15842e4c9986SGeorge Wilson 		/*
15852e4c9986SGeorge Wilson 		 * We preload only the maximum number of metaslabs specified
15862e4c9986SGeorge Wilson 		 * by metaslab_preload_limit. If a metaslab is being forced
15872e4c9986SGeorge Wilson 		 * to condense then we preload it too. This will ensure
15882e4c9986SGeorge Wilson 		 * that force condensing happens in the next txg.
15892e4c9986SGeorge Wilson 		 */
15902e4c9986SGeorge Wilson 		if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
15912e4c9986SGeorge Wilson 			msp = msp_next;
15922e4c9986SGeorge Wilson 			continue;
15932e4c9986SGeorge Wilson 		}
15940713e232SGeorge Wilson 
159530beaff4SGeorge Wilson 		/*
159630beaff4SGeorge Wilson 		 * We must drop the metaslab group lock here to preserve
159730beaff4SGeorge Wilson 		 * lock ordering with the ms_lock (when grabbing both
159830beaff4SGeorge Wilson 		 * the mg_lock and the ms_lock, the ms_lock must be taken
159930beaff4SGeorge Wilson 		 * first).  As a result, it is possible that the ordering
160030beaff4SGeorge Wilson 		 * of the metaslabs within the avl tree may change before
160130beaff4SGeorge Wilson 		 * we reacquire the lock. The metaslab cannot be removed from
160230beaff4SGeorge Wilson 		 * the tree while we're in syncing context so it is safe to
160330beaff4SGeorge Wilson 		 * drop the mg_lock here. If the metaslabs are reordered
160430beaff4SGeorge Wilson 		 * nothing will break -- we just may end up loading a
160530beaff4SGeorge Wilson 		 * less than optimal one.
160630beaff4SGeorge Wilson 		 */
160730beaff4SGeorge Wilson 		mutex_exit(&mg->mg_lock);
16080713e232SGeorge Wilson 		VERIFY(taskq_dispatch(mg->mg_taskq, metaslab_preload,
16090713e232SGeorge Wilson 		    msp, TQ_SLEEP) != NULL);
161030beaff4SGeorge Wilson 		mutex_enter(&mg->mg_lock);
161130beaff4SGeorge Wilson 		msp = msp_next;
16120713e232SGeorge Wilson 	}
16130713e232SGeorge Wilson 	mutex_exit(&mg->mg_lock);
16140713e232SGeorge Wilson }
16150713e232SGeorge Wilson 
16160713e232SGeorge Wilson /*
16170713e232SGeorge Wilson  * Determine if the space map's on-disk footprint is past our tolerance
16180713e232SGeorge Wilson  * for inefficiency. We would like to use the following criteria to make
16190713e232SGeorge Wilson  * our decision:
162016a4a807SGeorge Wilson  *
162116a4a807SGeorge Wilson  * 1. The size of the space map object should not dramatically increase as a
16220713e232SGeorge Wilson  * result of writing out the free space range tree.
162316a4a807SGeorge Wilson  *
162416a4a807SGeorge Wilson  * 2. The minimal on-disk space map representation is zfs_condense_pct/100
16250713e232SGeorge Wilson  * times the size than the free space range tree representation
16260713e232SGeorge Wilson  * (i.e. zfs_condense_pct = 110 and in-core = 1MB, minimal = 1.1.MB).
162716a4a807SGeorge Wilson  *
16282a104a52SAlex Reece  * 3. The on-disk size of the space map should actually decrease.
16292a104a52SAlex Reece  *
163016a4a807SGeorge Wilson  * Checking the first condition is tricky since we don't want to walk
163116a4a807SGeorge Wilson  * the entire AVL tree calculating the estimated on-disk size. Instead we
16320713e232SGeorge Wilson  * use the size-ordered range tree in the metaslab and calculate the
16330713e232SGeorge Wilson  * size required to write out the largest segment in our free tree. If the
163416a4a807SGeorge Wilson  * size required to represent that segment on disk is larger than the space
163516a4a807SGeorge Wilson  * map object then we avoid condensing this map.
163616a4a807SGeorge Wilson  *
163716a4a807SGeorge Wilson  * To determine the second criterion we use a best-case estimate and assume
163816a4a807SGeorge Wilson  * each segment can be represented on-disk as a single 64-bit entry. We refer
163916a4a807SGeorge Wilson  * to this best-case estimate as the space map's minimal form.
16402a104a52SAlex Reece  *
16412a104a52SAlex Reece  * Unfortunately, we cannot compute the on-disk size of the space map in this
16422a104a52SAlex Reece  * context because we cannot accurately compute the effects of compression, etc.
16432a104a52SAlex Reece  * Instead, we apply the heuristic described in the block comment for
16442a104a52SAlex Reece  * zfs_metaslab_condense_block_threshold - we only condense if the space used
16452a104a52SAlex Reece  * is greater than a threshold number of blocks.
164616a4a807SGeorge Wilson  */
164716a4a807SGeorge Wilson static boolean_t
metaslab_should_condense(metaslab_t * msp)164816a4a807SGeorge Wilson metaslab_should_condense(metaslab_t *msp)
164916a4a807SGeorge Wilson {
16500713e232SGeorge Wilson 	space_map_t *sm = msp->ms_sm;
16510713e232SGeorge Wilson 	range_seg_t *rs;
16522a104a52SAlex Reece 	uint64_t size, entries, segsz, object_size, optimal_size, record_size;
16532a104a52SAlex Reece 	dmu_object_info_t doi;
16542a104a52SAlex Reece 	uint64_t vdev_blocksize = 1 << msp->ms_group->mg_vd->vdev_ashift;
165516a4a807SGeorge Wilson 
165616a4a807SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
16570713e232SGeorge Wilson 	ASSERT(msp->ms_loaded);
165816a4a807SGeorge Wilson 
165916a4a807SGeorge Wilson 	/*
16600713e232SGeorge Wilson 	 * Use the ms_size_tree range tree, which is ordered by size, to
16612e4c9986SGeorge Wilson 	 * obtain the largest segment in the free tree. We always condense
16622e4c9986SGeorge Wilson 	 * metaslabs that are empty and metaslabs for which a condense
16632e4c9986SGeorge Wilson 	 * request has been made.
166416a4a807SGeorge Wilson 	 */
16650713e232SGeorge Wilson 	rs = avl_last(&msp->ms_size_tree);
16662e4c9986SGeorge Wilson 	if (rs == NULL || msp->ms_condense_wanted)
166716a4a807SGeorge Wilson 		return (B_TRUE);
166816a4a807SGeorge Wilson 
166916a4a807SGeorge Wilson 	/*
167016a4a807SGeorge Wilson 	 * Calculate the number of 64-bit entries this segment would
167116a4a807SGeorge Wilson 	 * require when written to disk. If this single segment would be
167216a4a807SGeorge Wilson 	 * larger on-disk than the entire current on-disk structure, then
167316a4a807SGeorge Wilson 	 * clearly condensing will increase the on-disk structure size.
167416a4a807SGeorge Wilson 	 */
16750713e232SGeorge Wilson 	size = (rs->rs_end - rs->rs_start) >> sm->sm_shift;
167616a4a807SGeorge Wilson 	entries = size / (MIN(size, SM_RUN_MAX));
167716a4a807SGeorge Wilson 	segsz = entries * sizeof (uint64_t);
167816a4a807SGeorge Wilson 
16792a104a52SAlex Reece 	optimal_size = sizeof (uint64_t) * avl_numnodes(&msp->ms_tree->rt_root);
16802a104a52SAlex Reece 	object_size = space_map_length(msp->ms_sm);
16812a104a52SAlex Reece 
16822a104a52SAlex Reece 	dmu_object_info_from_db(sm->sm_dbuf, &doi);
16832a104a52SAlex Reece 	record_size = MAX(doi.doi_data_block_size, vdev_blocksize);
16842a104a52SAlex Reece 
16852a104a52SAlex Reece 	return (segsz <= object_size &&
16862a104a52SAlex Reece 	    object_size >= (optimal_size * zfs_condense_pct / 100) &&
16872a104a52SAlex Reece 	    object_size > zfs_metaslab_condense_block_threshold * record_size);
168816a4a807SGeorge Wilson }
168916a4a807SGeorge Wilson 
169016a4a807SGeorge Wilson /*
169116a4a807SGeorge Wilson  * Condense the on-disk space map representation to its minimized form.
169216a4a807SGeorge Wilson  * The minimized form consists of a small number of allocations followed by
16930713e232SGeorge Wilson  * the entries of the free range tree.
169416a4a807SGeorge Wilson  */
169516a4a807SGeorge Wilson static void
metaslab_condense(metaslab_t * msp,uint64_t txg,dmu_tx_t * tx)169616a4a807SGeorge Wilson metaslab_condense(metaslab_t *msp, uint64_t txg, dmu_tx_t *tx)
169716a4a807SGeorge Wilson {
169816a4a807SGeorge Wilson 	spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
16990713e232SGeorge Wilson 	range_tree_t *freetree = msp->ms_freetree[txg & TXG_MASK];
17000713e232SGeorge Wilson 	range_tree_t *condense_tree;
17010713e232SGeorge Wilson 	space_map_t *sm = msp->ms_sm;
170216a4a807SGeorge Wilson 
170316a4a807SGeorge Wilson 	ASSERT(MUTEX_HELD(&msp->ms_lock));
170416a4a807SGeorge Wilson 	ASSERT3U(spa_sync_pass(spa), ==, 1);
17050713e232SGeorge Wilson 	ASSERT(msp->ms_loaded);
170616a4a807SGeorge Wilson 
17072e4c9986SGeorge Wilson 
170816a4a807SGeorge Wilson 	spa_dbgmsg(spa, "condensing: txg %llu, msp[%llu] %p, "
17092e4c9986SGeorge Wilson 	    "smp size %llu, segments %lu, forcing condense=%s", txg,
17102e4c9986SGeorge Wilson 	    msp->ms_id, msp, space_map_length(msp->ms_sm),
17112e4c9986SGeorge Wilson 	    avl_numnodes(&msp->ms_tree->rt_root),
17122e4c9986SGeorge Wilson 	    msp->ms_condense_wanted ? "TRUE" : "FALSE");
17132e4c9986SGeorge Wilson 
17142e4c9986SGeorge Wilson 	msp->ms_condense_wanted = B_FALSE;
171516a4a807SGeorge Wilson 
171616a4a807SGeorge Wilson 	/*
17170713e232SGeorge Wilson 	 * Create an range tree that is 100% allocated. We remove segments
171816a4a807SGeorge Wilson 	 * that have been freed in this txg, any deferred frees that exist,
171916a4a807SGeorge Wilson 	 * and any allocation in the future. Removing segments should be
17200713e232SGeorge Wilson 	 * a relatively inexpensive operation since we expect these trees to
17210713e232SGeorge Wilson 	 * have a small number of nodes.
172216a4a807SGeorge Wilson 	 */
17230713e232SGeorge Wilson 	condense_tree = range_tree_create(NULL, NULL, &msp->ms_lock);
17240713e232SGeorge Wilson 	range_tree_add(condense_tree, msp->ms_start, msp->ms_size);
172516a4a807SGeorge Wilson 
172616a4a807SGeorge Wilson 	/*
17270713e232SGeorge Wilson 	 * Remove what's been freed in this txg from the condense_tree.
172816a4a807SGeorge Wilson 	 * Since we're in sync_pass 1, we know that all the frees from
17290713e232SGeorge Wilson 	 * this txg are in the freetree.
173016a4a807SGeorge Wilson 	 */
17310713e232SGeorge Wilson 	range_tree_walk(freetree, range_tree_remove, condense_tree);
173216a4a807SGeorge Wilson 
17330713e232SGeorge Wilson 	for (int t = 0; t < TXG_DEFER_SIZE; t++) {
17340713e232SGeorge Wilson 		range_tree_walk(msp->ms_defertree[t],
17350713e232SGeorge Wilson 		    range_tree_remove, condense_tree);
17360713e232SGeorge Wilson 	}
173716a4a807SGeorge Wilson 
17380713e232SGeorge Wilson 	for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
17390713e232SGeorge Wilson 		range_tree_walk(msp->ms_alloctree[(txg + t) & TXG_MASK],
17400713e232SGeorge Wilson 		    range_tree_remove, condense_tree);
17410713e232SGeorge Wilson 	}
174216a4a807SGeorge Wilson 
174316a4a807SGeorge Wilson 	/*
174416a4a807SGeorge Wilson 	 * We're about to drop the metaslab's lock thus allowing
174516a4a807SGeorge Wilson 	 * other consumers to change it's content. Set the
17460713e232SGeorge Wilson 	 * metaslab's ms_condensing flag to ensure that
174716a4a807SGeorge Wilson 	 * allocations on this metaslab do not occur while we're
174816a4a807SGeorge Wilson 	 * in the middle of committing it to disk. This is only critical
17490713e232SGeorge Wilson 	 * for the ms_tree as all other range trees use per txg
175016a4a807SGeorge Wilson 	 * views of their content.
175116a4a807SGeorge Wilson 	 */
17520713e232SGeorge Wilson 	msp->ms_condensing = B_TRUE;
175316a4a807SGeorge Wilson 
175416a4a807SGeorge Wilson 	mutex_exit(&msp->ms_lock);
17550713e232SGeorge Wilson 	space_map_truncate(sm, tx);
175616a4a807SGeorge Wilson 	mutex_enter(&msp->ms_lock);
175716a4a807SGeorge Wilson 
175816a4a807SGeorge Wilson 	/*
175916a4a807SGeorge Wilson 	 * While we would ideally like to create a space_map representation
176016a4a807SGeorge Wilson 	 * that consists only of allocation records, doing so can be
17610713e232SGeorge Wilson 	 * prohibitively expensive because the in-core free tree can be
176216a4a807SGeorge Wilson 	 * large, and therefore computationally expensive to subtract
17630713e232SGeorge Wilson 	 * from the condense_tree. Instead we sync out two trees, a cheap
17640713e232SGeorge Wilson 	 * allocation only tree followed by the in-core free tree. While not
176516a4a807SGeorge Wilson 	 * optimal, this is typically close to optimal, and much cheaper to
176616a4a807SGeorge Wilson 	 * compute.
176716a4a807SGeorge Wilson 	 */
17680713e232SGeorge Wilson 	space_map_write(sm, condense_tree, SM_ALLOC, tx);
17690713e232SGeorge Wilson 	range_tree_vacate(condense_tree, NULL, NULL);
17700713e232SGeorge Wilson 	range_tree_destroy(condense_tree);
177116a4a807SGeorge Wilson 
17720713e232SGeorge Wilson 	space_map_write(sm, msp->ms_tree, SM_FREE, tx);
17730713e232SGeorge Wilson 	msp->ms_condensing = B_FALSE;
177416a4a807SGeorge Wilson }
177516a4a807SGeorge Wilson 
177616a4a807SGeorge Wilson /*
1777ecc2d604Sbonwick  * Write a metaslab to disk in the context of the specified transaction group.
1778ecc2d604Sbonwick  */
1779ecc2d604Sbonwick void
metaslab_sync(metaslab_t * msp,uint64_t txg)1780ecc2d604Sbonwick metaslab_sync(metaslab_t *msp, uint64_t txg)
1781ecc2d604Sbonwick {
17820713e232SGeorge Wilson 	metaslab_group_t *mg = msp->ms_group;
17830713e232SGeorge Wilson 	vdev_t *vd = mg->mg_vd;
1784ecc2d604Sbonwick 	spa_t *spa = vd->vdev_spa;
1785b24ab676SJeff Bonwick 	objset_t *mos = spa_meta_objset(spa);
17860713e232SGeorge Wilson 	range_tree_t *alloctree = msp->ms_alloctree[txg & TXG_MASK];
17870713e232SGeorge Wilson 	range_tree_t **freetree = &msp->ms_freetree[txg & TXG_MASK];
17880713e232SGeorge Wilson 	range_tree_t **freed_tree =
17890713e232SGeorge Wilson 	    &msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK];
1790ecc2d604Sbonwick 	dmu_tx_t *tx;
17910713e232SGeorge Wilson 	uint64_t object = space_map_object(msp->ms_sm);
1792ecc2d604Sbonwick 
179388ecc943SGeorge Wilson 	ASSERT(!vd->vdev_ishole);
179488ecc943SGeorge Wilson 
179516a4a807SGeorge Wilson 	/*
179616a4a807SGeorge Wilson 	 * This metaslab has just been added so there's no work to do now.
179716a4a807SGeorge Wilson 	 */
17980713e232SGeorge Wilson 	if (*freetree == NULL) {
17990713e232SGeorge Wilson 		ASSERT3P(alloctree, ==, NULL);
180016a4a807SGeorge Wilson 		return;
180116a4a807SGeorge Wilson 	}
180216a4a807SGeorge Wilson 
18030713e232SGeorge Wilson 	ASSERT3P(alloctree, !=, NULL);
18040713e232SGeorge Wilson 	ASSERT3P(*freetree, !=, NULL);
18050713e232SGeorge Wilson 	ASSERT3P(*freed_tree, !=, NULL);
180616a4a807SGeorge Wilson 
18072e4c9986SGeorge Wilson 	/*
18082e4c9986SGeorge Wilson 	 * Normally, we don't want to process a metaslab if there
18092e4c9986SGeorge Wilson 	 * are no allocations or frees to perform. However, if the metaslab
18102e4c9986SGeorge Wilson 	 * is being forced to condense we need to let it through.
18112e4c9986SGeorge Wilson 	 */
18120713e232SGeorge Wilson 	if (range_tree_space(alloctree) == 0 &&
18132e4c9986SGeorge Wilson 	    range_tree_space(*freetree) == 0 &&
18142e4c9986SGeorge Wilson 	    !msp->ms_condense_wanted)
1815468c413aSTim Haley 		return;
1816ecc2d604Sbonwick 
1817ecc2d604Sbonwick 	/*
1818ecc2d604Sbonwick 	 * The only state that can actually be changing concurrently with
18190713e232SGeorge Wilson 	 * metaslab_sync() is the metaslab's ms_tree.  No other thread can
18200713e232SGeorge Wilson 	 * be modifying this txg's alloctree, freetree, freed_tree, or
18210713e232SGeorge Wilson 	 * space_map_phys_t. Therefore, we only hold ms_lock to satify
18220713e232SGeorge Wilson 	 * space_map ASSERTs. We drop it whenever we call into the DMU,
18230713e232SGeorge Wilson 	 * because the DMU can call down to us (e.g. via zio_free()) at
18240713e232SGeorge Wilson 	 * any time.
1825ecc2d604Sbonwick 	 */
1826468c413aSTim Haley 
1827468c413aSTim Haley 	tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
1828ecc2d604Sbonwick 
18290713e232SGeorge Wilson 	if (msp->ms_sm == NULL) {
18300713e232SGeorge Wilson 		uint64_t new_object;
18310713e232SGeorge Wilson 
18320713e232SGeorge Wilson 		new_object = space_map_alloc(mos, tx);
18330713e232SGeorge Wilson 		VERIFY3U(new_object, !=, 0);
18340713e232SGeorge Wilson 
18350713e232SGeorge Wilson 		VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
18360713e232SGeorge Wilson 		    msp->ms_start, msp->ms_size, vd->vdev_ashift,
18370713e232SGeorge Wilson 		    &msp->ms_lock));
18380713e232SGeorge Wilson 		ASSERT(msp->ms_sm != NULL);
1839ecc2d604Sbonwick 	}
1840ecc2d604Sbonwick 
1841468c413aSTim Haley 	mutex_enter(&msp->ms_lock);
1842468c413aSTim Haley 
1843b1be2892SMatthew Ahrens 	/*
1844b1be2892SMatthew Ahrens 	 * Note: metaslab_condense() clears the space_map's histogram.
1845b1be2892SMatthew Ahrens 	 * Therefore we must verify and remove this histogram before
1846b1be2892SMatthew Ahrens 	 * condensing.
1847b1be2892SMatthew Ahrens 	 */
1848b1be2892SMatthew Ahrens 	metaslab_group_histogram_verify(mg);
1849b1be2892SMatthew Ahrens 	metaslab_class_histogram_verify(mg->mg_class);
1850b1be2892SMatthew Ahrens 	metaslab_group_histogram_remove(mg, msp);
1851b1be2892SMatthew Ahrens 
18520713e232SGeorge Wilson 	if (msp->ms_loaded && spa_sync_pass(spa) == 1 &&
185316a4a807SGeorge Wilson 	    metaslab_should_condense(msp)) {
185416a4a807SGeorge Wilson 		metaslab_condense(msp, txg, tx);
185516a4a807SGeorge Wilson 	} else {
18560713e232SGeorge Wilson 		space_map_write(msp->ms_sm, alloctree, SM_ALLOC, tx);
18570713e232SGeorge Wilson 		space_map_write(msp->ms_sm, *freetree, SM_FREE, tx);
1858ecc2d604Sbonwick 	}
1859ecc2d604Sbonwick 
18600713e232SGeorge Wilson 	if (msp->ms_loaded) {
18610713e232SGeorge Wilson 		/*
18620713e232SGeorge Wilson 		 * When the space map is loaded, we have an accruate
18630713e232SGeorge Wilson 		 * histogram in the range tree. This gives us an opportunity
18640713e232SGeorge Wilson 		 * to bring the space map's histogram up-to-date so we clear
18650713e232SGeorge Wilson 		 * it first before updating it.
18660713e232SGeorge Wilson 		 */
18670713e232SGeorge Wilson 		space_map_histogram_clear(msp->ms_sm);
18680713e232SGeorge Wilson 		space_map_histogram_add(msp->ms_sm, msp->ms_tree, tx);
18690713e232SGeorge Wilson 	} else {
18700713e232SGeorge Wilson 		/*
18710713e232SGeorge Wilson 		 * Since the space map is not loaded we simply update the
18720713e232SGeorge Wilson 		 * exisiting histogram with what was freed in this txg. This
18730713e232SGeorge Wilson 		 * means that the on-disk histogram may not have an accurate
18740713e232SGeorge Wilson 		 * view of the free space but it's close enough to allow
18750713e232SGeorge Wilson 		 * us to make allocation decisions.
18760713e232SGeorge Wilson 		 */
18770713e232SGeorge Wilson 		space_map_histogram_add(msp->ms_sm, *freetree, tx);
18780713e232SGeorge Wilson 	}
18792e4c9986SGeorge Wilson 	metaslab_group_histogram_add(mg, msp);
18802e4c9986SGeorge Wilson 	metaslab_group_histogram_verify(mg);
18812e4c9986SGeorge Wilson 	metaslab_class_histogram_verify(mg->mg_class);
188216a4a807SGeorge Wilson 
188316a4a807SGeorge Wilson 	/*
18840713e232SGeorge Wilson 	 * For sync pass 1, we avoid traversing this txg's free range tree
18850713e232SGeorge Wilson 	 * and instead will just swap the pointers for freetree and
18860713e232SGeorge Wilson 	 * freed_tree. We can safely do this since the freed_tree is
188716a4a807SGeorge Wilson 	 * guaranteed to be empty on the initial pass.
188816a4a807SGeorge Wilson 	 */
188916a4a807SGeorge Wilson 	if (spa_sync_pass(spa) == 1) {
18900713e232SGeorge Wilson 		range_tree_swap(freetree, freed_tree);
189116a4a807SGeorge Wilson 	} else {
18920713e232SGeorge Wilson 		range_tree_vacate(*freetree, range_tree_add, *freed_tree);
189316a4a807SGeorge Wilson 	}
18942e4c9986SGeorge Wilson 	range_tree_vacate(alloctree, NULL, NULL);
189516a4a807SGeorge Wilson 
18960713e232SGeorge Wilson 	ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
18970713e232SGeorge Wilson 	ASSERT0(range_tree_space(msp->ms_freetree[txg & TXG_MASK]));
1898ecc2d604Sbonwick 
1899ecc2d604Sbonwick 	mutex_exit(&msp->ms_lock);
1900ecc2d604Sbonwick 
19010713e232SGeorge Wilson 	if (object != space_map_object(msp->ms_sm)) {
19020713e232SGeorge Wilson 		object = space_map_object(msp->ms_sm);
19030713e232SGeorge Wilson 		dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
19040713e232SGeorge Wilson 		    msp->ms_id, sizeof (uint64_t), &object, tx);
19050713e232SGeorge Wilson 	}
1906ecc2d604Sbonwick 	dmu_tx_commit(tx);
1907ecc2d604Sbonwick }
1908ecc2d604Sbonwick 
1909ecc2d604Sbonwick /*
1910ecc2d604Sbonwick  * Called after a transaction group has completely synced to mark
1911ecc2d604Sbonwick  * all of the metaslab's free space as usable.
1912ecc2d604Sbonwick  */
1913ecc2d604Sbonwick void
metaslab_sync_done(metaslab_t * msp,uint64_t txg)1914ecc2d604Sbonwick metaslab_sync_done(metaslab_t *msp, uint64_t txg)
1915ecc2d604Sbonwick {
1916ecc2d604Sbonwick 	metaslab_group_t *mg = msp->ms_group;
1917ecc2d604Sbonwick 	vdev_t *vd = mg->mg_vd;
19180713e232SGeorge Wilson 	range_tree_t **freed_tree;
19190713e232SGeorge Wilson 	range_tree_t **defer_tree;
1920468c413aSTim Haley 	int64_t alloc_delta, defer_delta;
1921ecc2d604Sbonwick 
192288ecc943SGeorge Wilson 	ASSERT(!vd->vdev_ishole);
192388ecc943SGeorge Wilson 
1924ecc2d604Sbonwick 	mutex_enter(&msp->ms_lock);
1925ecc2d604Sbonwick 
1926ecc2d604Sbonwick 	/*
1927ecc2d604Sbonwick 	 * If this metaslab is just becoming available, initialize its
19280713e232SGeorge Wilson 	 * alloctrees, freetrees, and defertree and add its capacity to
19290713e232SGeorge Wilson 	 * the vdev.
1930ecc2d604Sbonwick 	 */
19310713e232SGeorge Wilson 	if (msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK] == NULL) {
1932468c413aSTim Haley 		for (int t = 0; t < TXG_SIZE; t++) {
19330713e232SGeorge Wilson 			ASSERT(msp->ms_alloctree[t] == NULL);
19340713e232SGeorge Wilson 			ASSERT(msp->ms_freetree[t] == NULL);
19350713e232SGeorge Wilson 
19360713e232SGeorge Wilson 			msp->ms_alloctree[t] = range_tree_create(NULL, msp,
19370713e232SGeorge Wilson 			    &msp->ms_lock);
19380713e232SGeorge Wilson 			msp->ms_freetree[t] = range_tree_create(NULL, msp,
19390713e232SGeorge Wilson 			    &msp->ms_lock);
1940ecc2d604Sbonwick 		}
1941468c413aSTim Haley 
194216a4a807SGeorge Wilson 		for (int t = 0; t < TXG_DEFER_SIZE; t++) {
19430713e232SGeorge Wilson 			ASSERT(msp->ms_defertree[t] == NULL);
19440713e232SGeorge Wilson 
19450713e232SGeorge Wilson 			msp->ms_defertree[t] = range_tree_create(NULL, msp,
19460713e232SGeorge Wilson 			    &msp->ms_lock);
194716a4a807SGeorge Wilson 		}
194816a4a807SGeorge Wilson 
19490713e232SGeorge Wilson 		vdev_space_update(vd, 0, 0, msp->ms_size);
1950ecc2d604Sbonwick 	}
1951ecc2d604Sbonwick 
19520713e232SGeorge Wilson 	freed_tree = &msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK];
19530713e232SGeorge Wilson 	defer_tree = &msp->ms_defertree[txg % TXG_DEFER_SIZE];
19540713e232SGeorge Wilson 
19550713e232SGeorge Wilson 	alloc_delta = space_map_alloc_delta(msp->ms_sm);
19560713e232SGeorge Wilson 	defer_delta = range_tree_space(*freed_tree) -
19570713e232SGeorge Wilson 	    range_tree_space(*defer_tree);
1958468c413aSTim Haley 
1959b24ab676SJeff Bonwick 	vdev_space_update(vd, alloc_delta + defer_delta, defer_delta, 0);
1960ecc2d604Sbonwick 
19610713e232SGeorge Wilson 	ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
19620713e232SGeorge Wilson 	ASSERT0(range_tree_space(msp->ms_freetree[txg & TXG_MASK]));
1963ecc2d604Sbonwick 
1964ecc2d604Sbonwick 	/*
19650713e232SGeorge Wilson 	 * If there's a metaslab_load() in progress, wait for it to complete
1966ecc2d604Sbonwick 	 * so that we have a consistent view of the in-core space map.
1967ecc2d604Sbonwick 	 */
19680713e232SGeorge Wilson 	metaslab_load_wait(msp);
19699eb57f7fSGeorge Wilson 
19709eb57f7fSGeorge Wilson 	/*
19710713e232SGeorge Wilson 	 * Move the frees from the defer_tree back to the free
19720713e232SGeorge Wilson 	 * range tree (if it's loaded). Swap the freed_tree and the
19730713e232SGeorge Wilson 	 * defer_tree -- this is safe to do because we've just emptied out
19740713e232SGeorge Wilson 	 * the defer_tree.
19759eb57f7fSGeorge Wilson 	 */
19760713e232SGeorge Wilson 	range_tree_vacate(*defer_tree,
19770713e232SGeorge Wilson 	    msp->ms_loaded ? range_tree_add : NULL, msp->ms_tree);
19780713e232SGeorge Wilson 	range_tree_swap(freed_tree, defer_tree);
1979ecc2d604Sbonwick 
19800713e232SGeorge Wilson 	space_map_update(msp->ms_sm);
1981ecc2d604Sbonwick 
1982468c413aSTim Haley 	msp->ms_deferspace += defer_delta;
1983468c413aSTim Haley 	ASSERT3S(msp->ms_deferspace, >=, 0);
19840713e232SGeorge Wilson 	ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
1985468c413aSTim Haley 	if (msp->ms_deferspace != 0) {
1986468c413aSTim Haley 		/*
1987468c413aSTim Haley 		 * Keep syncing this metaslab until all deferred frees
1988468c413aSTim Haley 		 * are back in circulation.
1989468c413aSTim Haley 		 */
1990468c413aSTim Haley 		vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
1991468c413aSTim Haley 	}
1992468c413aSTim Haley 
19930713e232SGeorge Wilson 	if (msp->ms_loaded && msp->ms_access_txg < txg) {
19940713e232SGeorge Wilson 		for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
19950713e232SGeorge Wilson 			VERIFY0(range_tree_space(
19960713e232SGeorge Wilson 			    msp->ms_alloctree[(txg + t) & TXG_MASK]));
19970713e232SGeorge Wilson 		}
1998ecc2d604Sbonwick 
19990713e232SGeorge Wilson 		if (!metaslab_debug_unload)
20000713e232SGeorge Wilson 			metaslab_unload(msp);
2001ecc2d604Sbonwick 	}
2002ecc2d604Sbonwick 
2003ecc2d604Sbonwick 	metaslab_group_sort(mg, msp, metaslab_weight(msp));
2004ecc2d604Sbonwick 	mutex_exit(&msp->ms_lock);
2005fa9e4066Sahrens }
2006fa9e4066Sahrens 
200780eb36f2SGeorge Wilson void
metaslab_sync_reassess(metaslab_group_t * mg)200880eb36f2SGeorge Wilson metaslab_sync_reassess(metaslab_group_t *mg)
200980eb36f2SGeorge Wilson {
201022e30981SGeorge Wilson 	metaslab_group_alloc_update(mg);
20112e4c9986SGeorge Wilson 	mg->mg_fragmentation = metaslab_group_fragmentation(mg);
201209c9d376SGeorge Wilson 
201380eb36f2SGeorge Wilson 	/*
20140713e232SGeorge Wilson 	 * Preload the next potential metaslabs
201580eb36f2SGeorge Wilson 	 */
20160713e232SGeorge Wilson 	metaslab_group_preload(mg);
201780eb36f2SGeorge Wilson }
201880eb36f2SGeorge Wilson 
201944cd46caSbillm static uint64_t
metaslab_distance(metaslab_t * msp,dva_t * dva)202044cd46caSbillm metaslab_distance(metaslab_t *msp, dva_t *dva)
202144cd46caSbillm {
202244cd46caSbillm 	uint64_t ms_shift = msp->ms_group->mg_vd->vdev_ms_shift;
202344cd46caSbillm 	uint64_t offset = DVA_GET_OFFSET(dva) >> ms_shift;
20240713e232SGeorge Wilson 	uint64_t start = msp->ms_id;
202544cd46caSbillm 
202644cd46caSbillm 	if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
202744cd46caSbillm 		return (1ULL << 63);
202844cd46caSbillm 
202944cd46caSbillm 	if (offset < start)
203044cd46caSbillm 		return ((start - offset) << ms_shift);
203144cd46caSbillm 	if (offset > start)
203244cd46caSbillm 		return ((offset - start) << ms_shift);
203344cd46caSbillm 	return (0);
203444cd46caSbillm }
203544cd46caSbillm 
203644cd46caSbillm 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)203709c9d376SGeorge Wilson metaslab_group_alloc(metaslab_group_t *mg, uint64_t psize, uint64_t asize,
2038b6240e83SGeorge Wilson     uint64_t txg, uint64_t min_distance, dva_t *dva, int d)
2039fa9e4066Sahrens {
204009c9d376SGeorge Wilson 	spa_t *spa = mg->mg_vd->vdev_spa;
2041ecc2d604Sbonwick 	metaslab_t *msp = NULL;
2042ecc2d604Sbonwick 	uint64_t offset = -1ULL;
204344cd46caSbillm 	avl_tree_t *t = &mg->mg_metaslab_tree;
204444cd46caSbillm 	uint64_t activation_weight;
204544cd46caSbillm 	uint64_t target_distance;
204644cd46caSbillm 	int i;
204744cd46caSbillm 
204844cd46caSbillm 	activation_weight = METASLAB_WEIGHT_PRIMARY;
2049d6e555bdSGeorge Wilson 	for (i = 0; i < d; i++) {
2050d6e555bdSGeorge Wilson 		if (DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
205144cd46caSbillm 			activation_weight = METASLAB_WEIGHT_SECONDARY;
2052d6e555bdSGeorge Wilson 			break;
2053d6e555bdSGeorge Wilson 		}
2054d6e555bdSGeorge Wilson 	}
2055fa9e4066Sahrens 
2056ecc2d604Sbonwick 	for (;;) {
2057d6e555bdSGeorge Wilson 		boolean_t was_active;
2058d6e555bdSGeorge Wilson 
2059fa9e4066Sahrens 		mutex_enter(&mg->mg_lock);
206044cd46caSbillm 		for (msp = avl_first(t); msp; msp = AVL_NEXT(t, msp)) {
206109c9d376SGeorge Wilson 			if (msp->ms_weight < asize) {
206209c9d376SGeorge Wilson 				spa_dbgmsg(spa, "%s: failed to meet weight "
206309c9d376SGeorge Wilson 				    "requirement: vdev %llu, txg %llu, mg %p, "
206409c9d376SGeorge Wilson 				    "msp %p, psize %llu, asize %llu, "
2065b6240e83SGeorge Wilson 				    "weight %llu", spa_name(spa),
2066b6240e83SGeorge Wilson 				    mg->mg_vd->vdev_id, txg,
2067b6240e83SGeorge Wilson 				    mg, msp, psize, asize, msp->ms_weight);
2068ecc2d604Sbonwick 				mutex_exit(&mg->mg_lock);
206944cd46caSbillm 				return (-1ULL);
207044cd46caSbillm 			}
207103f8c366SGeorge Wilson 
207203f8c366SGeorge Wilson 			/*
207303f8c366SGeorge Wilson 			 * If the selected metaslab is condensing, skip it.
207403f8c366SGeorge Wilson 			 */
20750713e232SGeorge Wilson 			if (msp->ms_condensing)
207603f8c366SGeorge Wilson 				continue;
207703f8c366SGeorge Wilson 
2078d6e555bdSGeorge Wilson 			was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
207944cd46caSbillm 			if (activation_weight == METASLAB_WEIGHT_PRIMARY)
208044cd46caSbillm 				break;
208144cd46caSbillm 
208244cd46caSbillm 			target_distance = min_distance +
20830713e232SGeorge Wilson 			    (space_map_allocated(msp->ms_sm) != 0 ? 0 :
20840713e232SGeorge Wilson 			    min_distance >> 1);
208544cd46caSbillm 
208644cd46caSbillm 			for (i = 0; i < d; i++)
208744cd46caSbillm 				if (metaslab_distance(msp, &dva[i]) <
208844cd46caSbillm 				    target_distance)
208944cd46caSbillm 					break;
209044cd46caSbillm 			if (i == d)
209144cd46caSbillm 				break;
2092ecc2d604Sbonwick 		}
2093fa9e4066Sahrens 		mutex_exit(&mg->mg_lock);
209444cd46caSbillm 		if (msp == NULL)
209544cd46caSbillm 			return (-1ULL);
2096fa9e4066Sahrens 
209722e30981SGeorge Wilson 		mutex_enter(&msp->ms_lock);
209822e30981SGeorge Wilson 
209909c9d376SGeorge Wilson 		/*
2100aeb1c1b6Sgw25295 		 * Ensure that the metaslab we have selected is still
2101aeb1c1b6Sgw25295 		 * capable of handling our request. It's possible that
2102aeb1c1b6Sgw25295 		 * another thread may have changed the weight while we
2103aeb1c1b6Sgw25295 		 * were blocked on the metaslab lock.
2104aeb1c1b6Sgw25295 		 */
210509c9d376SGeorge Wilson 		if (msp->ms_weight < asize || (was_active &&
2106d6e555bdSGeorge Wilson 		    !(msp->ms_weight & METASLAB_ACTIVE_MASK) &&
2107d6e555bdSGeorge Wilson 		    activation_weight == METASLAB_WEIGHT_PRIMARY)) {
2108aeb1c1b6Sgw25295 			mutex_exit(&msp->ms_lock);
2109aeb1c1b6Sgw25295 			continue;
2110aeb1c1b6Sgw25295 		}
2111aeb1c1b6Sgw25295 
211244cd46caSbillm 		if ((msp->ms_weight & METASLAB_WEIGHT_SECONDARY) &&
211344cd46caSbillm 		    activation_weight == METASLAB_WEIGHT_PRIMARY) {
211444cd46caSbillm 			metaslab_passivate(msp,
21155f5f7a6fSahrens 			    msp->ms_weight & ~METASLAB_ACTIVE_MASK);
211644cd46caSbillm 			mutex_exit(&msp->ms_lock);
211744cd46caSbillm 			continue;
211844cd46caSbillm 		}
211944cd46caSbillm 
212009c9d376SGeorge Wilson 		if (metaslab_activate(msp, activation_weight) != 0) {
2121fa9e4066Sahrens 			mutex_exit(&msp->ms_lock);
2122fa9e4066Sahrens 			continue;
2123fa9e4066Sahrens 		}
2124fa9e4066Sahrens 
212503f8c366SGeorge Wilson 		/*
212603f8c366SGeorge Wilson 		 * If this metaslab is currently condensing then pick again as
212703f8c366SGeorge Wilson 		 * we can't manipulate this metaslab until it's committed
212803f8c366SGeorge Wilson 		 * to disk.
212903f8c366SGeorge Wilson 		 */
21300713e232SGeorge Wilson 		if (msp->ms_condensing) {
213103f8c366SGeorge Wilson 			mutex_exit(&msp->ms_lock);
213203f8c366SGeorge Wilson 			continue;
213303f8c366SGeorge Wilson 		}
213403f8c366SGeorge Wilson 
21350713e232SGeorge Wilson 		if ((offset = metaslab_block_alloc(msp, asize)) != -1ULL)
2136ecc2d604Sbonwick 			break;
2137ecc2d604Sbonwick 
21380713e232SGeorge Wilson 		metaslab_passivate(msp, metaslab_block_maxsize(msp));
2139ecc2d604Sbonwick 		mutex_exit(&msp->ms_lock);
2140ecc2d604Sbonwick 	}
2141ecc2d604Sbonwick 
21420713e232SGeorge Wilson 	if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
2143ecc2d604Sbonwick 		vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
2144ecc2d604Sbonwick 
21450713e232SGeorge Wilson 	range_tree_add(msp->ms_alloctree[txg & TXG_MASK], offset, asize);
21460713e232SGeorge Wilson 	msp->ms_access_txg = txg + metaslab_unload_delay;
2147ecc2d604Sbonwick 
2148ecc2d604Sbonwick 	mutex_exit(&msp->ms_lock);
2149ecc2d604Sbonwick 
215044cd46caSbillm 	return (offset);
2151fa9e4066Sahrens }
2152fa9e4066Sahrens 
2153fa9e4066Sahrens /*
2154fa9e4066Sahrens  * Allocate a block for the specified i/o.
2155fa9e4066Sahrens  */
215644cd46caSbillm 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)21578654d025Sperrin metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
2158e14bb325SJeff Bonwick     dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags)
2159fa9e4066Sahrens {
2160fa9e4066Sahrens 	metaslab_group_t *mg, *rotor;
2161fa9e4066Sahrens 	vdev_t *vd;
216244cd46caSbillm 	int dshift = 3;
216344cd46caSbillm 	int all_zero;
21648ad4d6ddSJeff Bonwick 	int zio_lock = B_FALSE;
21658ad4d6ddSJeff Bonwick 	boolean_t allocatable;
2166fa9e4066Sahrens 	uint64_t offset = -1ULL;
2167fa9e4066Sahrens 	uint64_t asize;
216844cd46caSbillm 	uint64_t distance;
2169fa9e4066Sahrens 
2170d80c45e0Sbonwick 	ASSERT(!DVA_IS_VALID(&dva[d]));
2171d80c45e0Sbonwick 
2172fa9e4066Sahrens 	/*
2173e05725b1Sbonwick 	 * For testing, make some blocks above a certain size be gang blocks.
2174e05725b1Sbonwick 	 */
2175d3d50737SRafael Vanoni 	if (psize >= metaslab_gang_bang && (ddi_get_lbolt() & 3) == 0)
2176be6fd75aSMatthew Ahrens 		return (SET_ERROR(ENOSPC));
2177e05725b1Sbonwick 
2178e05725b1Sbonwick 	/*
2179fa9e4066Sahrens 	 * Start at the rotor and loop through all mgs until we find something.
2180b24ab676SJeff Bonwick 	 * Note that there's no locking on mc_rotor or mc_aliquot because
2181fa9e4066Sahrens 	 * nothing actually breaks if we miss a few updates -- we just won't
2182fa9e4066Sahrens 	 * allocate quite as evenly.  It all balances out over time.
218344cd46caSbillm 	 *
218467bd71c6Sperrin 	 * If we are doing ditto or log blocks, try to spread them across
218567bd71c6Sperrin 	 * consecutive vdevs.  If we're forced to reuse a vdev before we've
218667bd71c6Sperrin 	 * allocated all of our ditto blocks, then try and spread them out on
218767bd71c6Sperrin 	 * that vdev as much as possible.  If it turns out to not be possible,
218844cd46caSbillm 	 * gradually lower our standards until anything becomes acceptable.
218944cd46caSbillm 	 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
219044cd46caSbillm 	 * gives us hope of containing our fault domains to something we're
219144cd46caSbillm 	 * able to reason about.  Otherwise, any two top-level vdev failures
219244cd46caSbillm 	 * will guarantee the loss of data.  With consecutive allocation,
219344cd46caSbillm 	 * only two adjacent top-level vdev failures will result in data loss.
219444cd46caSbillm 	 *
219544cd46caSbillm 	 * If we are doing gang blocks (hintdva is non-NULL), try to keep
219644cd46caSbillm 	 * ourselves on the same vdev as our gang block header.  That
219744cd46caSbillm 	 * way, we can hope for locality in vdev_cache, plus it makes our
219844cd46caSbillm 	 * fault domains something tractable.
2199fa9e4066Sahrens 	 */
220044cd46caSbillm 	if (hintdva) {
220144cd46caSbillm 		vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
220288ecc943SGeorge Wilson 
220388ecc943SGeorge Wilson 		/*
220488ecc943SGeorge Wilson 		 * It's possible the vdev we're using as the hint no
220588ecc943SGeorge Wilson 		 * longer exists (i.e. removed). Consult the rotor when
220688ecc943SGeorge Wilson 		 * all else fails.
220788ecc943SGeorge Wilson 		 */
2208a1521560SJeff Bonwick 		if (vd != NULL) {
220944cd46caSbillm 			mg = vd->vdev_mg;
221088ecc943SGeorge Wilson 
221188ecc943SGeorge Wilson 			if (flags & METASLAB_HINTBP_AVOID &&
221288ecc943SGeorge Wilson 			    mg->mg_next != NULL)
221388ecc943SGeorge Wilson 				mg = mg->mg_next;
221488ecc943SGeorge Wilson 		} else {
221588ecc943SGeorge Wilson 			mg = mc->mc_rotor;
221688ecc943SGeorge Wilson 		}
221744cd46caSbillm 	} else if (d != 0) {
221844cd46caSbillm 		vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
221944cd46caSbillm 		mg = vd->vdev_mg->mg_next;
222044cd46caSbillm 	} else {
222144cd46caSbillm 		mg = mc->mc_rotor;
222244cd46caSbillm 	}
222344cd46caSbillm 
22248654d025Sperrin 	/*
2225a1521560SJeff Bonwick 	 * If the hint put us into the wrong metaslab class, or into a
2226a1521560SJeff Bonwick 	 * metaslab group that has been passivated, just follow the rotor.
22278654d025Sperrin 	 */
2228a1521560SJeff Bonwick 	if (mg->mg_class != mc || mg->mg_activation_count <= 0)
22298654d025Sperrin 		mg = mc->mc_rotor;
22308654d025Sperrin 
22318654d025Sperrin 	rotor = mg;
223244cd46caSbillm top:
223344cd46caSbillm 	all_zero = B_TRUE;
2234fa9e4066Sahrens 	do {
2235a1521560SJeff Bonwick 		ASSERT(mg->mg_activation_count == 1);
2236a1521560SJeff Bonwick 
2237fa9e4066Sahrens 		vd = mg->mg_vd;
22388ad4d6ddSJeff Bonwick 
22390a4e9518Sgw25295 		/*
2240e14bb325SJeff Bonwick 		 * Don't allocate from faulted devices.
22410a4e9518Sgw25295 		 */
22428ad4d6ddSJeff Bonwick 		if (zio_lock) {
22438ad4d6ddSJeff Bonwick 			spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
22448ad4d6ddSJeff Bonwick 			allocatable = vdev_allocatable(vd);
22458ad4d6ddSJeff Bonwick 			spa_config_exit(spa, SCL_ZIO, FTAG);
22468ad4d6ddSJeff Bonwick 		} else {
22478ad4d6ddSJeff Bonwick 			allocatable = vdev_allocatable(vd);
22488ad4d6ddSJeff Bonwick 		}
224922e30981SGeorge Wilson 
225022e30981SGeorge Wilson 		/*
225122e30981SGeorge Wilson 		 * Determine if the selected metaslab group is eligible
225222e30981SGeorge Wilson 		 * for allocations. If we're ganging or have requested
225322e30981SGeorge Wilson 		 * an allocation for the smallest gang block size
225422e30981SGeorge Wilson 		 * then we don't want to avoid allocating to the this
225522e30981SGeorge Wilson 		 * metaslab group. If we're in this condition we should
225622e30981SGeorge Wilson 		 * try to allocate from any device possible so that we
225722e30981SGeorge Wilson 		 * don't inadvertently return ENOSPC and suspend the pool
225822e30981SGeorge Wilson 		 * even though space is still available.
225922e30981SGeorge Wilson 		 */
226022e30981SGeorge Wilson 		if (allocatable && CAN_FASTGANG(flags) &&
226122e30981SGeorge Wilson 		    psize > SPA_GANGBLOCKSIZE)
226222e30981SGeorge Wilson 			allocatable = metaslab_group_allocatable(mg);
226322e30981SGeorge Wilson 
22648ad4d6ddSJeff Bonwick 		if (!allocatable)
22650a4e9518Sgw25295 			goto next;
22668ad4d6ddSJeff Bonwick 
22670a4e9518Sgw25295 		/*
22680a4e9518Sgw25295 		 * Avoid writing single-copy data to a failing vdev
22699dc3941cSSašo Kiselkov 		 * unless the user instructs us that it is okay.
22700a4e9518Sgw25295 		 */
22710a4e9518Sgw25295 		if ((vd->vdev_stat.vs_write_errors > 0 ||
22720a4e9518Sgw25295 		    vd->vdev_state < VDEV_STATE_HEALTHY) &&
22732e4c9986SGeorge Wilson 		    d == 0 && dshift == 3 && vd->vdev_children == 0) {
22740a4e9518Sgw25295 			all_zero = B_FALSE;
22750a4e9518Sgw25295 			goto next;
22760a4e9518Sgw25295 		}
227744cd46caSbillm 
22788654d025Sperrin 		ASSERT(mg->mg_class == mc);
22798654d025Sperrin 
228044cd46caSbillm 		distance = vd->vdev_asize >> dshift;
228144cd46caSbillm 		if (distance <= (1ULL << vd->vdev_ms_shift))
228244cd46caSbillm 			distance = 0;
228344cd46caSbillm 		else
228444cd46caSbillm 			all_zero = B_FALSE;
228544cd46caSbillm 
2286fa9e4066Sahrens 		asize = vdev_psize_to_asize(vd, psize);
2287fa9e4066Sahrens 		ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
2288fa9e4066Sahrens 
228909c9d376SGeorge Wilson 		offset = metaslab_group_alloc(mg, psize, asize, txg, distance,
2290b6240e83SGeorge Wilson 		    dva, d);
229144cd46caSbillm 		if (offset != -1ULL) {
2292fa9e4066Sahrens 			/*
2293fa9e4066Sahrens 			 * If we've just selected this metaslab group,
2294fa9e4066Sahrens 			 * figure out whether the corresponding vdev is
2295fa9e4066Sahrens 			 * over- or under-used relative to the pool,
2296fa9e4066Sahrens 			 * and set an allocation bias to even it out.
2297fa9e4066Sahrens 			 */
22982e4c9986SGeorge Wilson 			if (mc->mc_aliquot == 0 && metaslab_bias_enabled) {
2299fa9e4066Sahrens 				vdev_stat_t *vs = &vd->vdev_stat;
2300b24ab676SJeff Bonwick 				int64_t vu, cu;
2301fa9e4066Sahrens 
230209c9d376SGeorge Wilson 				vu = (vs->vs_alloc * 100) / (vs->vs_space + 1);
230309c9d376SGeorge Wilson 				cu = (mc->mc_alloc * 100) / (mc->mc_space + 1);
2304fa9e4066Sahrens 
2305fa9e4066Sahrens 				/*
230609c9d376SGeorge Wilson 				 * Calculate how much more or less we should
230709c9d376SGeorge Wilson 				 * try to allocate from this device during
230809c9d376SGeorge Wilson 				 * this iteration around the rotor.
230909c9d376SGeorge Wilson 				 * For example, if a device is 80% full
231009c9d376SGeorge Wilson 				 * and the pool is 20% full then we should
231109c9d376SGeorge Wilson 				 * reduce allocations by 60% on this device.
231209c9d376SGeorge Wilson 				 *
231309c9d376SGeorge Wilson 				 * mg_bias = (20 - 80) * 512K / 100 = -307K
231409c9d376SGeorge Wilson 				 *
231509c9d376SGeorge Wilson 				 * This reduces allocations by 307K for this
231609c9d376SGeorge Wilson 				 * iteration.
2317fa9e4066Sahrens 				 */
2318b24ab676SJeff Bonwick 				mg->mg_bias = ((cu - vu) *
231909c9d376SGeorge Wilson 				    (int64_t)mg->mg_aliquot) / 100;
23202e4c9986SGeorge Wilson 			} else if (!metaslab_bias_enabled) {
23212e4c9986SGeorge Wilson 				mg->mg_bias = 0;
2322fa9e4066Sahrens 			}
2323fa9e4066Sahrens 
2324b24ab676SJeff Bonwick 			if (atomic_add_64_nv(&mc->mc_aliquot, asize) >=
2325fa9e4066Sahrens 			    mg->mg_aliquot + mg->mg_bias) {
2326fa9e4066Sahrens 				mc->mc_rotor = mg->mg_next;
2327b24ab676SJeff Bonwick 				mc->mc_aliquot = 0;
2328fa9e4066Sahrens 			}
2329fa9e4066Sahrens 
233044cd46caSbillm 			DVA_SET_VDEV(&dva[d], vd->vdev_id);
233144cd46caSbillm 			DVA_SET_OFFSET(&dva[d], offset);
2332e14bb325SJeff Bonwick 			DVA_SET_GANG(&dva[d], !!(flags & METASLAB_GANG_HEADER));
233344cd46caSbillm 			DVA_SET_ASIZE(&dva[d], asize);
2334fa9e4066Sahrens 
2335fa9e4066Sahrens 			return (0);
2336fa9e4066Sahrens 		}
23370a4e9518Sgw25295 next:
2338fa9e4066Sahrens 		mc->mc_rotor = mg->mg_next;
2339b24ab676SJeff Bonwick 		mc->mc_aliquot = 0;
2340fa9e4066Sahrens 	} while ((mg = mg->mg_next) != rotor);
2341fa9e4066Sahrens 
234244cd46caSbillm 	if (!all_zero) {
234344cd46caSbillm 		dshift++;
234444cd46caSbillm 		ASSERT(dshift < 64);
234544cd46caSbillm 		goto top;
234644cd46caSbillm 	}
234744cd46caSbillm 
2348d6e555bdSGeorge Wilson 	if (!allocatable && !zio_lock) {
23498ad4d6ddSJeff Bonwick 		dshift = 3;
23508ad4d6ddSJeff Bonwick 		zio_lock = B_TRUE;
23518ad4d6ddSJeff Bonwick 		goto top;
23528ad4d6ddSJeff Bonwick 	}
23538ad4d6ddSJeff Bonwick 
235444cd46caSbillm 	bzero(&dva[d], sizeof (dva_t));
2355fa9e4066Sahrens 
2356be6fd75aSMatthew Ahrens 	return (SET_ERROR(ENOSPC));
2357fa9e4066Sahrens }
2358fa9e4066Sahrens 
2359fa9e4066Sahrens /*
2360fa9e4066Sahrens  * Free the block represented by DVA in the context of the specified
2361fa9e4066Sahrens  * transaction group.
2362fa9e4066Sahrens  */
2363d80c45e0Sbonwick static void
metaslab_free_dva(spa_t * spa,const dva_t * dva,uint64_t txg,boolean_t now)2364d80c45e0Sbonwick metaslab_free_dva(spa_t *spa, const dva_t *dva, uint64_t txg, boolean_t now)
2365fa9e4066Sahrens {
2366fa9e4066Sahrens 	uint64_t vdev = DVA_GET_VDEV(dva);
2367fa9e4066Sahrens 	uint64_t offset = DVA_GET_OFFSET(dva);
2368fa9e4066Sahrens 	uint64_t size = DVA_GET_ASIZE(dva);
2369fa9e4066Sahrens 	vdev_t *vd;
2370fa9e4066Sahrens 	metaslab_t *msp;
2371fa9e4066Sahrens 
2372d80c45e0Sbonwick 	ASSERT(DVA_IS_VALID(dva));
2373d80c45e0Sbonwick 
2374fa9e4066Sahrens 	if (txg > spa_freeze_txg(spa))
2375fa9e4066Sahrens 		return;
2376fa9e4066Sahrens 
2377d80c45e0Sbonwick 	if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
2378d80c45e0Sbonwick 	    (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
2379d80c45e0Sbonwick 		cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
2380d80c45e0Sbonwick 		    (u_longlong_t)vdev, (u_longlong_t)offset);
2381fa9e4066Sahrens 		ASSERT(0);
2382fa9e4066Sahrens 		return;
2383fa9e4066Sahrens 	}
2384fa9e4066Sahrens 
2385fa9e4066Sahrens 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
2386fa9e4066Sahrens 
2387fa9e4066Sahrens 	if (DVA_GET_GANG(dva))
2388fa9e4066Sahrens 		size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
2389fa9e4066Sahrens 
2390fa9e4066Sahrens 	mutex_enter(&msp->ms_lock);
2391fa9e4066Sahrens 
2392ecc2d604Sbonwick 	if (now) {
23930713e232SGeorge Wilson 		range_tree_remove(msp->ms_alloctree[txg & TXG_MASK],
2394ecc2d604Sbonwick 		    offset, size);
23950713e232SGeorge Wilson 
23960713e232SGeorge Wilson 		VERIFY(!msp->ms_condensing);
23970713e232SGeorge Wilson 		VERIFY3U(offset, >=, msp->ms_start);
23980713e232SGeorge Wilson 		VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
23990713e232SGeorge Wilson 		VERIFY3U(range_tree_space(msp->ms_tree) + size, <=,
24000713e232SGeorge Wilson 		    msp->ms_size);
24010713e232SGeorge Wilson 		VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
24020713e232SGeorge Wilson 		VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
24030713e232SGeorge Wilson 		range_tree_add(msp->ms_tree, offset, size);
2404ecc2d604Sbonwick 	} else {
24050713e232SGeorge Wilson 		if (range_tree_space(msp->ms_freetree[txg & TXG_MASK]) == 0)
2406ecc2d604Sbonwick 			vdev_dirty(vd, VDD_METASLAB, msp, txg);
24070713e232SGeorge Wilson 		range_tree_add(msp->ms_freetree[txg & TXG_MASK],
24080713e232SGeorge Wilson 		    offset, size);
2409ecc2d604Sbonwick 	}
2410fa9e4066Sahrens 
2411fa9e4066Sahrens 	mutex_exit(&msp->ms_lock);
2412fa9e4066Sahrens }
2413d80c45e0Sbonwick 
2414d80c45e0Sbonwick /*
2415d80c45e0Sbonwick  * Intent log support: upon opening the pool after a crash, notify the SPA
2416d80c45e0Sbonwick  * of blocks that the intent log has allocated for immediate write, but
2417d80c45e0Sbonwick  * which are still considered free by the SPA because the last transaction
2418d80c45e0Sbonwick  * group didn't commit yet.
2419d80c45e0Sbonwick  */
2420d80c45e0Sbonwick static int
metaslab_claim_dva(spa_t * spa,const dva_t * dva,uint64_t txg)2421d80c45e0Sbonwick metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
2422d80c45e0Sbonwick {
2423d80c45e0Sbonwick 	uint64_t vdev = DVA_GET_VDEV(dva);
2424d80c45e0Sbonwick 	uint64_t offset = DVA_GET_OFFSET(dva);
2425d80c45e0Sbonwick 	uint64_t size = DVA_GET_ASIZE(dva);
2426d80c45e0Sbonwick 	vdev_t *vd;
2427d80c45e0Sbonwick 	metaslab_t *msp;
2428b24ab676SJeff Bonwick 	int error = 0;
2429d80c45e0Sbonwick 
2430d80c45e0Sbonwick 	ASSERT(DVA_IS_VALID(dva));
2431d80c45e0Sbonwick 
2432d80c45e0Sbonwick 	if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
2433d80c45e0Sbonwick 	    (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
2434be6fd75aSMatthew Ahrens 		return (SET_ERROR(ENXIO));
2435d80c45e0Sbonwick 
2436d80c45e0Sbonwick 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
2437d80c45e0Sbonwick 
2438d80c45e0Sbonwick 	if (DVA_GET_GANG(dva))
2439d80c45e0Sbonwick 		size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
2440d80c45e0Sbonwick 
2441d80c45e0Sbonwick 	mutex_enter(&msp->ms_lock);
2442d80c45e0Sbonwick 
24430713e232SGeorge Wilson 	if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded)
244409c9d376SGeorge Wilson 		error = metaslab_activate(msp, METASLAB_WEIGHT_SECONDARY);
2445b24ab676SJeff Bonwick 
24460713e232SGeorge Wilson 	if (error == 0 && !range_tree_contains(msp->ms_tree, offset, size))
2447be6fd75aSMatthew Ahrens 		error = SET_ERROR(ENOENT);
2448b24ab676SJeff Bonwick 
2449e14bb325SJeff Bonwick 	if (error || txg == 0) {	/* txg == 0 indicates dry run */
2450d80c45e0Sbonwick 		mutex_exit(&msp->ms_lock);
2451d80c45e0Sbonwick 		return (error);
2452d80c45e0Sbonwick 	}
2453d80c45e0Sbonwick 
24540713e232SGeorge Wilson 	VERIFY(!msp->ms_condensing);
24550713e232SGeorge Wilson 	VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
24560713e232SGeorge Wilson 	VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
24570713e232SGeorge Wilson 	VERIFY3U(range_tree_space(msp->ms_tree) - size, <=, msp->ms_size);
24580713e232SGeorge Wilson 	range_tree_remove(msp->ms_tree, offset, size);
2459e14bb325SJeff Bonwick 
24608ad4d6ddSJeff Bonwick 	if (spa_writeable(spa)) {	/* don't dirty if we're zdb(1M) */
24610713e232SGeorge Wilson 		if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
2462d80c45e0Sbonwick 			vdev_dirty(vd, VDD_METASLAB, msp, txg);
24630713e232SGeorge Wilson 		range_tree_add(msp->ms_alloctree[txg & TXG_MASK], offset, size);
2464e14bb325SJeff Bonwick 	}
2465d80c45e0Sbonwick 
2466d80c45e0Sbonwick 	mutex_exit(&msp->ms_lock);
2467d80c45e0Sbonwick 
2468d80c45e0Sbonwick 	return (0);
2469d80c45e0Sbonwick }
2470d80c45e0Sbonwick 
2471d80c45e0Sbonwick 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)24728654d025Sperrin metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
2473e14bb325SJeff Bonwick     int ndvas, uint64_t txg, blkptr_t *hintbp, int flags)
2474d80c45e0Sbonwick {
2475d80c45e0Sbonwick 	dva_t *dva = bp->blk_dva;
2476d80c45e0Sbonwick 	dva_t *hintdva = hintbp->blk_dva;
2477d80c45e0Sbonwick 	int error = 0;
2478d80c45e0Sbonwick 
2479e14bb325SJeff Bonwick 	ASSERT(bp->blk_birth == 0);
2480b24ab676SJeff Bonwick 	ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
2481e14bb325SJeff Bonwick 
2482e14bb325SJeff Bonwick 	spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
2483e14bb325SJeff Bonwick 
2484e14bb325SJeff Bonwick 	if (mc->mc_rotor == NULL) {	/* no vdevs in this class */
2485e14bb325SJeff Bonwick 		spa_config_exit(spa, SCL_ALLOC, FTAG);
2486be6fd75aSMatthew Ahrens 		return (SET_ERROR(ENOSPC));
2487e14bb325SJeff Bonwick 	}
24888654d025Sperrin 
2489d80c45e0Sbonwick 	ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
2490d80c45e0Sbonwick 	ASSERT(BP_GET_NDVAS(bp) == 0);
2491d80c45e0Sbonwick 	ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
2492d80c45e0Sbonwick 
2493e14bb325SJeff Bonwick 	for (int d = 0; d < ndvas; d++) {
24948654d025Sperrin 		error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
2495e14bb325SJeff Bonwick 		    txg, flags);
24960713e232SGeorge Wilson 		if (error != 0) {
2497d80c45e0Sbonwick 			for (d--; d >= 0; d--) {
2498d80c45e0Sbonwick 				metaslab_free_dva(spa, &dva[d], txg, B_TRUE);
2499d80c45e0Sbonwick 				bzero(&dva[d], sizeof (dva_t));
2500d80c45e0Sbonwick 			}
2501e14bb325SJeff Bonwick 			spa_config_exit(spa, SCL_ALLOC, FTAG);
2502d80c45e0Sbonwick 			return (error);
2503d80c45e0Sbonwick 		}
2504d80c45e0Sbonwick 	}
2505d80c45e0Sbonwick 	ASSERT(error == 0);
2506d80c45e0Sbonwick 	ASSERT(BP_GET_NDVAS(bp) == ndvas);
2507d80c45e0Sbonwick 
2508e14bb325SJeff Bonwick 	spa_config_exit(spa, SCL_ALLOC, FTAG);
2509e14bb325SJeff Bonwick 
2510b24ab676SJeff Bonwick 	BP_SET_BIRTH(bp, txg, txg);
2511e14bb325SJeff Bonwick 
2512d80c45e0Sbonwick 	return (0);
2513d80c45e0Sbonwick }
2514d80c45e0Sbonwick 
2515d80c45e0Sbonwick void
metaslab_free(spa_t * spa,const blkptr_t * bp,uint64_t txg,boolean_t now)2516d80c45e0Sbonwick metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
2517d80c45e0Sbonwick {
2518d80c45e0Sbonwick 	const dva_t *dva = bp->blk_dva;
2519d80c45e0Sbonwick 	int ndvas = BP_GET_NDVAS(bp);
2520d80c45e0Sbonwick 
2521d80c45e0Sbonwick 	ASSERT(!BP_IS_HOLE(bp));
2522b24ab676SJeff Bonwick 	ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
2523d80c45e0Sbonwick 
2524e14bb325SJeff Bonwick 	spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
2525e14bb325SJeff Bonwick 
2526e14bb325SJeff Bonwick 	for (int d = 0; d < ndvas; d++)
2527d80c45e0Sbonwick 		metaslab_free_dva(spa, &dva[d], txg, now);
2528e14bb325SJeff Bonwick 
2529e14bb325SJeff Bonwick 	spa_config_exit(spa, SCL_FREE, FTAG);
2530d80c45e0Sbonwick }
2531d80c45e0Sbonwick 
2532d80c45e0Sbonwick int
metaslab_claim(spa_t * spa,const blkptr_t * bp,uint64_t txg)2533d80c45e0Sbonwick metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
2534d80c45e0Sbonwick {
2535d80c45e0Sbonwick 	const dva_t *dva = bp->blk_dva;
2536d80c45e0Sbonwick 	int ndvas = BP_GET_NDVAS(bp);
2537e14bb325SJeff Bonwick 	int error = 0;
2538d80c45e0Sbonwick 
2539d80c45e0Sbonwick 	ASSERT(!BP_IS_HOLE(bp));
2540d80c45e0Sbonwick 
2541e14bb325SJeff Bonwick 	if (txg != 0) {
2542e14bb325SJeff Bonwick 		/*
2543e14bb325SJeff Bonwick 		 * First do a dry run to make sure all DVAs are claimable,
2544e14bb325SJeff Bonwick 		 * so we don't have to unwind from partial failures below.
2545e14bb325SJeff Bonwick 		 */
2546e14bb325SJeff Bonwick 		if ((error = metaslab_claim(spa, bp, 0)) != 0)
2547e14bb325SJeff Bonwick 			return (error);
2548e14bb325SJeff Bonwick 	}
2549d80c45e0Sbonwick 
2550e14bb325SJeff Bonwick 	spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
2551e14bb325SJeff Bonwick 
2552e14bb325SJeff Bonwick 	for (int d = 0; d < ndvas; d++)
2553e14bb325SJeff Bonwick 		if ((error = metaslab_claim_dva(spa, &dva[d], txg)) != 0)
2554e14bb325SJeff Bonwick 			break;
2555e14bb325SJeff Bonwick 
2556e14bb325SJeff Bonwick 	spa_config_exit(spa, SCL_ALLOC, FTAG);
2557e14bb325SJeff Bonwick 
2558e14bb325SJeff Bonwick 	ASSERT(error == 0 || txg == 0);
2559e14bb325SJeff Bonwick 
2560e14bb325SJeff Bonwick 	return (error);
2561d80c45e0Sbonwick }
25623b2aab18SMatthew Ahrens 
25633b2aab18SMatthew Ahrens void
metaslab_check_free(spa_t * spa,const blkptr_t * bp)25643b2aab18SMatthew Ahrens metaslab_check_free(spa_t *spa, const blkptr_t *bp)
25653b2aab18SMatthew Ahrens {
25663b2aab18SMatthew Ahrens 	if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
25673b2aab18SMatthew Ahrens 		return;
25683b2aab18SMatthew Ahrens 
25693b2aab18SMatthew Ahrens 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
25703b2aab18SMatthew Ahrens 	for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
25710713e232SGeorge Wilson 		uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
25720713e232SGeorge Wilson 		vdev_t *vd = vdev_lookup_top(spa, vdev);
25730713e232SGeorge Wilson 		uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
25743b2aab18SMatthew Ahrens 		uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
25750713e232SGeorge Wilson 		metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
25763b2aab18SMatthew Ahrens 
25770713e232SGeorge Wilson 		if (msp->ms_loaded)
25780713e232SGeorge Wilson 			range_tree_verify(msp->ms_tree, offset, size);
25793b2aab18SMatthew Ahrens 
25803b2aab18SMatthew Ahrens 		for (int j = 0; j < TXG_SIZE; j++)
25810713e232SGeorge Wilson 			range_tree_verify(msp->ms_freetree[j], offset, size);
25823b2aab18SMatthew Ahrens 		for (int j = 0; j < TXG_DEFER_SIZE; j++)
25830713e232SGeorge Wilson 			range_tree_verify(msp->ms_defertree[j], offset, size);
25843b2aab18SMatthew Ahrens 	}
25853b2aab18SMatthew Ahrens 	spa_config_exit(spa, SCL_VDEV, FTAG);
25863b2aab18SMatthew Ahrens }
2587