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