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