]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/metaslab.c
Vendor import of openzfs master @ 184df27eef0abdc7ab2105b21257f753834b936b
[FreeBSD/FreeBSD.git] / 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, 2019 by Delphix. All rights reserved.
24  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
25  * Copyright (c) 2017, Intel Corporation.
26  */
27
28 #include <sys/zfs_context.h>
29 #include <sys/dmu.h>
30 #include <sys/dmu_tx.h>
31 #include <sys/space_map.h>
32 #include <sys/metaslab_impl.h>
33 #include <sys/vdev_impl.h>
34 #include <sys/zio.h>
35 #include <sys/spa_impl.h>
36 #include <sys/zfeature.h>
37 #include <sys/vdev_indirect_mapping.h>
38 #include <sys/zap.h>
39 #include <sys/btree.h>
40
41 #define WITH_DF_BLOCK_ALLOCATOR
42
43 #define GANG_ALLOCATION(flags) \
44         ((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER))
45
46 /*
47  * Metaslab granularity, in bytes. This is roughly similar to what would be
48  * referred to as the "stripe size" in traditional RAID arrays. In normal
49  * operation, we will try to write this amount of data to a top-level vdev
50  * before moving on to the next one.
51  */
52 unsigned long metaslab_aliquot = 512 << 10;
53
54 /*
55  * For testing, make some blocks above a certain size be gang blocks.
56  */
57 unsigned long metaslab_force_ganging = SPA_MAXBLOCKSIZE + 1;
58
59 /*
60  * In pools where the log space map feature is not enabled we touch
61  * multiple metaslabs (and their respective space maps) with each
62  * transaction group. Thus, we benefit from having a small space map
63  * block size since it allows us to issue more I/O operations scattered
64  * around the disk. So a sane default for the space map block size
65  * is 8~16K.
66  */
67 int zfs_metaslab_sm_blksz_no_log = (1 << 14);
68
69 /*
70  * When the log space map feature is enabled, we accumulate a lot of
71  * changes per metaslab that are flushed once in a while so we benefit
72  * from a bigger block size like 128K for the metaslab space maps.
73  */
74 int zfs_metaslab_sm_blksz_with_log = (1 << 17);
75
76 /*
77  * The in-core space map representation is more compact than its on-disk form.
78  * The zfs_condense_pct determines how much more compact the in-core
79  * space map representation must be before we compact it on-disk.
80  * Values should be greater than or equal to 100.
81  */
82 int zfs_condense_pct = 200;
83
84 /*
85  * Condensing a metaslab is not guaranteed to actually reduce the amount of
86  * space used on disk. In particular, a space map uses data in increments of
87  * MAX(1 << ashift, space_map_blksz), so a metaslab might use the
88  * same number of blocks after condensing. Since the goal of condensing is to
89  * reduce the number of IOPs required to read the space map, we only want to
90  * condense when we can be sure we will reduce the number of blocks used by the
91  * space map. Unfortunately, we cannot precisely compute whether or not this is
92  * the case in metaslab_should_condense since we are holding ms_lock. Instead,
93  * we apply the following heuristic: do not condense a spacemap unless the
94  * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
95  * blocks.
96  */
97 int zfs_metaslab_condense_block_threshold = 4;
98
99 /*
100  * The zfs_mg_noalloc_threshold defines which metaslab groups should
101  * be eligible for allocation. The value is defined as a percentage of
102  * free space. Metaslab groups that have more free space than
103  * zfs_mg_noalloc_threshold are always eligible for allocations. Once
104  * a metaslab group's free space is less than or equal to the
105  * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
106  * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
107  * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
108  * groups are allowed to accept allocations. Gang blocks are always
109  * eligible to allocate on any metaslab group. The default value of 0 means
110  * no metaslab group will be excluded based on this criterion.
111  */
112 int zfs_mg_noalloc_threshold = 0;
113
114 /*
115  * Metaslab groups are considered eligible for allocations if their
116  * fragmentation metric (measured as a percentage) is less than or
117  * equal to zfs_mg_fragmentation_threshold. If a metaslab group
118  * exceeds this threshold then it will be skipped unless all metaslab
119  * groups within the metaslab class have also crossed this threshold.
120  *
121  * This tunable was introduced to avoid edge cases where we continue
122  * allocating from very fragmented disks in our pool while other, less
123  * fragmented disks, exists. On the other hand, if all disks in the
124  * pool are uniformly approaching the threshold, the threshold can
125  * be a speed bump in performance, where we keep switching the disks
126  * that we allocate from (e.g. we allocate some segments from disk A
127  * making it bypassing the threshold while freeing segments from disk
128  * B getting its fragmentation below the threshold).
129  *
130  * Empirically, we've seen that our vdev selection for allocations is
131  * good enough that fragmentation increases uniformly across all vdevs
132  * the majority of the time. Thus we set the threshold percentage high
133  * enough to avoid hitting the speed bump on pools that are being pushed
134  * to the edge.
135  */
136 int zfs_mg_fragmentation_threshold = 95;
137
138 /*
139  * Allow metaslabs to keep their active state as long as their fragmentation
140  * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
141  * active metaslab that exceeds this threshold will no longer keep its active
142  * status allowing better metaslabs to be selected.
143  */
144 int zfs_metaslab_fragmentation_threshold = 70;
145
146 /*
147  * When set will load all metaslabs when pool is first opened.
148  */
149 int metaslab_debug_load = 0;
150
151 /*
152  * When set will prevent metaslabs from being unloaded.
153  */
154 int metaslab_debug_unload = 0;
155
156 /*
157  * Minimum size which forces the dynamic allocator to change
158  * it's allocation strategy.  Once the space map cannot satisfy
159  * an allocation of this size then it switches to using more
160  * aggressive strategy (i.e search by size rather than offset).
161  */
162 uint64_t metaslab_df_alloc_threshold = SPA_OLD_MAXBLOCKSIZE;
163
164 /*
165  * The minimum free space, in percent, which must be available
166  * in a space map to continue allocations in a first-fit fashion.
167  * Once the space map's free space drops below this level we dynamically
168  * switch to using best-fit allocations.
169  */
170 int metaslab_df_free_pct = 4;
171
172 /*
173  * Maximum distance to search forward from the last offset. Without this
174  * limit, fragmented pools can see >100,000 iterations and
175  * metaslab_block_picker() becomes the performance limiting factor on
176  * high-performance storage.
177  *
178  * With the default setting of 16MB, we typically see less than 500
179  * iterations, even with very fragmented, ashift=9 pools. The maximum number
180  * of iterations possible is:
181  *     metaslab_df_max_search / (2 * (1<<ashift))
182  * With the default setting of 16MB this is 16*1024 (with ashift=9) or
183  * 2048 (with ashift=12).
184  */
185 int metaslab_df_max_search = 16 * 1024 * 1024;
186
187 /*
188  * Forces the metaslab_block_picker function to search for at least this many
189  * segments forwards until giving up on finding a segment that the allocation
190  * will fit into.
191  */
192 uint32_t metaslab_min_search_count = 100;
193
194 /*
195  * If we are not searching forward (due to metaslab_df_max_search,
196  * metaslab_df_free_pct, or metaslab_df_alloc_threshold), this tunable
197  * controls what segment is used.  If it is set, we will use the largest free
198  * segment.  If it is not set, we will use a segment of exactly the requested
199  * size (or larger).
200  */
201 int metaslab_df_use_largest_segment = B_FALSE;
202
203 /*
204  * Percentage of all cpus that can be used by the metaslab taskq.
205  */
206 int metaslab_load_pct = 50;
207
208 /*
209  * These tunables control how long a metaslab will remain loaded after the
210  * last allocation from it.  A metaslab can't be unloaded until at least
211  * metaslab_unload_delay TXG's and metaslab_unload_delay_ms milliseconds
212  * have elapsed.  However, zfs_metaslab_mem_limit may cause it to be
213  * unloaded sooner.  These settings are intended to be generous -- to keep
214  * metaslabs loaded for a long time, reducing the rate of metaslab loading.
215  */
216 int metaslab_unload_delay = 32;
217 int metaslab_unload_delay_ms = 10 * 60 * 1000; /* ten minutes */
218
219 /*
220  * Max number of metaslabs per group to preload.
221  */
222 int metaslab_preload_limit = 10;
223
224 /*
225  * Enable/disable preloading of metaslab.
226  */
227 int metaslab_preload_enabled = B_TRUE;
228
229 /*
230  * Enable/disable fragmentation weighting on metaslabs.
231  */
232 int metaslab_fragmentation_factor_enabled = B_TRUE;
233
234 /*
235  * Enable/disable lba weighting (i.e. outer tracks are given preference).
236  */
237 int metaslab_lba_weighting_enabled = B_TRUE;
238
239 /*
240  * Enable/disable metaslab group biasing.
241  */
242 int metaslab_bias_enabled = B_TRUE;
243
244 /*
245  * Enable/disable remapping of indirect DVAs to their concrete vdevs.
246  */
247 boolean_t zfs_remap_blkptr_enable = B_TRUE;
248
249 /*
250  * Enable/disable segment-based metaslab selection.
251  */
252 int zfs_metaslab_segment_weight_enabled = B_TRUE;
253
254 /*
255  * When using segment-based metaslab selection, we will continue
256  * allocating from the active metaslab until we have exhausted
257  * zfs_metaslab_switch_threshold of its buckets.
258  */
259 int zfs_metaslab_switch_threshold = 2;
260
261 /*
262  * Internal switch to enable/disable the metaslab allocation tracing
263  * facility.
264  */
265 #ifdef _METASLAB_TRACING
266 boolean_t metaslab_trace_enabled = B_TRUE;
267 #endif
268
269 /*
270  * Maximum entries that the metaslab allocation tracing facility will keep
271  * in a given list when running in non-debug mode. We limit the number
272  * of entries in non-debug mode to prevent us from using up too much memory.
273  * The limit should be sufficiently large that we don't expect any allocation
274  * to every exceed this value. In debug mode, the system will panic if this
275  * limit is ever reached allowing for further investigation.
276  */
277 #ifdef _METASLAB_TRACING
278 uint64_t metaslab_trace_max_entries = 5000;
279 #endif
280
281 /*
282  * Maximum number of metaslabs per group that can be disabled
283  * simultaneously.
284  */
285 int max_disabled_ms = 3;
286
287 /*
288  * Time (in seconds) to respect ms_max_size when the metaslab is not loaded.
289  * To avoid 64-bit overflow, don't set above UINT32_MAX.
290  */
291 unsigned long zfs_metaslab_max_size_cache_sec = 3600; /* 1 hour */
292
293 /*
294  * Maximum percentage of memory to use on storing loaded metaslabs. If loading
295  * a metaslab would take it over this percentage, the oldest selected metaslab
296  * is automatically unloaded.
297  */
298 int zfs_metaslab_mem_limit = 75;
299
300 /*
301  * Force the per-metaslab range trees to use 64-bit integers to store
302  * segments. Used for debugging purposes.
303  */
304 boolean_t zfs_metaslab_force_large_segs = B_FALSE;
305
306 /*
307  * By default we only store segments over a certain size in the size-sorted
308  * metaslab trees (ms_allocatable_by_size and
309  * ms_unflushed_frees_by_size). This dramatically reduces memory usage and
310  * improves load and unload times at the cost of causing us to use slightly
311  * larger segments than we would otherwise in some cases.
312  */
313 uint32_t metaslab_by_size_min_shift = 14;
314
315 static uint64_t metaslab_weight(metaslab_t *, boolean_t);
316 static void metaslab_set_fragmentation(metaslab_t *, boolean_t);
317 static void metaslab_free_impl(vdev_t *, uint64_t, uint64_t, boolean_t);
318 static void metaslab_check_free_impl(vdev_t *, uint64_t, uint64_t);
319
320 static void metaslab_passivate(metaslab_t *msp, uint64_t weight);
321 static uint64_t metaslab_weight_from_range_tree(metaslab_t *msp);
322 static void metaslab_flush_update(metaslab_t *, dmu_tx_t *);
323 static unsigned int metaslab_idx_func(multilist_t *, void *);
324 static void metaslab_evict(metaslab_t *, uint64_t);
325 static void metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg);
326 #ifdef _METASLAB_TRACING
327 kmem_cache_t *metaslab_alloc_trace_cache;
328
329 typedef struct metaslab_stats {
330         kstat_named_t metaslabstat_trace_over_limit;
331         kstat_named_t metaslabstat_df_find_under_floor;
332         kstat_named_t metaslabstat_reload_tree;
333 } metaslab_stats_t;
334
335 static metaslab_stats_t metaslab_stats = {
336         { "trace_over_limit",           KSTAT_DATA_UINT64 },
337         { "df_find_under_floor",        KSTAT_DATA_UINT64 },
338         { "reload_tree",                KSTAT_DATA_UINT64 },
339 };
340
341 #define METASLABSTAT_BUMP(stat) \
342         atomic_inc_64(&metaslab_stats.stat.value.ui64);
343
344
345 kstat_t *metaslab_ksp;
346
347 void
348 metaslab_stat_init(void)
349 {
350         ASSERT(metaslab_alloc_trace_cache == NULL);
351         metaslab_alloc_trace_cache = kmem_cache_create(
352             "metaslab_alloc_trace_cache", sizeof (metaslab_alloc_trace_t),
353             0, NULL, NULL, NULL, NULL, NULL, 0);
354         metaslab_ksp = kstat_create("zfs", 0, "metaslab_stats",
355             "misc", KSTAT_TYPE_NAMED, sizeof (metaslab_stats) /
356             sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
357         if (metaslab_ksp != NULL) {
358                 metaslab_ksp->ks_data = &metaslab_stats;
359                 kstat_install(metaslab_ksp);
360         }
361 }
362
363 void
364 metaslab_stat_fini(void)
365 {
366         if (metaslab_ksp != NULL) {
367                 kstat_delete(metaslab_ksp);
368                 metaslab_ksp = NULL;
369         }
370
371         kmem_cache_destroy(metaslab_alloc_trace_cache);
372         metaslab_alloc_trace_cache = NULL;
373 }
374 #else
375
376 void
377 metaslab_stat_init(void)
378 {
379 }
380
381 void
382 metaslab_stat_fini(void)
383 {
384 }
385 #endif
386
387 /*
388  * ==========================================================================
389  * Metaslab classes
390  * ==========================================================================
391  */
392 metaslab_class_t *
393 metaslab_class_create(spa_t *spa, metaslab_ops_t *ops)
394 {
395         metaslab_class_t *mc;
396
397         mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
398
399         mc->mc_spa = spa;
400         mc->mc_rotor = NULL;
401         mc->mc_ops = ops;
402         mutex_init(&mc->mc_lock, NULL, MUTEX_DEFAULT, NULL);
403         mc->mc_metaslab_txg_list = multilist_create(sizeof (metaslab_t),
404             offsetof(metaslab_t, ms_class_txg_node), metaslab_idx_func);
405         mc->mc_alloc_slots = kmem_zalloc(spa->spa_alloc_count *
406             sizeof (zfs_refcount_t), KM_SLEEP);
407         mc->mc_alloc_max_slots = kmem_zalloc(spa->spa_alloc_count *
408             sizeof (uint64_t), KM_SLEEP);
409         for (int i = 0; i < spa->spa_alloc_count; i++)
410                 zfs_refcount_create_tracked(&mc->mc_alloc_slots[i]);
411
412         return (mc);
413 }
414
415 void
416 metaslab_class_destroy(metaslab_class_t *mc)
417 {
418         ASSERT(mc->mc_rotor == NULL);
419         ASSERT(mc->mc_alloc == 0);
420         ASSERT(mc->mc_deferred == 0);
421         ASSERT(mc->mc_space == 0);
422         ASSERT(mc->mc_dspace == 0);
423
424         for (int i = 0; i < mc->mc_spa->spa_alloc_count; i++)
425                 zfs_refcount_destroy(&mc->mc_alloc_slots[i]);
426         kmem_free(mc->mc_alloc_slots, mc->mc_spa->spa_alloc_count *
427             sizeof (zfs_refcount_t));
428         kmem_free(mc->mc_alloc_max_slots, mc->mc_spa->spa_alloc_count *
429             sizeof (uint64_t));
430         mutex_destroy(&mc->mc_lock);
431         multilist_destroy(mc->mc_metaslab_txg_list);
432         kmem_free(mc, sizeof (metaslab_class_t));
433 }
434
435 int
436 metaslab_class_validate(metaslab_class_t *mc)
437 {
438         metaslab_group_t *mg;
439         vdev_t *vd;
440
441         /*
442          * Must hold one of the spa_config locks.
443          */
444         ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
445             spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
446
447         if ((mg = mc->mc_rotor) == NULL)
448                 return (0);
449
450         do {
451                 vd = mg->mg_vd;
452                 ASSERT(vd->vdev_mg != NULL);
453                 ASSERT3P(vd->vdev_top, ==, vd);
454                 ASSERT3P(mg->mg_class, ==, mc);
455                 ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
456         } while ((mg = mg->mg_next) != mc->mc_rotor);
457
458         return (0);
459 }
460
461 static void
462 metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
463     int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
464 {
465         atomic_add_64(&mc->mc_alloc, alloc_delta);
466         atomic_add_64(&mc->mc_deferred, defer_delta);
467         atomic_add_64(&mc->mc_space, space_delta);
468         atomic_add_64(&mc->mc_dspace, dspace_delta);
469 }
470
471 uint64_t
472 metaslab_class_get_alloc(metaslab_class_t *mc)
473 {
474         return (mc->mc_alloc);
475 }
476
477 uint64_t
478 metaslab_class_get_deferred(metaslab_class_t *mc)
479 {
480         return (mc->mc_deferred);
481 }
482
483 uint64_t
484 metaslab_class_get_space(metaslab_class_t *mc)
485 {
486         return (mc->mc_space);
487 }
488
489 uint64_t
490 metaslab_class_get_dspace(metaslab_class_t *mc)
491 {
492         return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
493 }
494
495 void
496 metaslab_class_histogram_verify(metaslab_class_t *mc)
497 {
498         spa_t *spa = mc->mc_spa;
499         vdev_t *rvd = spa->spa_root_vdev;
500         uint64_t *mc_hist;
501         int i;
502
503         if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
504                 return;
505
506         mc_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
507             KM_SLEEP);
508
509         for (int c = 0; c < rvd->vdev_children; c++) {
510                 vdev_t *tvd = rvd->vdev_child[c];
511                 metaslab_group_t *mg = tvd->vdev_mg;
512
513                 /*
514                  * Skip any holes, uninitialized top-levels, or
515                  * vdevs that are not in this metalab class.
516                  */
517                 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
518                     mg->mg_class != mc) {
519                         continue;
520                 }
521
522                 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
523                         mc_hist[i] += mg->mg_histogram[i];
524         }
525
526         for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
527                 VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
528
529         kmem_free(mc_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
530 }
531
532 /*
533  * Calculate the metaslab class's fragmentation metric. The metric
534  * is weighted based on the space contribution of each metaslab group.
535  * The return value will be a number between 0 and 100 (inclusive), or
536  * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
537  * zfs_frag_table for more information about the metric.
538  */
539 uint64_t
540 metaslab_class_fragmentation(metaslab_class_t *mc)
541 {
542         vdev_t *rvd = mc->mc_spa->spa_root_vdev;
543         uint64_t fragmentation = 0;
544
545         spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
546
547         for (int c = 0; c < rvd->vdev_children; c++) {
548                 vdev_t *tvd = rvd->vdev_child[c];
549                 metaslab_group_t *mg = tvd->vdev_mg;
550
551                 /*
552                  * Skip any holes, uninitialized top-levels,
553                  * or vdevs that are not in this metalab class.
554                  */
555                 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
556                     mg->mg_class != mc) {
557                         continue;
558                 }
559
560                 /*
561                  * If a metaslab group does not contain a fragmentation
562                  * metric then just bail out.
563                  */
564                 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
565                         spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
566                         return (ZFS_FRAG_INVALID);
567                 }
568
569                 /*
570                  * Determine how much this metaslab_group is contributing
571                  * to the overall pool fragmentation metric.
572                  */
573                 fragmentation += mg->mg_fragmentation *
574                     metaslab_group_get_space(mg);
575         }
576         fragmentation /= metaslab_class_get_space(mc);
577
578         ASSERT3U(fragmentation, <=, 100);
579         spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
580         return (fragmentation);
581 }
582
583 /*
584  * Calculate the amount of expandable space that is available in
585  * this metaslab class. If a device is expanded then its expandable
586  * space will be the amount of allocatable space that is currently not
587  * part of this metaslab class.
588  */
589 uint64_t
590 metaslab_class_expandable_space(metaslab_class_t *mc)
591 {
592         vdev_t *rvd = mc->mc_spa->spa_root_vdev;
593         uint64_t space = 0;
594
595         spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
596         for (int c = 0; c < rvd->vdev_children; c++) {
597                 vdev_t *tvd = rvd->vdev_child[c];
598                 metaslab_group_t *mg = tvd->vdev_mg;
599
600                 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
601                     mg->mg_class != mc) {
602                         continue;
603                 }
604
605                 /*
606                  * Calculate if we have enough space to add additional
607                  * metaslabs. We report the expandable space in terms
608                  * of the metaslab size since that's the unit of expansion.
609                  */
610                 space += P2ALIGN(tvd->vdev_max_asize - tvd->vdev_asize,
611                     1ULL << tvd->vdev_ms_shift);
612         }
613         spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
614         return (space);
615 }
616
617 void
618 metaslab_class_evict_old(metaslab_class_t *mc, uint64_t txg)
619 {
620         multilist_t *ml = mc->mc_metaslab_txg_list;
621         for (int i = 0; i < multilist_get_num_sublists(ml); i++) {
622                 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
623                 metaslab_t *msp = multilist_sublist_head(mls);
624                 multilist_sublist_unlock(mls);
625                 while (msp != NULL) {
626                         mutex_enter(&msp->ms_lock);
627
628                         /*
629                          * If the metaslab has been removed from the list
630                          * (which could happen if we were at the memory limit
631                          * and it was evicted during this loop), then we can't
632                          * proceed and we should restart the sublist.
633                          */
634                         if (!multilist_link_active(&msp->ms_class_txg_node)) {
635                                 mutex_exit(&msp->ms_lock);
636                                 i--;
637                                 break;
638                         }
639                         mls = multilist_sublist_lock(ml, i);
640                         metaslab_t *next_msp = multilist_sublist_next(mls, msp);
641                         multilist_sublist_unlock(mls);
642                         if (txg >
643                             msp->ms_selected_txg + metaslab_unload_delay &&
644                             gethrtime() > msp->ms_selected_time +
645                             (uint64_t)MSEC2NSEC(metaslab_unload_delay_ms)) {
646                                 metaslab_evict(msp, txg);
647                         } else {
648                                 /*
649                                  * Once we've hit a metaslab selected too
650                                  * recently to evict, we're done evicting for
651                                  * now.
652                                  */
653                                 mutex_exit(&msp->ms_lock);
654                                 break;
655                         }
656                         mutex_exit(&msp->ms_lock);
657                         msp = next_msp;
658                 }
659         }
660 }
661
662 static int
663 metaslab_compare(const void *x1, const void *x2)
664 {
665         const metaslab_t *m1 = (const metaslab_t *)x1;
666         const metaslab_t *m2 = (const metaslab_t *)x2;
667
668         int sort1 = 0;
669         int sort2 = 0;
670         if (m1->ms_allocator != -1 && m1->ms_primary)
671                 sort1 = 1;
672         else if (m1->ms_allocator != -1 && !m1->ms_primary)
673                 sort1 = 2;
674         if (m2->ms_allocator != -1 && m2->ms_primary)
675                 sort2 = 1;
676         else if (m2->ms_allocator != -1 && !m2->ms_primary)
677                 sort2 = 2;
678
679         /*
680          * Sort inactive metaslabs first, then primaries, then secondaries. When
681          * selecting a metaslab to allocate from, an allocator first tries its
682          * primary, then secondary active metaslab. If it doesn't have active
683          * metaslabs, or can't allocate from them, it searches for an inactive
684          * metaslab to activate. If it can't find a suitable one, it will steal
685          * a primary or secondary metaslab from another allocator.
686          */
687         if (sort1 < sort2)
688                 return (-1);
689         if (sort1 > sort2)
690                 return (1);
691
692         int cmp = TREE_CMP(m2->ms_weight, m1->ms_weight);
693         if (likely(cmp))
694                 return (cmp);
695
696         IMPLY(TREE_CMP(m1->ms_start, m2->ms_start) == 0, m1 == m2);
697
698         return (TREE_CMP(m1->ms_start, m2->ms_start));
699 }
700
701 /*
702  * ==========================================================================
703  * Metaslab groups
704  * ==========================================================================
705  */
706 /*
707  * Update the allocatable flag and the metaslab group's capacity.
708  * The allocatable flag is set to true if the capacity is below
709  * the zfs_mg_noalloc_threshold or has a fragmentation value that is
710  * greater than zfs_mg_fragmentation_threshold. If a metaslab group
711  * transitions from allocatable to non-allocatable or vice versa then the
712  * metaslab group's class is updated to reflect the transition.
713  */
714 static void
715 metaslab_group_alloc_update(metaslab_group_t *mg)
716 {
717         vdev_t *vd = mg->mg_vd;
718         metaslab_class_t *mc = mg->mg_class;
719         vdev_stat_t *vs = &vd->vdev_stat;
720         boolean_t was_allocatable;
721         boolean_t was_initialized;
722
723         ASSERT(vd == vd->vdev_top);
724         ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_READER), ==,
725             SCL_ALLOC);
726
727         mutex_enter(&mg->mg_lock);
728         was_allocatable = mg->mg_allocatable;
729         was_initialized = mg->mg_initialized;
730
731         mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
732             (vs->vs_space + 1);
733
734         mutex_enter(&mc->mc_lock);
735
736         /*
737          * If the metaslab group was just added then it won't
738          * have any space until we finish syncing out this txg.
739          * At that point we will consider it initialized and available
740          * for allocations.  We also don't consider non-activated
741          * metaslab groups (e.g. vdevs that are in the middle of being removed)
742          * to be initialized, because they can't be used for allocation.
743          */
744         mg->mg_initialized = metaslab_group_initialized(mg);
745         if (!was_initialized && mg->mg_initialized) {
746                 mc->mc_groups++;
747         } else if (was_initialized && !mg->mg_initialized) {
748                 ASSERT3U(mc->mc_groups, >, 0);
749                 mc->mc_groups--;
750         }
751         if (mg->mg_initialized)
752                 mg->mg_no_free_space = B_FALSE;
753
754         /*
755          * A metaslab group is considered allocatable if it has plenty
756          * of free space or is not heavily fragmented. We only take
757          * fragmentation into account if the metaslab group has a valid
758          * fragmentation metric (i.e. a value between 0 and 100).
759          */
760         mg->mg_allocatable = (mg->mg_activation_count > 0 &&
761             mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
762             (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
763             mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
764
765         /*
766          * The mc_alloc_groups maintains a count of the number of
767          * groups in this metaslab class that are still above the
768          * zfs_mg_noalloc_threshold. This is used by the allocating
769          * threads to determine if they should avoid allocations to
770          * a given group. The allocator will avoid allocations to a group
771          * if that group has reached or is below the zfs_mg_noalloc_threshold
772          * and there are still other groups that are above the threshold.
773          * When a group transitions from allocatable to non-allocatable or
774          * vice versa we update the metaslab class to reflect that change.
775          * When the mc_alloc_groups value drops to 0 that means that all
776          * groups have reached the zfs_mg_noalloc_threshold making all groups
777          * eligible for allocations. This effectively means that all devices
778          * are balanced again.
779          */
780         if (was_allocatable && !mg->mg_allocatable)
781                 mc->mc_alloc_groups--;
782         else if (!was_allocatable && mg->mg_allocatable)
783                 mc->mc_alloc_groups++;
784         mutex_exit(&mc->mc_lock);
785
786         mutex_exit(&mg->mg_lock);
787 }
788
789 int
790 metaslab_sort_by_flushed(const void *va, const void *vb)
791 {
792         const metaslab_t *a = va;
793         const metaslab_t *b = vb;
794
795         int cmp = TREE_CMP(a->ms_unflushed_txg, b->ms_unflushed_txg);
796         if (likely(cmp))
797                 return (cmp);
798
799         uint64_t a_vdev_id = a->ms_group->mg_vd->vdev_id;
800         uint64_t b_vdev_id = b->ms_group->mg_vd->vdev_id;
801         cmp = TREE_CMP(a_vdev_id, b_vdev_id);
802         if (cmp)
803                 return (cmp);
804
805         return (TREE_CMP(a->ms_id, b->ms_id));
806 }
807
808 metaslab_group_t *
809 metaslab_group_create(metaslab_class_t *mc, vdev_t *vd, int allocators)
810 {
811         metaslab_group_t *mg;
812
813         mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
814         mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
815         mutex_init(&mg->mg_ms_disabled_lock, NULL, MUTEX_DEFAULT, NULL);
816         cv_init(&mg->mg_ms_disabled_cv, NULL, CV_DEFAULT, NULL);
817         avl_create(&mg->mg_metaslab_tree, metaslab_compare,
818             sizeof (metaslab_t), offsetof(metaslab_t, ms_group_node));
819         mg->mg_vd = vd;
820         mg->mg_class = mc;
821         mg->mg_activation_count = 0;
822         mg->mg_initialized = B_FALSE;
823         mg->mg_no_free_space = B_TRUE;
824         mg->mg_allocators = allocators;
825
826         mg->mg_allocator = kmem_zalloc(allocators *
827             sizeof (metaslab_group_allocator_t), KM_SLEEP);
828         for (int i = 0; i < allocators; i++) {
829                 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
830                 zfs_refcount_create_tracked(&mga->mga_alloc_queue_depth);
831         }
832
833         mg->mg_taskq = taskq_create("metaslab_group_taskq", metaslab_load_pct,
834             maxclsyspri, 10, INT_MAX, TASKQ_THREADS_CPU_PCT | TASKQ_DYNAMIC);
835
836         return (mg);
837 }
838
839 void
840 metaslab_group_destroy(metaslab_group_t *mg)
841 {
842         ASSERT(mg->mg_prev == NULL);
843         ASSERT(mg->mg_next == NULL);
844         /*
845          * We may have gone below zero with the activation count
846          * either because we never activated in the first place or
847          * because we're done, and possibly removing the vdev.
848          */
849         ASSERT(mg->mg_activation_count <= 0);
850
851         taskq_destroy(mg->mg_taskq);
852         avl_destroy(&mg->mg_metaslab_tree);
853         mutex_destroy(&mg->mg_lock);
854         mutex_destroy(&mg->mg_ms_disabled_lock);
855         cv_destroy(&mg->mg_ms_disabled_cv);
856
857         for (int i = 0; i < mg->mg_allocators; i++) {
858                 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
859                 zfs_refcount_destroy(&mga->mga_alloc_queue_depth);
860         }
861         kmem_free(mg->mg_allocator, mg->mg_allocators *
862             sizeof (metaslab_group_allocator_t));
863
864         kmem_free(mg, sizeof (metaslab_group_t));
865 }
866
867 void
868 metaslab_group_activate(metaslab_group_t *mg)
869 {
870         metaslab_class_t *mc = mg->mg_class;
871         metaslab_group_t *mgprev, *mgnext;
872
873         ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER), !=, 0);
874
875         ASSERT(mc->mc_rotor != mg);
876         ASSERT(mg->mg_prev == NULL);
877         ASSERT(mg->mg_next == NULL);
878         ASSERT(mg->mg_activation_count <= 0);
879
880         if (++mg->mg_activation_count <= 0)
881                 return;
882
883         mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
884         metaslab_group_alloc_update(mg);
885
886         if ((mgprev = mc->mc_rotor) == NULL) {
887                 mg->mg_prev = mg;
888                 mg->mg_next = mg;
889         } else {
890                 mgnext = mgprev->mg_next;
891                 mg->mg_prev = mgprev;
892                 mg->mg_next = mgnext;
893                 mgprev->mg_next = mg;
894                 mgnext->mg_prev = mg;
895         }
896         mc->mc_rotor = mg;
897 }
898
899 /*
900  * Passivate a metaslab group and remove it from the allocation rotor.
901  * Callers must hold both the SCL_ALLOC and SCL_ZIO lock prior to passivating
902  * a metaslab group. This function will momentarily drop spa_config_locks
903  * that are lower than the SCL_ALLOC lock (see comment below).
904  */
905 void
906 metaslab_group_passivate(metaslab_group_t *mg)
907 {
908         metaslab_class_t *mc = mg->mg_class;
909         spa_t *spa = mc->mc_spa;
910         metaslab_group_t *mgprev, *mgnext;
911         int locks = spa_config_held(spa, SCL_ALL, RW_WRITER);
912
913         ASSERT3U(spa_config_held(spa, SCL_ALLOC | SCL_ZIO, RW_WRITER), ==,
914             (SCL_ALLOC | SCL_ZIO));
915
916         if (--mg->mg_activation_count != 0) {
917                 ASSERT(mc->mc_rotor != mg);
918                 ASSERT(mg->mg_prev == NULL);
919                 ASSERT(mg->mg_next == NULL);
920                 ASSERT(mg->mg_activation_count < 0);
921                 return;
922         }
923
924         /*
925          * The spa_config_lock is an array of rwlocks, ordered as
926          * follows (from highest to lowest):
927          *      SCL_CONFIG > SCL_STATE > SCL_L2ARC > SCL_ALLOC >
928          *      SCL_ZIO > SCL_FREE > SCL_VDEV
929          * (For more information about the spa_config_lock see spa_misc.c)
930          * The higher the lock, the broader its coverage. When we passivate
931          * a metaslab group, we must hold both the SCL_ALLOC and the SCL_ZIO
932          * config locks. However, the metaslab group's taskq might be trying
933          * to preload metaslabs so we must drop the SCL_ZIO lock and any
934          * lower locks to allow the I/O to complete. At a minimum,
935          * we continue to hold the SCL_ALLOC lock, which prevents any future
936          * allocations from taking place and any changes to the vdev tree.
937          */
938         spa_config_exit(spa, locks & ~(SCL_ZIO - 1), spa);
939         taskq_wait_outstanding(mg->mg_taskq, 0);
940         spa_config_enter(spa, locks & ~(SCL_ZIO - 1), spa, RW_WRITER);
941         metaslab_group_alloc_update(mg);
942         for (int i = 0; i < mg->mg_allocators; i++) {
943                 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
944                 metaslab_t *msp = mga->mga_primary;
945                 if (msp != NULL) {
946                         mutex_enter(&msp->ms_lock);
947                         metaslab_passivate(msp,
948                             metaslab_weight_from_range_tree(msp));
949                         mutex_exit(&msp->ms_lock);
950                 }
951                 msp = mga->mga_secondary;
952                 if (msp != NULL) {
953                         mutex_enter(&msp->ms_lock);
954                         metaslab_passivate(msp,
955                             metaslab_weight_from_range_tree(msp));
956                         mutex_exit(&msp->ms_lock);
957                 }
958         }
959
960         mgprev = mg->mg_prev;
961         mgnext = mg->mg_next;
962
963         if (mg == mgnext) {
964                 mc->mc_rotor = NULL;
965         } else {
966                 mc->mc_rotor = mgnext;
967                 mgprev->mg_next = mgnext;
968                 mgnext->mg_prev = mgprev;
969         }
970
971         mg->mg_prev = NULL;
972         mg->mg_next = NULL;
973 }
974
975 boolean_t
976 metaslab_group_initialized(metaslab_group_t *mg)
977 {
978         vdev_t *vd = mg->mg_vd;
979         vdev_stat_t *vs = &vd->vdev_stat;
980
981         return (vs->vs_space != 0 && mg->mg_activation_count > 0);
982 }
983
984 uint64_t
985 metaslab_group_get_space(metaslab_group_t *mg)
986 {
987         return ((1ULL << mg->mg_vd->vdev_ms_shift) * mg->mg_vd->vdev_ms_count);
988 }
989
990 void
991 metaslab_group_histogram_verify(metaslab_group_t *mg)
992 {
993         uint64_t *mg_hist;
994         vdev_t *vd = mg->mg_vd;
995         uint64_t ashift = vd->vdev_ashift;
996         int i;
997
998         if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
999                 return;
1000
1001         mg_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
1002             KM_SLEEP);
1003
1004         ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE, >=,
1005             SPACE_MAP_HISTOGRAM_SIZE + ashift);
1006
1007         for (int m = 0; m < vd->vdev_ms_count; m++) {
1008                 metaslab_t *msp = vd->vdev_ms[m];
1009
1010                 /* skip if not active or not a member */
1011                 if (msp->ms_sm == NULL || msp->ms_group != mg)
1012                         continue;
1013
1014                 for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
1015                         mg_hist[i + ashift] +=
1016                             msp->ms_sm->sm_phys->smp_histogram[i];
1017         }
1018
1019         for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i ++)
1020                 VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
1021
1022         kmem_free(mg_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
1023 }
1024
1025 static void
1026 metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
1027 {
1028         metaslab_class_t *mc = mg->mg_class;
1029         uint64_t ashift = mg->mg_vd->vdev_ashift;
1030
1031         ASSERT(MUTEX_HELD(&msp->ms_lock));
1032         if (msp->ms_sm == NULL)
1033                 return;
1034
1035         mutex_enter(&mg->mg_lock);
1036         for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1037                 mg->mg_histogram[i + ashift] +=
1038                     msp->ms_sm->sm_phys->smp_histogram[i];
1039                 mc->mc_histogram[i + ashift] +=
1040                     msp->ms_sm->sm_phys->smp_histogram[i];
1041         }
1042         mutex_exit(&mg->mg_lock);
1043 }
1044
1045 void
1046 metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
1047 {
1048         metaslab_class_t *mc = mg->mg_class;
1049         uint64_t ashift = mg->mg_vd->vdev_ashift;
1050
1051         ASSERT(MUTEX_HELD(&msp->ms_lock));
1052         if (msp->ms_sm == NULL)
1053                 return;
1054
1055         mutex_enter(&mg->mg_lock);
1056         for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1057                 ASSERT3U(mg->mg_histogram[i + ashift], >=,
1058                     msp->ms_sm->sm_phys->smp_histogram[i]);
1059                 ASSERT3U(mc->mc_histogram[i + ashift], >=,
1060                     msp->ms_sm->sm_phys->smp_histogram[i]);
1061
1062                 mg->mg_histogram[i + ashift] -=
1063                     msp->ms_sm->sm_phys->smp_histogram[i];
1064                 mc->mc_histogram[i + ashift] -=
1065                     msp->ms_sm->sm_phys->smp_histogram[i];
1066         }
1067         mutex_exit(&mg->mg_lock);
1068 }
1069
1070 static void
1071 metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
1072 {
1073         ASSERT(msp->ms_group == NULL);
1074         mutex_enter(&mg->mg_lock);
1075         msp->ms_group = mg;
1076         msp->ms_weight = 0;
1077         avl_add(&mg->mg_metaslab_tree, msp);
1078         mutex_exit(&mg->mg_lock);
1079
1080         mutex_enter(&msp->ms_lock);
1081         metaslab_group_histogram_add(mg, msp);
1082         mutex_exit(&msp->ms_lock);
1083 }
1084
1085 static void
1086 metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
1087 {
1088         mutex_enter(&msp->ms_lock);
1089         metaslab_group_histogram_remove(mg, msp);
1090         mutex_exit(&msp->ms_lock);
1091
1092         mutex_enter(&mg->mg_lock);
1093         ASSERT(msp->ms_group == mg);
1094         avl_remove(&mg->mg_metaslab_tree, msp);
1095
1096         metaslab_class_t *mc = msp->ms_group->mg_class;
1097         multilist_sublist_t *mls =
1098             multilist_sublist_lock_obj(mc->mc_metaslab_txg_list, msp);
1099         if (multilist_link_active(&msp->ms_class_txg_node))
1100                 multilist_sublist_remove(mls, msp);
1101         multilist_sublist_unlock(mls);
1102
1103         msp->ms_group = NULL;
1104         mutex_exit(&mg->mg_lock);
1105 }
1106
1107 static void
1108 metaslab_group_sort_impl(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1109 {
1110         ASSERT(MUTEX_HELD(&msp->ms_lock));
1111         ASSERT(MUTEX_HELD(&mg->mg_lock));
1112         ASSERT(msp->ms_group == mg);
1113
1114         avl_remove(&mg->mg_metaslab_tree, msp);
1115         msp->ms_weight = weight;
1116         avl_add(&mg->mg_metaslab_tree, msp);
1117
1118 }
1119
1120 static void
1121 metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1122 {
1123         /*
1124          * Although in principle the weight can be any value, in
1125          * practice we do not use values in the range [1, 511].
1126          */
1127         ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
1128         ASSERT(MUTEX_HELD(&msp->ms_lock));
1129
1130         mutex_enter(&mg->mg_lock);
1131         metaslab_group_sort_impl(mg, msp, weight);
1132         mutex_exit(&mg->mg_lock);
1133 }
1134
1135 /*
1136  * Calculate the fragmentation for a given metaslab group. We can use
1137  * a simple average here since all metaslabs within the group must have
1138  * the same size. The return value will be a value between 0 and 100
1139  * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
1140  * group have a fragmentation metric.
1141  */
1142 uint64_t
1143 metaslab_group_fragmentation(metaslab_group_t *mg)
1144 {
1145         vdev_t *vd = mg->mg_vd;
1146         uint64_t fragmentation = 0;
1147         uint64_t valid_ms = 0;
1148
1149         for (int m = 0; m < vd->vdev_ms_count; m++) {
1150                 metaslab_t *msp = vd->vdev_ms[m];
1151
1152                 if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
1153                         continue;
1154                 if (msp->ms_group != mg)
1155                         continue;
1156
1157                 valid_ms++;
1158                 fragmentation += msp->ms_fragmentation;
1159         }
1160
1161         if (valid_ms <= mg->mg_vd->vdev_ms_count / 2)
1162                 return (ZFS_FRAG_INVALID);
1163
1164         fragmentation /= valid_ms;
1165         ASSERT3U(fragmentation, <=, 100);
1166         return (fragmentation);
1167 }
1168
1169 /*
1170  * Determine if a given metaslab group should skip allocations. A metaslab
1171  * group should avoid allocations if its free capacity is less than the
1172  * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
1173  * zfs_mg_fragmentation_threshold and there is at least one metaslab group
1174  * that can still handle allocations. If the allocation throttle is enabled
1175  * then we skip allocations to devices that have reached their maximum
1176  * allocation queue depth unless the selected metaslab group is the only
1177  * eligible group remaining.
1178  */
1179 static boolean_t
1180 metaslab_group_allocatable(metaslab_group_t *mg, metaslab_group_t *rotor,
1181     uint64_t psize, int allocator, int d)
1182 {
1183         spa_t *spa = mg->mg_vd->vdev_spa;
1184         metaslab_class_t *mc = mg->mg_class;
1185
1186         /*
1187          * We can only consider skipping this metaslab group if it's
1188          * in the normal metaslab class and there are other metaslab
1189          * groups to select from. Otherwise, we always consider it eligible
1190          * for allocations.
1191          */
1192         if ((mc != spa_normal_class(spa) &&
1193             mc != spa_special_class(spa) &&
1194             mc != spa_dedup_class(spa)) ||
1195             mc->mc_groups <= 1)
1196                 return (B_TRUE);
1197
1198         /*
1199          * If the metaslab group's mg_allocatable flag is set (see comments
1200          * in metaslab_group_alloc_update() for more information) and
1201          * the allocation throttle is disabled then allow allocations to this
1202          * device. However, if the allocation throttle is enabled then
1203          * check if we have reached our allocation limit (mg_alloc_queue_depth)
1204          * to determine if we should allow allocations to this metaslab group.
1205          * If all metaslab groups are no longer considered allocatable
1206          * (mc_alloc_groups == 0) or we're trying to allocate the smallest
1207          * gang block size then we allow allocations on this metaslab group
1208          * regardless of the mg_allocatable or throttle settings.
1209          */
1210         if (mg->mg_allocatable) {
1211                 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
1212                 int64_t qdepth;
1213                 uint64_t qmax = mga->mga_cur_max_alloc_queue_depth;
1214
1215                 if (!mc->mc_alloc_throttle_enabled)
1216                         return (B_TRUE);
1217
1218                 /*
1219                  * If this metaslab group does not have any free space, then
1220                  * there is no point in looking further.
1221                  */
1222                 if (mg->mg_no_free_space)
1223                         return (B_FALSE);
1224
1225                 /*
1226                  * Relax allocation throttling for ditto blocks.  Due to
1227                  * random imbalances in allocation it tends to push copies
1228                  * to one vdev, that looks a bit better at the moment.
1229                  */
1230                 qmax = qmax * (4 + d) / 4;
1231
1232                 qdepth = zfs_refcount_count(&mga->mga_alloc_queue_depth);
1233
1234                 /*
1235                  * If this metaslab group is below its qmax or it's
1236                  * the only allocatable metasable group, then attempt
1237                  * to allocate from it.
1238                  */
1239                 if (qdepth < qmax || mc->mc_alloc_groups == 1)
1240                         return (B_TRUE);
1241                 ASSERT3U(mc->mc_alloc_groups, >, 1);
1242
1243                 /*
1244                  * Since this metaslab group is at or over its qmax, we
1245                  * need to determine if there are metaslab groups after this
1246                  * one that might be able to handle this allocation. This is
1247                  * racy since we can't hold the locks for all metaslab
1248                  * groups at the same time when we make this check.
1249                  */
1250                 for (metaslab_group_t *mgp = mg->mg_next;
1251                     mgp != rotor; mgp = mgp->mg_next) {
1252                         metaslab_group_allocator_t *mgap =
1253                             &mgp->mg_allocator[allocator];
1254                         qmax = mgap->mga_cur_max_alloc_queue_depth;
1255                         qmax = qmax * (4 + d) / 4;
1256                         qdepth =
1257                             zfs_refcount_count(&mgap->mga_alloc_queue_depth);
1258
1259                         /*
1260                          * If there is another metaslab group that
1261                          * might be able to handle the allocation, then
1262                          * we return false so that we skip this group.
1263                          */
1264                         if (qdepth < qmax && !mgp->mg_no_free_space)
1265                                 return (B_FALSE);
1266                 }
1267
1268                 /*
1269                  * We didn't find another group to handle the allocation
1270                  * so we can't skip this metaslab group even though
1271                  * we are at or over our qmax.
1272                  */
1273                 return (B_TRUE);
1274
1275         } else if (mc->mc_alloc_groups == 0 || psize == SPA_MINBLOCKSIZE) {
1276                 return (B_TRUE);
1277         }
1278         return (B_FALSE);
1279 }
1280
1281 /*
1282  * ==========================================================================
1283  * Range tree callbacks
1284  * ==========================================================================
1285  */
1286
1287 /*
1288  * Comparison function for the private size-ordered tree using 32-bit
1289  * ranges. Tree is sorted by size, larger sizes at the end of the tree.
1290  */
1291 static int
1292 metaslab_rangesize32_compare(const void *x1, const void *x2)
1293 {
1294         const range_seg32_t *r1 = x1;
1295         const range_seg32_t *r2 = x2;
1296
1297         uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1298         uint64_t rs_size2 = r2->rs_end - r2->rs_start;
1299
1300         int cmp = TREE_CMP(rs_size1, rs_size2);
1301         if (likely(cmp))
1302                 return (cmp);
1303
1304         return (TREE_CMP(r1->rs_start, r2->rs_start));
1305 }
1306
1307 /*
1308  * Comparison function for the private size-ordered tree using 64-bit
1309  * ranges. Tree is sorted by size, larger sizes at the end of the tree.
1310  */
1311 static int
1312 metaslab_rangesize64_compare(const void *x1, const void *x2)
1313 {
1314         const range_seg64_t *r1 = x1;
1315         const range_seg64_t *r2 = x2;
1316
1317         uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1318         uint64_t rs_size2 = r2->rs_end - r2->rs_start;
1319
1320         int cmp = TREE_CMP(rs_size1, rs_size2);
1321         if (likely(cmp))
1322                 return (cmp);
1323
1324         return (TREE_CMP(r1->rs_start, r2->rs_start));
1325 }
1326 typedef struct metaslab_rt_arg {
1327         zfs_btree_t *mra_bt;
1328         uint32_t mra_floor_shift;
1329 } metaslab_rt_arg_t;
1330
1331 struct mssa_arg {
1332         range_tree_t *rt;
1333         metaslab_rt_arg_t *mra;
1334 };
1335
1336 static void
1337 metaslab_size_sorted_add(void *arg, uint64_t start, uint64_t size)
1338 {
1339         struct mssa_arg *mssap = arg;
1340         range_tree_t *rt = mssap->rt;
1341         metaslab_rt_arg_t *mrap = mssap->mra;
1342         range_seg_max_t seg = {0};
1343         rs_set_start(&seg, rt, start);
1344         rs_set_end(&seg, rt, start + size);
1345         metaslab_rt_add(rt, &seg, mrap);
1346 }
1347
1348 static void
1349 metaslab_size_tree_full_load(range_tree_t *rt)
1350 {
1351         metaslab_rt_arg_t *mrap = rt->rt_arg;
1352 #ifdef _METASLAB_TRACING
1353         METASLABSTAT_BUMP(metaslabstat_reload_tree);
1354 #endif
1355         ASSERT0(zfs_btree_numnodes(mrap->mra_bt));
1356         mrap->mra_floor_shift = 0;
1357         struct mssa_arg arg = {0};
1358         arg.rt = rt;
1359         arg.mra = mrap;
1360         range_tree_walk(rt, metaslab_size_sorted_add, &arg);
1361 }
1362
1363 /*
1364  * Create any block allocator specific components. The current allocators
1365  * rely on using both a size-ordered range_tree_t and an array of uint64_t's.
1366  */
1367 /* ARGSUSED */
1368 static void
1369 metaslab_rt_create(range_tree_t *rt, void *arg)
1370 {
1371         metaslab_rt_arg_t *mrap = arg;
1372         zfs_btree_t *size_tree = mrap->mra_bt;
1373
1374         size_t size;
1375         int (*compare) (const void *, const void *);
1376         switch (rt->rt_type) {
1377         case RANGE_SEG32:
1378                 size = sizeof (range_seg32_t);
1379                 compare = metaslab_rangesize32_compare;
1380                 break;
1381         case RANGE_SEG64:
1382                 size = sizeof (range_seg64_t);
1383                 compare = metaslab_rangesize64_compare;
1384                 break;
1385         default:
1386                 panic("Invalid range seg type %d", rt->rt_type);
1387         }
1388         zfs_btree_create(size_tree, compare, size);
1389         mrap->mra_floor_shift = metaslab_by_size_min_shift;
1390 }
1391
1392 /* ARGSUSED */
1393 static void
1394 metaslab_rt_destroy(range_tree_t *rt, void *arg)
1395 {
1396         metaslab_rt_arg_t *mrap = arg;
1397         zfs_btree_t *size_tree = mrap->mra_bt;
1398
1399         zfs_btree_destroy(size_tree);
1400         kmem_free(mrap, sizeof (*mrap));
1401 }
1402
1403 /* ARGSUSED */
1404 static void
1405 metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg)
1406 {
1407         metaslab_rt_arg_t *mrap = arg;
1408         zfs_btree_t *size_tree = mrap->mra_bt;
1409
1410         if (rs_get_end(rs, rt) - rs_get_start(rs, rt) <
1411             (1 << mrap->mra_floor_shift))
1412                 return;
1413
1414         zfs_btree_add(size_tree, rs);
1415 }
1416
1417 /* ARGSUSED */
1418 static void
1419 metaslab_rt_remove(range_tree_t *rt, range_seg_t *rs, void *arg)
1420 {
1421         metaslab_rt_arg_t *mrap = arg;
1422         zfs_btree_t *size_tree = mrap->mra_bt;
1423
1424         if (rs_get_end(rs, rt) - rs_get_start(rs, rt) < (1 <<
1425             mrap->mra_floor_shift))
1426                 return;
1427
1428         zfs_btree_remove(size_tree, rs);
1429 }
1430
1431 /* ARGSUSED */
1432 static void
1433 metaslab_rt_vacate(range_tree_t *rt, void *arg)
1434 {
1435         metaslab_rt_arg_t *mrap = arg;
1436         zfs_btree_t *size_tree = mrap->mra_bt;
1437         zfs_btree_clear(size_tree);
1438         zfs_btree_destroy(size_tree);
1439
1440         metaslab_rt_create(rt, arg);
1441 }
1442
1443 static range_tree_ops_t metaslab_rt_ops = {
1444         .rtop_create = metaslab_rt_create,
1445         .rtop_destroy = metaslab_rt_destroy,
1446         .rtop_add = metaslab_rt_add,
1447         .rtop_remove = metaslab_rt_remove,
1448         .rtop_vacate = metaslab_rt_vacate
1449 };
1450
1451 /*
1452  * ==========================================================================
1453  * Common allocator routines
1454  * ==========================================================================
1455  */
1456
1457 /*
1458  * Return the maximum contiguous segment within the metaslab.
1459  */
1460 uint64_t
1461 metaslab_largest_allocatable(metaslab_t *msp)
1462 {
1463         zfs_btree_t *t = &msp->ms_allocatable_by_size;
1464         range_seg_t *rs;
1465
1466         if (t == NULL)
1467                 return (0);
1468         if (zfs_btree_numnodes(t) == 0)
1469                 metaslab_size_tree_full_load(msp->ms_allocatable);
1470
1471         rs = zfs_btree_last(t, NULL);
1472         if (rs == NULL)
1473                 return (0);
1474
1475         return (rs_get_end(rs, msp->ms_allocatable) - rs_get_start(rs,
1476             msp->ms_allocatable));
1477 }
1478
1479 /*
1480  * Return the maximum contiguous segment within the unflushed frees of this
1481  * metaslab.
1482  */
1483 static uint64_t
1484 metaslab_largest_unflushed_free(metaslab_t *msp)
1485 {
1486         ASSERT(MUTEX_HELD(&msp->ms_lock));
1487
1488         if (msp->ms_unflushed_frees == NULL)
1489                 return (0);
1490
1491         if (zfs_btree_numnodes(&msp->ms_unflushed_frees_by_size) == 0)
1492                 metaslab_size_tree_full_load(msp->ms_unflushed_frees);
1493         range_seg_t *rs = zfs_btree_last(&msp->ms_unflushed_frees_by_size,
1494             NULL);
1495         if (rs == NULL)
1496                 return (0);
1497
1498         /*
1499          * When a range is freed from the metaslab, that range is added to
1500          * both the unflushed frees and the deferred frees. While the block
1501          * will eventually be usable, if the metaslab were loaded the range
1502          * would not be added to the ms_allocatable tree until TXG_DEFER_SIZE
1503          * txgs had passed.  As a result, when attempting to estimate an upper
1504          * bound for the largest currently-usable free segment in the
1505          * metaslab, we need to not consider any ranges currently in the defer
1506          * trees. This algorithm approximates the largest available chunk in
1507          * the largest range in the unflushed_frees tree by taking the first
1508          * chunk.  While this may be a poor estimate, it should only remain so
1509          * briefly and should eventually self-correct as frees are no longer
1510          * deferred. Similar logic applies to the ms_freed tree. See
1511          * metaslab_load() for more details.
1512          *
1513          * There are two primary sources of inaccuracy in this estimate. Both
1514          * are tolerated for performance reasons. The first source is that we
1515          * only check the largest segment for overlaps. Smaller segments may
1516          * have more favorable overlaps with the other trees, resulting in
1517          * larger usable chunks.  Second, we only look at the first chunk in
1518          * the largest segment; there may be other usable chunks in the
1519          * largest segment, but we ignore them.
1520          */
1521         uint64_t rstart = rs_get_start(rs, msp->ms_unflushed_frees);
1522         uint64_t rsize = rs_get_end(rs, msp->ms_unflushed_frees) - rstart;
1523         for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1524                 uint64_t start = 0;
1525                 uint64_t size = 0;
1526                 boolean_t found = range_tree_find_in(msp->ms_defer[t], rstart,
1527                     rsize, &start, &size);
1528                 if (found) {
1529                         if (rstart == start)
1530                                 return (0);
1531                         rsize = start - rstart;
1532                 }
1533         }
1534
1535         uint64_t start = 0;
1536         uint64_t size = 0;
1537         boolean_t found = range_tree_find_in(msp->ms_freed, rstart,
1538             rsize, &start, &size);
1539         if (found)
1540                 rsize = start - rstart;
1541
1542         return (rsize);
1543 }
1544
1545 static range_seg_t *
1546 metaslab_block_find(zfs_btree_t *t, range_tree_t *rt, uint64_t start,
1547     uint64_t size, zfs_btree_index_t *where)
1548 {
1549         range_seg_t *rs;
1550         range_seg_max_t rsearch;
1551
1552         rs_set_start(&rsearch, rt, start);
1553         rs_set_end(&rsearch, rt, start + size);
1554
1555         rs = zfs_btree_find(t, &rsearch, where);
1556         if (rs == NULL) {
1557                 rs = zfs_btree_next(t, where, where);
1558         }
1559
1560         return (rs);
1561 }
1562
1563 #if defined(WITH_DF_BLOCK_ALLOCATOR) || \
1564     defined(WITH_CF_BLOCK_ALLOCATOR)
1565 /*
1566  * This is a helper function that can be used by the allocator to find a
1567  * suitable block to allocate. This will search the specified B-tree looking
1568  * for a block that matches the specified criteria.
1569  */
1570 static uint64_t
1571 metaslab_block_picker(range_tree_t *rt, uint64_t *cursor, uint64_t size,
1572     uint64_t max_search)
1573 {
1574         if (*cursor == 0)
1575                 *cursor = rt->rt_start;
1576         zfs_btree_t *bt = &rt->rt_root;
1577         zfs_btree_index_t where;
1578         range_seg_t *rs = metaslab_block_find(bt, rt, *cursor, size, &where);
1579         uint64_t first_found;
1580         int count_searched = 0;
1581
1582         if (rs != NULL)
1583                 first_found = rs_get_start(rs, rt);
1584
1585         while (rs != NULL && (rs_get_start(rs, rt) - first_found <=
1586             max_search || count_searched < metaslab_min_search_count)) {
1587                 uint64_t offset = rs_get_start(rs, rt);
1588                 if (offset + size <= rs_get_end(rs, rt)) {
1589                         *cursor = offset + size;
1590                         return (offset);
1591                 }
1592                 rs = zfs_btree_next(bt, &where, &where);
1593                 count_searched++;
1594         }
1595
1596         *cursor = 0;
1597         return (-1ULL);
1598 }
1599 #endif /* WITH_DF/CF_BLOCK_ALLOCATOR */
1600
1601 #if defined(WITH_DF_BLOCK_ALLOCATOR)
1602 /*
1603  * ==========================================================================
1604  * Dynamic Fit (df) block allocator
1605  *
1606  * Search for a free chunk of at least this size, starting from the last
1607  * offset (for this alignment of block) looking for up to
1608  * metaslab_df_max_search bytes (16MB).  If a large enough free chunk is not
1609  * found within 16MB, then return a free chunk of exactly the requested size (or
1610  * larger).
1611  *
1612  * If it seems like searching from the last offset will be unproductive, skip
1613  * that and just return a free chunk of exactly the requested size (or larger).
1614  * This is based on metaslab_df_alloc_threshold and metaslab_df_free_pct.  This
1615  * mechanism is probably not very useful and may be removed in the future.
1616  *
1617  * The behavior when not searching can be changed to return the largest free
1618  * chunk, instead of a free chunk of exactly the requested size, by setting
1619  * metaslab_df_use_largest_segment.
1620  * ==========================================================================
1621  */
1622 static uint64_t
1623 metaslab_df_alloc(metaslab_t *msp, uint64_t size)
1624 {
1625         /*
1626          * Find the largest power of 2 block size that evenly divides the
1627          * requested size. This is used to try to allocate blocks with similar
1628          * alignment from the same area of the metaslab (i.e. same cursor
1629          * bucket) but it does not guarantee that other allocations sizes
1630          * may exist in the same region.
1631          */
1632         uint64_t align = size & -size;
1633         uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
1634         range_tree_t *rt = msp->ms_allocatable;
1635         int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1636         uint64_t offset;
1637
1638         ASSERT(MUTEX_HELD(&msp->ms_lock));
1639
1640         /*
1641          * If we're running low on space, find a segment based on size,
1642          * rather than iterating based on offset.
1643          */
1644         if (metaslab_largest_allocatable(msp) < metaslab_df_alloc_threshold ||
1645             free_pct < metaslab_df_free_pct) {
1646                 offset = -1;
1647         } else {
1648                 offset = metaslab_block_picker(rt,
1649                     cursor, size, metaslab_df_max_search);
1650         }
1651
1652         if (offset == -1) {
1653                 range_seg_t *rs;
1654                 if (zfs_btree_numnodes(&msp->ms_allocatable_by_size) == 0)
1655                         metaslab_size_tree_full_load(msp->ms_allocatable);
1656                 if (metaslab_df_use_largest_segment) {
1657                         /* use largest free segment */
1658                         rs = zfs_btree_last(&msp->ms_allocatable_by_size, NULL);
1659                 } else {
1660                         zfs_btree_index_t where;
1661                         /* use segment of this size, or next largest */
1662 #ifdef _METASLAB_TRACING
1663                         metaslab_rt_arg_t *mrap = msp->ms_allocatable->rt_arg;
1664                         if (size < (1 << mrap->mra_floor_shift)) {
1665                                 METASLABSTAT_BUMP(
1666                                     metaslabstat_df_find_under_floor);
1667                         }
1668 #endif
1669                         rs = metaslab_block_find(&msp->ms_allocatable_by_size,
1670                             rt, msp->ms_start, size, &where);
1671                 }
1672                 if (rs != NULL && rs_get_start(rs, rt) + size <= rs_get_end(rs,
1673                     rt)) {
1674                         offset = rs_get_start(rs, rt);
1675                         *cursor = offset + size;
1676                 }
1677         }
1678
1679         return (offset);
1680 }
1681
1682 static metaslab_ops_t metaslab_df_ops = {
1683         metaslab_df_alloc
1684 };
1685
1686 metaslab_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
1687 #endif /* WITH_DF_BLOCK_ALLOCATOR */
1688
1689 #if defined(WITH_CF_BLOCK_ALLOCATOR)
1690 /*
1691  * ==========================================================================
1692  * Cursor fit block allocator -
1693  * Select the largest region in the metaslab, set the cursor to the beginning
1694  * of the range and the cursor_end to the end of the range. As allocations
1695  * are made advance the cursor. Continue allocating from the cursor until
1696  * the range is exhausted and then find a new range.
1697  * ==========================================================================
1698  */
1699 static uint64_t
1700 metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
1701 {
1702         range_tree_t *rt = msp->ms_allocatable;
1703         zfs_btree_t *t = &msp->ms_allocatable_by_size;
1704         uint64_t *cursor = &msp->ms_lbas[0];
1705         uint64_t *cursor_end = &msp->ms_lbas[1];
1706         uint64_t offset = 0;
1707
1708         ASSERT(MUTEX_HELD(&msp->ms_lock));
1709
1710         ASSERT3U(*cursor_end, >=, *cursor);
1711
1712         if ((*cursor + size) > *cursor_end) {
1713                 range_seg_t *rs;
1714
1715                 if (zfs_btree_numnodes(t) == 0)
1716                         metaslab_size_tree_full_load(msp->ms_allocatable);
1717                 rs = zfs_btree_last(t, NULL);
1718                 if (rs == NULL || (rs_get_end(rs, rt) - rs_get_start(rs, rt)) <
1719                     size)
1720                         return (-1ULL);
1721
1722                 *cursor = rs_get_start(rs, rt);
1723                 *cursor_end = rs_get_end(rs, rt);
1724         }
1725
1726         offset = *cursor;
1727         *cursor += size;
1728
1729         return (offset);
1730 }
1731
1732 static metaslab_ops_t metaslab_cf_ops = {
1733         metaslab_cf_alloc
1734 };
1735
1736 metaslab_ops_t *zfs_metaslab_ops = &metaslab_cf_ops;
1737 #endif /* WITH_CF_BLOCK_ALLOCATOR */
1738
1739 #if defined(WITH_NDF_BLOCK_ALLOCATOR)
1740 /*
1741  * ==========================================================================
1742  * New dynamic fit allocator -
1743  * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1744  * contiguous blocks. If no region is found then just use the largest segment
1745  * that remains.
1746  * ==========================================================================
1747  */
1748
1749 /*
1750  * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1751  * to request from the allocator.
1752  */
1753 uint64_t metaslab_ndf_clump_shift = 4;
1754
1755 static uint64_t
1756 metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
1757 {
1758         zfs_btree_t *t = &msp->ms_allocatable->rt_root;
1759         range_tree_t *rt = msp->ms_allocatable;
1760         zfs_btree_index_t where;
1761         range_seg_t *rs;
1762         range_seg_max_t rsearch;
1763         uint64_t hbit = highbit64(size);
1764         uint64_t *cursor = &msp->ms_lbas[hbit - 1];
1765         uint64_t max_size = metaslab_largest_allocatable(msp);
1766
1767         ASSERT(MUTEX_HELD(&msp->ms_lock));
1768
1769         if (max_size < size)
1770                 return (-1ULL);
1771
1772         rs_set_start(&rsearch, rt, *cursor);
1773         rs_set_end(&rsearch, rt, *cursor + size);
1774
1775         rs = zfs_btree_find(t, &rsearch, &where);
1776         if (rs == NULL || (rs_get_end(rs, rt) - rs_get_start(rs, rt)) < size) {
1777                 t = &msp->ms_allocatable_by_size;
1778
1779                 rs_set_start(&rsearch, rt, 0);
1780                 rs_set_end(&rsearch, rt, MIN(max_size, 1ULL << (hbit +
1781                     metaslab_ndf_clump_shift)));
1782
1783                 rs = zfs_btree_find(t, &rsearch, &where);
1784                 if (rs == NULL)
1785                         rs = zfs_btree_next(t, &where, &where);
1786                 ASSERT(rs != NULL);
1787         }
1788
1789         if ((rs_get_end(rs, rt) - rs_get_start(rs, rt)) >= size) {
1790                 *cursor = rs_get_start(rs, rt) + size;
1791                 return (rs_get_start(rs, rt));
1792         }
1793         return (-1ULL);
1794 }
1795
1796 static metaslab_ops_t metaslab_ndf_ops = {
1797         metaslab_ndf_alloc
1798 };
1799
1800 metaslab_ops_t *zfs_metaslab_ops = &metaslab_ndf_ops;
1801 #endif /* WITH_NDF_BLOCK_ALLOCATOR */
1802
1803
1804 /*
1805  * ==========================================================================
1806  * Metaslabs
1807  * ==========================================================================
1808  */
1809
1810 /*
1811  * Wait for any in-progress metaslab loads to complete.
1812  */
1813 static void
1814 metaslab_load_wait(metaslab_t *msp)
1815 {
1816         ASSERT(MUTEX_HELD(&msp->ms_lock));
1817
1818         while (msp->ms_loading) {
1819                 ASSERT(!msp->ms_loaded);
1820                 cv_wait(&msp->ms_load_cv, &msp->ms_lock);
1821         }
1822 }
1823
1824 /*
1825  * Wait for any in-progress flushing to complete.
1826  */
1827 static void
1828 metaslab_flush_wait(metaslab_t *msp)
1829 {
1830         ASSERT(MUTEX_HELD(&msp->ms_lock));
1831
1832         while (msp->ms_flushing)
1833                 cv_wait(&msp->ms_flush_cv, &msp->ms_lock);
1834 }
1835
1836 static unsigned int
1837 metaslab_idx_func(multilist_t *ml, void *arg)
1838 {
1839         metaslab_t *msp = arg;
1840         return (msp->ms_id % multilist_get_num_sublists(ml));
1841 }
1842
1843 uint64_t
1844 metaslab_allocated_space(metaslab_t *msp)
1845 {
1846         return (msp->ms_allocated_space);
1847 }
1848
1849 /*
1850  * Verify that the space accounting on disk matches the in-core range_trees.
1851  */
1852 static void
1853 metaslab_verify_space(metaslab_t *msp, uint64_t txg)
1854 {
1855         spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1856         uint64_t allocating = 0;
1857         uint64_t sm_free_space, msp_free_space;
1858
1859         ASSERT(MUTEX_HELD(&msp->ms_lock));
1860         ASSERT(!msp->ms_condensing);
1861
1862         if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
1863                 return;
1864
1865         /*
1866          * We can only verify the metaslab space when we're called
1867          * from syncing context with a loaded metaslab that has an
1868          * allocated space map. Calling this in non-syncing context
1869          * does not provide a consistent view of the metaslab since
1870          * we're performing allocations in the future.
1871          */
1872         if (txg != spa_syncing_txg(spa) || msp->ms_sm == NULL ||
1873             !msp->ms_loaded)
1874                 return;
1875
1876         /*
1877          * Even though the smp_alloc field can get negative,
1878          * when it comes to a metaslab's space map, that should
1879          * never be the case.
1880          */
1881         ASSERT3S(space_map_allocated(msp->ms_sm), >=, 0);
1882
1883         ASSERT3U(space_map_allocated(msp->ms_sm), >=,
1884             range_tree_space(msp->ms_unflushed_frees));
1885
1886         ASSERT3U(metaslab_allocated_space(msp), ==,
1887             space_map_allocated(msp->ms_sm) +
1888             range_tree_space(msp->ms_unflushed_allocs) -
1889             range_tree_space(msp->ms_unflushed_frees));
1890
1891         sm_free_space = msp->ms_size - metaslab_allocated_space(msp);
1892
1893         /*
1894          * Account for future allocations since we would have
1895          * already deducted that space from the ms_allocatable.
1896          */
1897         for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
1898                 allocating +=
1899                     range_tree_space(msp->ms_allocating[(txg + t) & TXG_MASK]);
1900         }
1901         ASSERT3U(allocating + msp->ms_allocated_this_txg, ==,
1902             msp->ms_allocating_total);
1903
1904         ASSERT3U(msp->ms_deferspace, ==,
1905             range_tree_space(msp->ms_defer[0]) +
1906             range_tree_space(msp->ms_defer[1]));
1907
1908         msp_free_space = range_tree_space(msp->ms_allocatable) + allocating +
1909             msp->ms_deferspace + range_tree_space(msp->ms_freed);
1910
1911         VERIFY3U(sm_free_space, ==, msp_free_space);
1912 }
1913
1914 static void
1915 metaslab_aux_histograms_clear(metaslab_t *msp)
1916 {
1917         /*
1918          * Auxiliary histograms are only cleared when resetting them,
1919          * which can only happen while the metaslab is loaded.
1920          */
1921         ASSERT(msp->ms_loaded);
1922
1923         bzero(msp->ms_synchist, sizeof (msp->ms_synchist));
1924         for (int t = 0; t < TXG_DEFER_SIZE; t++)
1925                 bzero(msp->ms_deferhist[t], sizeof (msp->ms_deferhist[t]));
1926 }
1927
1928 static void
1929 metaslab_aux_histogram_add(uint64_t *histogram, uint64_t shift,
1930     range_tree_t *rt)
1931 {
1932         /*
1933          * This is modeled after space_map_histogram_add(), so refer to that
1934          * function for implementation details. We want this to work like
1935          * the space map histogram, and not the range tree histogram, as we
1936          * are essentially constructing a delta that will be later subtracted
1937          * from the space map histogram.
1938          */
1939         int idx = 0;
1940         for (int i = shift; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
1941                 ASSERT3U(i, >=, idx + shift);
1942                 histogram[idx] += rt->rt_histogram[i] << (i - idx - shift);
1943
1944                 if (idx < SPACE_MAP_HISTOGRAM_SIZE - 1) {
1945                         ASSERT3U(idx + shift, ==, i);
1946                         idx++;
1947                         ASSERT3U(idx, <, SPACE_MAP_HISTOGRAM_SIZE);
1948                 }
1949         }
1950 }
1951
1952 /*
1953  * Called at every sync pass that the metaslab gets synced.
1954  *
1955  * The reason is that we want our auxiliary histograms to be updated
1956  * wherever the metaslab's space map histogram is updated. This way
1957  * we stay consistent on which parts of the metaslab space map's
1958  * histogram are currently not available for allocations (e.g because
1959  * they are in the defer, freed, and freeing trees).
1960  */
1961 static void
1962 metaslab_aux_histograms_update(metaslab_t *msp)
1963 {
1964         space_map_t *sm = msp->ms_sm;
1965         ASSERT(sm != NULL);
1966
1967         /*
1968          * This is similar to the metaslab's space map histogram updates
1969          * that take place in metaslab_sync(). The only difference is that
1970          * we only care about segments that haven't made it into the
1971          * ms_allocatable tree yet.
1972          */
1973         if (msp->ms_loaded) {
1974                 metaslab_aux_histograms_clear(msp);
1975
1976                 metaslab_aux_histogram_add(msp->ms_synchist,
1977                     sm->sm_shift, msp->ms_freed);
1978
1979                 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1980                         metaslab_aux_histogram_add(msp->ms_deferhist[t],
1981                             sm->sm_shift, msp->ms_defer[t]);
1982                 }
1983         }
1984
1985         metaslab_aux_histogram_add(msp->ms_synchist,
1986             sm->sm_shift, msp->ms_freeing);
1987 }
1988
1989 /*
1990  * Called every time we are done syncing (writing to) the metaslab,
1991  * i.e. at the end of each sync pass.
1992  * [see the comment in metaslab_impl.h for ms_synchist, ms_deferhist]
1993  */
1994 static void
1995 metaslab_aux_histograms_update_done(metaslab_t *msp, boolean_t defer_allowed)
1996 {
1997         spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1998         space_map_t *sm = msp->ms_sm;
1999
2000         if (sm == NULL) {
2001                 /*
2002                  * We came here from metaslab_init() when creating/opening a
2003                  * pool, looking at a metaslab that hasn't had any allocations
2004                  * yet.
2005                  */
2006                 return;
2007         }
2008
2009         /*
2010          * This is similar to the actions that we take for the ms_freed
2011          * and ms_defer trees in metaslab_sync_done().
2012          */
2013         uint64_t hist_index = spa_syncing_txg(spa) % TXG_DEFER_SIZE;
2014         if (defer_allowed) {
2015                 bcopy(msp->ms_synchist, msp->ms_deferhist[hist_index],
2016                     sizeof (msp->ms_synchist));
2017         } else {
2018                 bzero(msp->ms_deferhist[hist_index],
2019                     sizeof (msp->ms_deferhist[hist_index]));
2020         }
2021         bzero(msp->ms_synchist, sizeof (msp->ms_synchist));
2022 }
2023
2024 /*
2025  * Ensure that the metaslab's weight and fragmentation are consistent
2026  * with the contents of the histogram (either the range tree's histogram
2027  * or the space map's depending whether the metaslab is loaded).
2028  */
2029 static void
2030 metaslab_verify_weight_and_frag(metaslab_t *msp)
2031 {
2032         ASSERT(MUTEX_HELD(&msp->ms_lock));
2033
2034         if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
2035                 return;
2036
2037         /*
2038          * We can end up here from vdev_remove_complete(), in which case we
2039          * cannot do these assertions because we hold spa config locks and
2040          * thus we are not allowed to read from the DMU.
2041          *
2042          * We check if the metaslab group has been removed and if that's
2043          * the case we return immediately as that would mean that we are
2044          * here from the aforementioned code path.
2045          */
2046         if (msp->ms_group == NULL)
2047                 return;
2048
2049         /*
2050          * Devices being removed always return a weight of 0 and leave
2051          * fragmentation and ms_max_size as is - there is nothing for
2052          * us to verify here.
2053          */
2054         vdev_t *vd = msp->ms_group->mg_vd;
2055         if (vd->vdev_removing)
2056                 return;
2057
2058         /*
2059          * If the metaslab is dirty it probably means that we've done
2060          * some allocations or frees that have changed our histograms
2061          * and thus the weight.
2062          */
2063         for (int t = 0; t < TXG_SIZE; t++) {
2064                 if (txg_list_member(&vd->vdev_ms_list, msp, t))
2065                         return;
2066         }
2067
2068         /*
2069          * This verification checks that our in-memory state is consistent
2070          * with what's on disk. If the pool is read-only then there aren't
2071          * any changes and we just have the initially-loaded state.
2072          */
2073         if (!spa_writeable(msp->ms_group->mg_vd->vdev_spa))
2074                 return;
2075
2076         /* some extra verification for in-core tree if you can */
2077         if (msp->ms_loaded) {
2078                 range_tree_stat_verify(msp->ms_allocatable);
2079                 VERIFY(space_map_histogram_verify(msp->ms_sm,
2080                     msp->ms_allocatable));
2081         }
2082
2083         uint64_t weight = msp->ms_weight;
2084         uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
2085         boolean_t space_based = WEIGHT_IS_SPACEBASED(msp->ms_weight);
2086         uint64_t frag = msp->ms_fragmentation;
2087         uint64_t max_segsize = msp->ms_max_size;
2088
2089         msp->ms_weight = 0;
2090         msp->ms_fragmentation = 0;
2091
2092         /*
2093          * This function is used for verification purposes and thus should
2094          * not introduce any side-effects/mutations on the system's state.
2095          *
2096          * Regardless of whether metaslab_weight() thinks this metaslab
2097          * should be active or not, we want to ensure that the actual weight
2098          * (and therefore the value of ms_weight) would be the same if it
2099          * was to be recalculated at this point.
2100          *
2101          * In addition we set the nodirty flag so metaslab_weight() does
2102          * not dirty the metaslab for future TXGs (e.g. when trying to
2103          * force condensing to upgrade the metaslab spacemaps).
2104          */
2105         msp->ms_weight = metaslab_weight(msp, B_TRUE) | was_active;
2106
2107         VERIFY3U(max_segsize, ==, msp->ms_max_size);
2108
2109         /*
2110          * If the weight type changed then there is no point in doing
2111          * verification. Revert fields to their original values.
2112          */
2113         if ((space_based && !WEIGHT_IS_SPACEBASED(msp->ms_weight)) ||
2114             (!space_based && WEIGHT_IS_SPACEBASED(msp->ms_weight))) {
2115                 msp->ms_fragmentation = frag;
2116                 msp->ms_weight = weight;
2117                 return;
2118         }
2119
2120         VERIFY3U(msp->ms_fragmentation, ==, frag);
2121         VERIFY3U(msp->ms_weight, ==, weight);
2122 }
2123
2124 /*
2125  * If we're over the zfs_metaslab_mem_limit, select the loaded metaslab from
2126  * this class that was used longest ago, and attempt to unload it.  We don't
2127  * want to spend too much time in this loop to prevent performance
2128  * degradation, and we expect that most of the time this operation will
2129  * succeed. Between that and the normal unloading processing during txg sync,
2130  * we expect this to keep the metaslab memory usage under control.
2131  */
2132 static void
2133 metaslab_potentially_evict(metaslab_class_t *mc)
2134 {
2135 #ifdef _KERNEL
2136         uint64_t allmem = arc_all_memory();
2137         uint64_t inuse = spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2138         uint64_t size = spl_kmem_cache_entry_size(zfs_btree_leaf_cache);
2139         int tries = 0;
2140         for (; allmem * zfs_metaslab_mem_limit / 100 < inuse * size &&
2141             tries < multilist_get_num_sublists(mc->mc_metaslab_txg_list) * 2;
2142             tries++) {
2143                 unsigned int idx = multilist_get_random_index(
2144                     mc->mc_metaslab_txg_list);
2145                 multilist_sublist_t *mls =
2146                     multilist_sublist_lock(mc->mc_metaslab_txg_list, idx);
2147                 metaslab_t *msp = multilist_sublist_head(mls);
2148                 multilist_sublist_unlock(mls);
2149                 while (msp != NULL && allmem * zfs_metaslab_mem_limit / 100 <
2150                     inuse * size) {
2151                         VERIFY3P(mls, ==, multilist_sublist_lock(
2152                             mc->mc_metaslab_txg_list, idx));
2153                         ASSERT3U(idx, ==,
2154                             metaslab_idx_func(mc->mc_metaslab_txg_list, msp));
2155
2156                         if (!multilist_link_active(&msp->ms_class_txg_node)) {
2157                                 multilist_sublist_unlock(mls);
2158                                 break;
2159                         }
2160                         metaslab_t *next_msp = multilist_sublist_next(mls, msp);
2161                         multilist_sublist_unlock(mls);
2162                         /*
2163                          * If the metaslab is currently loading there are two
2164                          * cases. If it's the metaslab we're evicting, we
2165                          * can't continue on or we'll panic when we attempt to
2166                          * recursively lock the mutex. If it's another
2167                          * metaslab that's loading, it can be safely skipped,
2168                          * since we know it's very new and therefore not a
2169                          * good eviction candidate. We check later once the
2170                          * lock is held that the metaslab is fully loaded
2171                          * before actually unloading it.
2172                          */
2173                         if (msp->ms_loading) {
2174                                 msp = next_msp;
2175                                 inuse =
2176                                     spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2177                                 continue;
2178                         }
2179                         /*
2180                          * We can't unload metaslabs with no spacemap because
2181                          * they're not ready to be unloaded yet. We can't
2182                          * unload metaslabs with outstanding allocations
2183                          * because doing so could cause the metaslab's weight
2184                          * to decrease while it's unloaded, which violates an
2185                          * invariant that we use to prevent unnecessary
2186                          * loading. We also don't unload metaslabs that are
2187                          * currently active because they are high-weight
2188                          * metaslabs that are likely to be used in the near
2189                          * future.
2190                          */
2191                         mutex_enter(&msp->ms_lock);
2192                         if (msp->ms_allocator == -1 && msp->ms_sm != NULL &&
2193                             msp->ms_allocating_total == 0) {
2194                                 metaslab_unload(msp);
2195                         }
2196                         mutex_exit(&msp->ms_lock);
2197                         msp = next_msp;
2198                         inuse = spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2199                 }
2200         }
2201 #endif
2202 }
2203
2204 static int
2205 metaslab_load_impl(metaslab_t *msp)
2206 {
2207         int error = 0;
2208
2209         ASSERT(MUTEX_HELD(&msp->ms_lock));
2210         ASSERT(msp->ms_loading);
2211         ASSERT(!msp->ms_condensing);
2212
2213         /*
2214          * We temporarily drop the lock to unblock other operations while we
2215          * are reading the space map. Therefore, metaslab_sync() and
2216          * metaslab_sync_done() can run at the same time as we do.
2217          *
2218          * If we are using the log space maps, metaslab_sync() can't write to
2219          * the metaslab's space map while we are loading as we only write to
2220          * it when we are flushing the metaslab, and that can't happen while
2221          * we are loading it.
2222          *
2223          * If we are not using log space maps though, metaslab_sync() can
2224          * append to the space map while we are loading. Therefore we load
2225          * only entries that existed when we started the load. Additionally,
2226          * metaslab_sync_done() has to wait for the load to complete because
2227          * there are potential races like metaslab_load() loading parts of the
2228          * space map that are currently being appended by metaslab_sync(). If
2229          * we didn't, the ms_allocatable would have entries that
2230          * metaslab_sync_done() would try to re-add later.
2231          *
2232          * That's why before dropping the lock we remember the synced length
2233          * of the metaslab and read up to that point of the space map,
2234          * ignoring entries appended by metaslab_sync() that happen after we
2235          * drop the lock.
2236          */
2237         uint64_t length = msp->ms_synced_length;
2238         mutex_exit(&msp->ms_lock);
2239
2240         hrtime_t load_start = gethrtime();
2241         metaslab_rt_arg_t *mrap;
2242         if (msp->ms_allocatable->rt_arg == NULL) {
2243                 mrap = kmem_zalloc(sizeof (*mrap), KM_SLEEP);
2244         } else {
2245                 mrap = msp->ms_allocatable->rt_arg;
2246                 msp->ms_allocatable->rt_ops = NULL;
2247                 msp->ms_allocatable->rt_arg = NULL;
2248         }
2249         mrap->mra_bt = &msp->ms_allocatable_by_size;
2250         mrap->mra_floor_shift = metaslab_by_size_min_shift;
2251
2252         if (msp->ms_sm != NULL) {
2253                 error = space_map_load_length(msp->ms_sm, msp->ms_allocatable,
2254                     SM_FREE, length);
2255
2256                 /* Now, populate the size-sorted tree. */
2257                 metaslab_rt_create(msp->ms_allocatable, mrap);
2258                 msp->ms_allocatable->rt_ops = &metaslab_rt_ops;
2259                 msp->ms_allocatable->rt_arg = mrap;
2260
2261                 struct mssa_arg arg = {0};
2262                 arg.rt = msp->ms_allocatable;
2263                 arg.mra = mrap;
2264                 range_tree_walk(msp->ms_allocatable, metaslab_size_sorted_add,
2265                     &arg);
2266         } else {
2267                 /*
2268                  * Add the size-sorted tree first, since we don't need to load
2269                  * the metaslab from the spacemap.
2270                  */
2271                 metaslab_rt_create(msp->ms_allocatable, mrap);
2272                 msp->ms_allocatable->rt_ops = &metaslab_rt_ops;
2273                 msp->ms_allocatable->rt_arg = mrap;
2274                 /*
2275                  * The space map has not been allocated yet, so treat
2276                  * all the space in the metaslab as free and add it to the
2277                  * ms_allocatable tree.
2278                  */
2279                 range_tree_add(msp->ms_allocatable,
2280                     msp->ms_start, msp->ms_size);
2281
2282                 if (msp->ms_freed != NULL) {
2283                         /*
2284                          * If the ms_sm doesn't exist, this means that this
2285                          * metaslab hasn't gone through metaslab_sync() and
2286                          * thus has never been dirtied. So we shouldn't
2287                          * expect any unflushed allocs or frees from previous
2288                          * TXGs.
2289                          *
2290                          * Note: ms_freed and all the other trees except for
2291                          * the ms_allocatable, can be NULL at this point only
2292                          * if this is a new metaslab of a vdev that just got
2293                          * expanded.
2294                          */
2295                         ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
2296                         ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
2297                 }
2298         }
2299
2300         /*
2301          * We need to grab the ms_sync_lock to prevent metaslab_sync() from
2302          * changing the ms_sm (or log_sm) and the metaslab's range trees
2303          * while we are about to use them and populate the ms_allocatable.
2304          * The ms_lock is insufficient for this because metaslab_sync() doesn't
2305          * hold the ms_lock while writing the ms_checkpointing tree to disk.
2306          */
2307         mutex_enter(&msp->ms_sync_lock);
2308         mutex_enter(&msp->ms_lock);
2309
2310         ASSERT(!msp->ms_condensing);
2311         ASSERT(!msp->ms_flushing);
2312
2313         if (error != 0) {
2314                 mutex_exit(&msp->ms_sync_lock);
2315                 return (error);
2316         }
2317
2318         ASSERT3P(msp->ms_group, !=, NULL);
2319         msp->ms_loaded = B_TRUE;
2320
2321         /*
2322          * Apply all the unflushed changes to ms_allocatable right
2323          * away so any manipulations we do below have a clear view
2324          * of what is allocated and what is free.
2325          */
2326         range_tree_walk(msp->ms_unflushed_allocs,
2327             range_tree_remove, msp->ms_allocatable);
2328         range_tree_walk(msp->ms_unflushed_frees,
2329             range_tree_add, msp->ms_allocatable);
2330
2331         msp->ms_loaded = B_TRUE;
2332
2333         ASSERT3P(msp->ms_group, !=, NULL);
2334         spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2335         if (spa_syncing_log_sm(spa) != NULL) {
2336                 ASSERT(spa_feature_is_enabled(spa,
2337                     SPA_FEATURE_LOG_SPACEMAP));
2338
2339                 /*
2340                  * If we use a log space map we add all the segments
2341                  * that are in ms_unflushed_frees so they are available
2342                  * for allocation.
2343                  *
2344                  * ms_allocatable needs to contain all free segments
2345                  * that are ready for allocations (thus not segments
2346                  * from ms_freeing, ms_freed, and the ms_defer trees).
2347                  * But if we grab the lock in this code path at a sync
2348                  * pass later that 1, then it also contains the
2349                  * segments of ms_freed (they were added to it earlier
2350                  * in this path through ms_unflushed_frees). So we
2351                  * need to remove all the segments that exist in
2352                  * ms_freed from ms_allocatable as they will be added
2353                  * later in metaslab_sync_done().
2354                  *
2355                  * When there's no log space map, the ms_allocatable
2356                  * correctly doesn't contain any segments that exist
2357                  * in ms_freed [see ms_synced_length].
2358                  */
2359                 range_tree_walk(msp->ms_freed,
2360                     range_tree_remove, msp->ms_allocatable);
2361         }
2362
2363         /*
2364          * If we are not using the log space map, ms_allocatable
2365          * contains the segments that exist in the ms_defer trees
2366          * [see ms_synced_length]. Thus we need to remove them
2367          * from ms_allocatable as they will be added again in
2368          * metaslab_sync_done().
2369          *
2370          * If we are using the log space map, ms_allocatable still
2371          * contains the segments that exist in the ms_defer trees.
2372          * Not because it read them through the ms_sm though. But
2373          * because these segments are part of ms_unflushed_frees
2374          * whose segments we add to ms_allocatable earlier in this
2375          * code path.
2376          */
2377         for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2378                 range_tree_walk(msp->ms_defer[t],
2379                     range_tree_remove, msp->ms_allocatable);
2380         }
2381
2382         /*
2383          * Call metaslab_recalculate_weight_and_sort() now that the
2384          * metaslab is loaded so we get the metaslab's real weight.
2385          *
2386          * Unless this metaslab was created with older software and
2387          * has not yet been converted to use segment-based weight, we
2388          * expect the new weight to be better or equal to the weight
2389          * that the metaslab had while it was not loaded. This is
2390          * because the old weight does not take into account the
2391          * consolidation of adjacent segments between TXGs. [see
2392          * comment for ms_synchist and ms_deferhist[] for more info]
2393          */
2394         uint64_t weight = msp->ms_weight;
2395         uint64_t max_size = msp->ms_max_size;
2396         metaslab_recalculate_weight_and_sort(msp);
2397         if (!WEIGHT_IS_SPACEBASED(weight))
2398                 ASSERT3U(weight, <=, msp->ms_weight);
2399         msp->ms_max_size = metaslab_largest_allocatable(msp);
2400         ASSERT3U(max_size, <=, msp->ms_max_size);
2401         hrtime_t load_end = gethrtime();
2402         msp->ms_load_time = load_end;
2403         zfs_dbgmsg("metaslab_load: txg %llu, spa %s, vdev_id %llu, "
2404             "ms_id %llu, smp_length %llu, "
2405             "unflushed_allocs %llu, unflushed_frees %llu, "
2406             "freed %llu, defer %llu + %llu, unloaded time %llu ms, "
2407             "loading_time %lld ms, ms_max_size %llu, "
2408             "max size error %lld, "
2409             "old_weight %llx, new_weight %llx",
2410             spa_syncing_txg(spa), spa_name(spa),
2411             msp->ms_group->mg_vd->vdev_id, msp->ms_id,
2412             space_map_length(msp->ms_sm),
2413             range_tree_space(msp->ms_unflushed_allocs),
2414             range_tree_space(msp->ms_unflushed_frees),
2415             range_tree_space(msp->ms_freed),
2416             range_tree_space(msp->ms_defer[0]),
2417             range_tree_space(msp->ms_defer[1]),
2418             (longlong_t)((load_start - msp->ms_unload_time) / 1000000),
2419             (longlong_t)((load_end - load_start) / 1000000),
2420             msp->ms_max_size, msp->ms_max_size - max_size,
2421             weight, msp->ms_weight);
2422
2423         metaslab_verify_space(msp, spa_syncing_txg(spa));
2424         mutex_exit(&msp->ms_sync_lock);
2425         return (0);
2426 }
2427
2428 int
2429 metaslab_load(metaslab_t *msp)
2430 {
2431         ASSERT(MUTEX_HELD(&msp->ms_lock));
2432
2433         /*
2434          * There may be another thread loading the same metaslab, if that's
2435          * the case just wait until the other thread is done and return.
2436          */
2437         metaslab_load_wait(msp);
2438         if (msp->ms_loaded)
2439                 return (0);
2440         VERIFY(!msp->ms_loading);
2441         ASSERT(!msp->ms_condensing);
2442
2443         /*
2444          * We set the loading flag BEFORE potentially dropping the lock to
2445          * wait for an ongoing flush (see ms_flushing below). This way other
2446          * threads know that there is already a thread that is loading this
2447          * metaslab.
2448          */
2449         msp->ms_loading = B_TRUE;
2450
2451         /*
2452          * Wait for any in-progress flushing to finish as we drop the ms_lock
2453          * both here (during space_map_load()) and in metaslab_flush() (when
2454          * we flush our changes to the ms_sm).
2455          */
2456         if (msp->ms_flushing)
2457                 metaslab_flush_wait(msp);
2458
2459         /*
2460          * In the possibility that we were waiting for the metaslab to be
2461          * flushed (where we temporarily dropped the ms_lock), ensure that
2462          * no one else loaded the metaslab somehow.
2463          */
2464         ASSERT(!msp->ms_loaded);
2465
2466         /*
2467          * If we're loading a metaslab in the normal class, consider evicting
2468          * another one to keep our memory usage under the limit defined by the
2469          * zfs_metaslab_mem_limit tunable.
2470          */
2471         if (spa_normal_class(msp->ms_group->mg_class->mc_spa) ==
2472             msp->ms_group->mg_class) {
2473                 metaslab_potentially_evict(msp->ms_group->mg_class);
2474         }
2475
2476         int error = metaslab_load_impl(msp);
2477
2478         ASSERT(MUTEX_HELD(&msp->ms_lock));
2479         msp->ms_loading = B_FALSE;
2480         cv_broadcast(&msp->ms_load_cv);
2481
2482         return (error);
2483 }
2484
2485 void
2486 metaslab_unload(metaslab_t *msp)
2487 {
2488         ASSERT(MUTEX_HELD(&msp->ms_lock));
2489
2490         /*
2491          * This can happen if a metaslab is selected for eviction (in
2492          * metaslab_potentially_evict) and then unloaded during spa_sync (via
2493          * metaslab_class_evict_old).
2494          */
2495         if (!msp->ms_loaded)
2496                 return;
2497
2498         range_tree_vacate(msp->ms_allocatable, NULL, NULL);
2499         msp->ms_loaded = B_FALSE;
2500         msp->ms_unload_time = gethrtime();
2501
2502         msp->ms_activation_weight = 0;
2503         msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
2504
2505         if (msp->ms_group != NULL) {
2506                 metaslab_class_t *mc = msp->ms_group->mg_class;
2507                 multilist_sublist_t *mls =
2508                     multilist_sublist_lock_obj(mc->mc_metaslab_txg_list, msp);
2509                 if (multilist_link_active(&msp->ms_class_txg_node))
2510                         multilist_sublist_remove(mls, msp);
2511                 multilist_sublist_unlock(mls);
2512
2513                 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2514                 zfs_dbgmsg("metaslab_unload: txg %llu, spa %s, vdev_id %llu, "
2515                     "ms_id %llu, weight %llx, "
2516                     "selected txg %llu (%llu ms ago), alloc_txg %llu, "
2517                     "loaded %llu ms ago, max_size %llu",
2518                     spa_syncing_txg(spa), spa_name(spa),
2519                     msp->ms_group->mg_vd->vdev_id, msp->ms_id,
2520                     msp->ms_weight,
2521                     msp->ms_selected_txg,
2522                     (msp->ms_unload_time - msp->ms_selected_time) / 1000 / 1000,
2523                     msp->ms_alloc_txg,
2524                     (msp->ms_unload_time - msp->ms_load_time) / 1000 / 1000,
2525                     msp->ms_max_size);
2526         }
2527
2528         /*
2529          * We explicitly recalculate the metaslab's weight based on its space
2530          * map (as it is now not loaded). We want unload metaslabs to always
2531          * have their weights calculated from the space map histograms, while
2532          * loaded ones have it calculated from their in-core range tree
2533          * [see metaslab_load()]. This way, the weight reflects the information
2534          * available in-core, whether it is loaded or not.
2535          *
2536          * If ms_group == NULL means that we came here from metaslab_fini(),
2537          * at which point it doesn't make sense for us to do the recalculation
2538          * and the sorting.
2539          */
2540         if (msp->ms_group != NULL)
2541                 metaslab_recalculate_weight_and_sort(msp);
2542 }
2543
2544 /*
2545  * We want to optimize the memory use of the per-metaslab range
2546  * trees. To do this, we store the segments in the range trees in
2547  * units of sectors, zero-indexing from the start of the metaslab. If
2548  * the vdev_ms_shift - the vdev_ashift is less than 32, we can store
2549  * the ranges using two uint32_ts, rather than two uint64_ts.
2550  */
2551 range_seg_type_t
2552 metaslab_calculate_range_tree_type(vdev_t *vdev, metaslab_t *msp,
2553     uint64_t *start, uint64_t *shift)
2554 {
2555         if (vdev->vdev_ms_shift - vdev->vdev_ashift < 32 &&
2556             !zfs_metaslab_force_large_segs) {
2557                 *shift = vdev->vdev_ashift;
2558                 *start = msp->ms_start;
2559                 return (RANGE_SEG32);
2560         } else {
2561                 *shift = 0;
2562                 *start = 0;
2563                 return (RANGE_SEG64);
2564         }
2565 }
2566
2567 void
2568 metaslab_set_selected_txg(metaslab_t *msp, uint64_t txg)
2569 {
2570         ASSERT(MUTEX_HELD(&msp->ms_lock));
2571         metaslab_class_t *mc = msp->ms_group->mg_class;
2572         multilist_sublist_t *mls =
2573             multilist_sublist_lock_obj(mc->mc_metaslab_txg_list, msp);
2574         if (multilist_link_active(&msp->ms_class_txg_node))
2575                 multilist_sublist_remove(mls, msp);
2576         msp->ms_selected_txg = txg;
2577         msp->ms_selected_time = gethrtime();
2578         multilist_sublist_insert_tail(mls, msp);
2579         multilist_sublist_unlock(mls);
2580 }
2581
2582 void
2583 metaslab_space_update(vdev_t *vd, metaslab_class_t *mc, int64_t alloc_delta,
2584     int64_t defer_delta, int64_t space_delta)
2585 {
2586         vdev_space_update(vd, alloc_delta, defer_delta, space_delta);
2587
2588         ASSERT3P(vd->vdev_spa->spa_root_vdev, ==, vd->vdev_parent);
2589         ASSERT(vd->vdev_ms_count != 0);
2590
2591         metaslab_class_space_update(mc, alloc_delta, defer_delta, space_delta,
2592             vdev_deflated_space(vd, space_delta));
2593 }
2594
2595 int
2596 metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object,
2597     uint64_t txg, metaslab_t **msp)
2598 {
2599         vdev_t *vd = mg->mg_vd;
2600         spa_t *spa = vd->vdev_spa;
2601         objset_t *mos = spa->spa_meta_objset;
2602         metaslab_t *ms;
2603         int error;
2604
2605         ms = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
2606         mutex_init(&ms->ms_lock, NULL, MUTEX_DEFAULT, NULL);
2607         mutex_init(&ms->ms_sync_lock, NULL, MUTEX_DEFAULT, NULL);
2608         cv_init(&ms->ms_load_cv, NULL, CV_DEFAULT, NULL);
2609         cv_init(&ms->ms_flush_cv, NULL, CV_DEFAULT, NULL);
2610         multilist_link_init(&ms->ms_class_txg_node);
2611
2612         ms->ms_id = id;
2613         ms->ms_start = id << vd->vdev_ms_shift;
2614         ms->ms_size = 1ULL << vd->vdev_ms_shift;
2615         ms->ms_allocator = -1;
2616         ms->ms_new = B_TRUE;
2617
2618         /*
2619          * We only open space map objects that already exist. All others
2620          * will be opened when we finally allocate an object for it.
2621          *
2622          * Note:
2623          * When called from vdev_expand(), we can't call into the DMU as
2624          * we are holding the spa_config_lock as a writer and we would
2625          * deadlock [see relevant comment in vdev_metaslab_init()]. in
2626          * that case, the object parameter is zero though, so we won't
2627          * call into the DMU.
2628          */
2629         if (object != 0) {
2630                 error = space_map_open(&ms->ms_sm, mos, object, ms->ms_start,
2631                     ms->ms_size, vd->vdev_ashift);
2632
2633                 if (error != 0) {
2634                         kmem_free(ms, sizeof (metaslab_t));
2635                         return (error);
2636                 }
2637
2638                 ASSERT(ms->ms_sm != NULL);
2639                 ms->ms_allocated_space = space_map_allocated(ms->ms_sm);
2640         }
2641
2642         range_seg_type_t type;
2643         uint64_t shift, start;
2644         type = metaslab_calculate_range_tree_type(vd, ms, &start, &shift);
2645
2646         /*
2647          * We create the ms_allocatable here, but we don't create the
2648          * other range trees until metaslab_sync_done().  This serves
2649          * two purposes: it allows metaslab_sync_done() to detect the
2650          * addition of new space; and for debugging, it ensures that
2651          * we'd data fault on any attempt to use this metaslab before
2652          * it's ready.
2653          */
2654         ms->ms_allocatable = range_tree_create(NULL, type, NULL, start, shift);
2655
2656         ms->ms_trim = range_tree_create(NULL, type, NULL, start, shift);
2657
2658         metaslab_group_add(mg, ms);
2659         metaslab_set_fragmentation(ms, B_FALSE);
2660
2661         /*
2662          * If we're opening an existing pool (txg == 0) or creating
2663          * a new one (txg == TXG_INITIAL), all space is available now.
2664          * If we're adding space to an existing pool, the new space
2665          * does not become available until after this txg has synced.
2666          * The metaslab's weight will also be initialized when we sync
2667          * out this txg. This ensures that we don't attempt to allocate
2668          * from it before we have initialized it completely.
2669          */
2670         if (txg <= TXG_INITIAL) {
2671                 metaslab_sync_done(ms, 0);
2672                 metaslab_space_update(vd, mg->mg_class,
2673                     metaslab_allocated_space(ms), 0, 0);
2674         }
2675
2676         if (txg != 0) {
2677                 vdev_dirty(vd, 0, NULL, txg);
2678                 vdev_dirty(vd, VDD_METASLAB, ms, txg);
2679         }
2680
2681         *msp = ms;
2682
2683         return (0);
2684 }
2685
2686 static void
2687 metaslab_fini_flush_data(metaslab_t *msp)
2688 {
2689         spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2690
2691         if (metaslab_unflushed_txg(msp) == 0) {
2692                 ASSERT3P(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL),
2693                     ==, NULL);
2694                 return;
2695         }
2696         ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
2697
2698         mutex_enter(&spa->spa_flushed_ms_lock);
2699         avl_remove(&spa->spa_metaslabs_by_flushed, msp);
2700         mutex_exit(&spa->spa_flushed_ms_lock);
2701
2702         spa_log_sm_decrement_mscount(spa, metaslab_unflushed_txg(msp));
2703         spa_log_summary_decrement_mscount(spa, metaslab_unflushed_txg(msp));
2704 }
2705
2706 uint64_t
2707 metaslab_unflushed_changes_memused(metaslab_t *ms)
2708 {
2709         return ((range_tree_numsegs(ms->ms_unflushed_allocs) +
2710             range_tree_numsegs(ms->ms_unflushed_frees)) *
2711             ms->ms_unflushed_allocs->rt_root.bt_elem_size);
2712 }
2713
2714 void
2715 metaslab_fini(metaslab_t *msp)
2716 {
2717         metaslab_group_t *mg = msp->ms_group;
2718         vdev_t *vd = mg->mg_vd;
2719         spa_t *spa = vd->vdev_spa;
2720
2721         metaslab_fini_flush_data(msp);
2722
2723         metaslab_group_remove(mg, msp);
2724
2725         mutex_enter(&msp->ms_lock);
2726         VERIFY(msp->ms_group == NULL);
2727         metaslab_space_update(vd, mg->mg_class,
2728             -metaslab_allocated_space(msp), 0, -msp->ms_size);
2729
2730         space_map_close(msp->ms_sm);
2731         msp->ms_sm = NULL;
2732
2733         metaslab_unload(msp);
2734         range_tree_destroy(msp->ms_allocatable);
2735         range_tree_destroy(msp->ms_freeing);
2736         range_tree_destroy(msp->ms_freed);
2737
2738         ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
2739             metaslab_unflushed_changes_memused(msp));
2740         spa->spa_unflushed_stats.sus_memused -=
2741             metaslab_unflushed_changes_memused(msp);
2742         range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
2743         range_tree_destroy(msp->ms_unflushed_allocs);
2744         range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
2745         range_tree_destroy(msp->ms_unflushed_frees);
2746
2747         for (int t = 0; t < TXG_SIZE; t++) {
2748                 range_tree_destroy(msp->ms_allocating[t]);
2749         }
2750
2751         for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2752                 range_tree_destroy(msp->ms_defer[t]);
2753         }
2754         ASSERT0(msp->ms_deferspace);
2755
2756         range_tree_destroy(msp->ms_checkpointing);
2757
2758         for (int t = 0; t < TXG_SIZE; t++)
2759                 ASSERT(!txg_list_member(&vd->vdev_ms_list, msp, t));
2760
2761         range_tree_vacate(msp->ms_trim, NULL, NULL);
2762         range_tree_destroy(msp->ms_trim);
2763
2764         mutex_exit(&msp->ms_lock);
2765         cv_destroy(&msp->ms_load_cv);
2766         cv_destroy(&msp->ms_flush_cv);
2767         mutex_destroy(&msp->ms_lock);
2768         mutex_destroy(&msp->ms_sync_lock);
2769         ASSERT3U(msp->ms_allocator, ==, -1);
2770
2771         kmem_free(msp, sizeof (metaslab_t));
2772 }
2773
2774 #define FRAGMENTATION_TABLE_SIZE        17
2775
2776 /*
2777  * This table defines a segment size based fragmentation metric that will
2778  * allow each metaslab to derive its own fragmentation value. This is done
2779  * by calculating the space in each bucket of the spacemap histogram and
2780  * multiplying that by the fragmentation metric in this table. Doing
2781  * this for all buckets and dividing it by the total amount of free
2782  * space in this metaslab (i.e. the total free space in all buckets) gives
2783  * us the fragmentation metric. This means that a high fragmentation metric
2784  * equates to most of the free space being comprised of small segments.
2785  * Conversely, if the metric is low, then most of the free space is in
2786  * large segments. A 10% change in fragmentation equates to approximately
2787  * double the number of segments.
2788  *
2789  * This table defines 0% fragmented space using 16MB segments. Testing has
2790  * shown that segments that are greater than or equal to 16MB do not suffer
2791  * from drastic performance problems. Using this value, we derive the rest
2792  * of the table. Since the fragmentation value is never stored on disk, it
2793  * is possible to change these calculations in the future.
2794  */
2795 int zfs_frag_table[FRAGMENTATION_TABLE_SIZE] = {
2796         100,    /* 512B */
2797         100,    /* 1K   */
2798         98,     /* 2K   */
2799         95,     /* 4K   */
2800         90,     /* 8K   */
2801         80,     /* 16K  */
2802         70,     /* 32K  */
2803         60,     /* 64K  */
2804         50,     /* 128K */
2805         40,     /* 256K */
2806         30,     /* 512K */
2807         20,     /* 1M   */
2808         15,     /* 2M   */
2809         10,     /* 4M   */
2810         5,      /* 8M   */
2811         0       /* 16M  */
2812 };
2813
2814 /*
2815  * Calculate the metaslab's fragmentation metric and set ms_fragmentation.
2816  * Setting this value to ZFS_FRAG_INVALID means that the metaslab has not
2817  * been upgraded and does not support this metric. Otherwise, the return
2818  * value should be in the range [0, 100].
2819  */
2820 static void
2821 metaslab_set_fragmentation(metaslab_t *msp, boolean_t nodirty)
2822 {
2823         spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2824         uint64_t fragmentation = 0;
2825         uint64_t total = 0;
2826         boolean_t feature_enabled = spa_feature_is_enabled(spa,
2827             SPA_FEATURE_SPACEMAP_HISTOGRAM);
2828
2829         if (!feature_enabled) {
2830                 msp->ms_fragmentation = ZFS_FRAG_INVALID;
2831                 return;
2832         }
2833
2834         /*
2835          * A null space map means that the entire metaslab is free
2836          * and thus is not fragmented.
2837          */
2838         if (msp->ms_sm == NULL) {
2839                 msp->ms_fragmentation = 0;
2840                 return;
2841         }
2842
2843         /*
2844          * If this metaslab's space map has not been upgraded, flag it
2845          * so that we upgrade next time we encounter it.
2846          */
2847         if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
2848                 uint64_t txg = spa_syncing_txg(spa);
2849                 vdev_t *vd = msp->ms_group->mg_vd;
2850
2851                 /*
2852                  * If we've reached the final dirty txg, then we must
2853                  * be shutting down the pool. We don't want to dirty
2854                  * any data past this point so skip setting the condense
2855                  * flag. We can retry this action the next time the pool
2856                  * is imported. We also skip marking this metaslab for
2857                  * condensing if the caller has explicitly set nodirty.
2858                  */
2859                 if (!nodirty &&
2860                     spa_writeable(spa) && txg < spa_final_dirty_txg(spa)) {
2861                         msp->ms_condense_wanted = B_TRUE;
2862                         vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
2863                         zfs_dbgmsg("txg %llu, requesting force condense: "
2864                             "ms_id %llu, vdev_id %llu", txg, msp->ms_id,
2865                             vd->vdev_id);
2866                 }
2867                 msp->ms_fragmentation = ZFS_FRAG_INVALID;
2868                 return;
2869         }
2870
2871         for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
2872                 uint64_t space = 0;
2873                 uint8_t shift = msp->ms_sm->sm_shift;
2874
2875                 int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
2876                     FRAGMENTATION_TABLE_SIZE - 1);
2877
2878                 if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
2879                         continue;
2880
2881                 space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
2882                 total += space;
2883
2884                 ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
2885                 fragmentation += space * zfs_frag_table[idx];
2886         }
2887
2888         if (total > 0)
2889                 fragmentation /= total;
2890         ASSERT3U(fragmentation, <=, 100);
2891
2892         msp->ms_fragmentation = fragmentation;
2893 }
2894
2895 /*
2896  * Compute a weight -- a selection preference value -- for the given metaslab.
2897  * This is based on the amount of free space, the level of fragmentation,
2898  * the LBA range, and whether the metaslab is loaded.
2899  */
2900 static uint64_t
2901 metaslab_space_weight(metaslab_t *msp)
2902 {
2903         metaslab_group_t *mg = msp->ms_group;
2904         vdev_t *vd = mg->mg_vd;
2905         uint64_t weight, space;
2906
2907         ASSERT(MUTEX_HELD(&msp->ms_lock));
2908
2909         /*
2910          * The baseline weight is the metaslab's free space.
2911          */
2912         space = msp->ms_size - metaslab_allocated_space(msp);
2913
2914         if (metaslab_fragmentation_factor_enabled &&
2915             msp->ms_fragmentation != ZFS_FRAG_INVALID) {
2916                 /*
2917                  * Use the fragmentation information to inversely scale
2918                  * down the baseline weight. We need to ensure that we
2919                  * don't exclude this metaslab completely when it's 100%
2920                  * fragmented. To avoid this we reduce the fragmented value
2921                  * by 1.
2922                  */
2923                 space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
2924
2925                 /*
2926                  * If space < SPA_MINBLOCKSIZE, then we will not allocate from
2927                  * this metaslab again. The fragmentation metric may have
2928                  * decreased the space to something smaller than
2929                  * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
2930                  * so that we can consume any remaining space.
2931                  */
2932                 if (space > 0 && space < SPA_MINBLOCKSIZE)
2933                         space = SPA_MINBLOCKSIZE;
2934         }
2935         weight = space;
2936
2937         /*
2938          * Modern disks have uniform bit density and constant angular velocity.
2939          * Therefore, the outer recording zones are faster (higher bandwidth)
2940          * than the inner zones by the ratio of outer to inner track diameter,
2941          * which is typically around 2:1.  We account for this by assigning
2942          * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
2943          * In effect, this means that we'll select the metaslab with the most
2944          * free bandwidth rather than simply the one with the most free space.
2945          */
2946         if (!vd->vdev_nonrot && metaslab_lba_weighting_enabled) {
2947                 weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
2948                 ASSERT(weight >= space && weight <= 2 * space);
2949         }
2950
2951         /*
2952          * If this metaslab is one we're actively using, adjust its
2953          * weight to make it preferable to any inactive metaslab so
2954          * we'll polish it off. If the fragmentation on this metaslab
2955          * has exceed our threshold, then don't mark it active.
2956          */
2957         if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
2958             msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
2959                 weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
2960         }
2961
2962         WEIGHT_SET_SPACEBASED(weight);
2963         return (weight);
2964 }
2965
2966 /*
2967  * Return the weight of the specified metaslab, according to the segment-based
2968  * weighting algorithm. The metaslab must be loaded. This function can
2969  * be called within a sync pass since it relies only on the metaslab's
2970  * range tree which is always accurate when the metaslab is loaded.
2971  */
2972 static uint64_t
2973 metaslab_weight_from_range_tree(metaslab_t *msp)
2974 {
2975         uint64_t weight = 0;
2976         uint32_t segments = 0;
2977
2978         ASSERT(msp->ms_loaded);
2979
2980         for (int i = RANGE_TREE_HISTOGRAM_SIZE - 1; i >= SPA_MINBLOCKSHIFT;
2981             i--) {
2982                 uint8_t shift = msp->ms_group->mg_vd->vdev_ashift;
2983                 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
2984
2985                 segments <<= 1;
2986                 segments += msp->ms_allocatable->rt_histogram[i];
2987
2988                 /*
2989                  * The range tree provides more precision than the space map
2990                  * and must be downgraded so that all values fit within the
2991                  * space map's histogram. This allows us to compare loaded
2992                  * vs. unloaded metaslabs to determine which metaslab is
2993                  * considered "best".
2994                  */
2995                 if (i > max_idx)
2996                         continue;
2997
2998                 if (segments != 0) {
2999                         WEIGHT_SET_COUNT(weight, segments);
3000                         WEIGHT_SET_INDEX(weight, i);
3001                         WEIGHT_SET_ACTIVE(weight, 0);
3002                         break;
3003                 }
3004         }
3005         return (weight);
3006 }
3007
3008 /*
3009  * Calculate the weight based on the on-disk histogram. Should be applied
3010  * only to unloaded metaslabs  (i.e no incoming allocations) in-order to
3011  * give results consistent with the on-disk state
3012  */
3013 static uint64_t
3014 metaslab_weight_from_spacemap(metaslab_t *msp)
3015 {
3016         space_map_t *sm = msp->ms_sm;
3017         ASSERT(!msp->ms_loaded);
3018         ASSERT(sm != NULL);
3019         ASSERT3U(space_map_object(sm), !=, 0);
3020         ASSERT3U(sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
3021
3022         /*
3023          * Create a joint histogram from all the segments that have made
3024          * it to the metaslab's space map histogram, that are not yet
3025          * available for allocation because they are still in the freeing
3026          * pipeline (e.g. freeing, freed, and defer trees). Then subtract
3027          * these segments from the space map's histogram to get a more
3028          * accurate weight.
3029          */
3030         uint64_t deferspace_histogram[SPACE_MAP_HISTOGRAM_SIZE] = {0};
3031         for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
3032                 deferspace_histogram[i] += msp->ms_synchist[i];
3033         for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3034                 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
3035                         deferspace_histogram[i] += msp->ms_deferhist[t][i];
3036                 }
3037         }
3038
3039         uint64_t weight = 0;
3040         for (int i = SPACE_MAP_HISTOGRAM_SIZE - 1; i >= 0; i--) {
3041                 ASSERT3U(sm->sm_phys->smp_histogram[i], >=,
3042                     deferspace_histogram[i]);
3043                 uint64_t count =
3044                     sm->sm_phys->smp_histogram[i] - deferspace_histogram[i];
3045                 if (count != 0) {
3046                         WEIGHT_SET_COUNT(weight, count);
3047                         WEIGHT_SET_INDEX(weight, i + sm->sm_shift);
3048                         WEIGHT_SET_ACTIVE(weight, 0);
3049                         break;
3050                 }
3051         }
3052         return (weight);
3053 }
3054
3055 /*
3056  * Compute a segment-based weight for the specified metaslab. The weight
3057  * is determined by highest bucket in the histogram. The information
3058  * for the highest bucket is encoded into the weight value.
3059  */
3060 static uint64_t
3061 metaslab_segment_weight(metaslab_t *msp)
3062 {
3063         metaslab_group_t *mg = msp->ms_group;
3064         uint64_t weight = 0;
3065         uint8_t shift = mg->mg_vd->vdev_ashift;
3066
3067         ASSERT(MUTEX_HELD(&msp->ms_lock));
3068
3069         /*
3070          * The metaslab is completely free.
3071          */
3072         if (metaslab_allocated_space(msp) == 0) {
3073                 int idx = highbit64(msp->ms_size) - 1;
3074                 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
3075
3076                 if (idx < max_idx) {
3077                         WEIGHT_SET_COUNT(weight, 1ULL);
3078                         WEIGHT_SET_INDEX(weight, idx);
3079                 } else {
3080                         WEIGHT_SET_COUNT(weight, 1ULL << (idx - max_idx));
3081                         WEIGHT_SET_INDEX(weight, max_idx);
3082                 }
3083                 WEIGHT_SET_ACTIVE(weight, 0);
3084                 ASSERT(!WEIGHT_IS_SPACEBASED(weight));
3085                 return (weight);
3086         }
3087
3088         ASSERT3U(msp->ms_sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
3089
3090         /*
3091          * If the metaslab is fully allocated then just make the weight 0.
3092          */
3093         if (metaslab_allocated_space(msp) == msp->ms_size)
3094                 return (0);
3095         /*
3096          * If the metaslab is already loaded, then use the range tree to
3097          * determine the weight. Otherwise, we rely on the space map information
3098          * to generate the weight.
3099          */
3100         if (msp->ms_loaded) {
3101                 weight = metaslab_weight_from_range_tree(msp);
3102         } else {
3103                 weight = metaslab_weight_from_spacemap(msp);
3104         }
3105
3106         /*
3107          * If the metaslab was active the last time we calculated its weight
3108          * then keep it active. We want to consume the entire region that
3109          * is associated with this weight.
3110          */
3111         if (msp->ms_activation_weight != 0 && weight != 0)
3112                 WEIGHT_SET_ACTIVE(weight, WEIGHT_GET_ACTIVE(msp->ms_weight));
3113         return (weight);
3114 }
3115
3116 /*
3117  * Determine if we should attempt to allocate from this metaslab. If the
3118  * metaslab is loaded, then we can determine if the desired allocation
3119  * can be satisfied by looking at the size of the maximum free segment
3120  * on that metaslab. Otherwise, we make our decision based on the metaslab's
3121  * weight. For segment-based weighting we can determine the maximum
3122  * allocation based on the index encoded in its value. For space-based
3123  * weights we rely on the entire weight (excluding the weight-type bit).
3124  */
3125 static boolean_t
3126 metaslab_should_allocate(metaslab_t *msp, uint64_t asize, boolean_t try_hard)
3127 {
3128         /*
3129          * If the metaslab is loaded, ms_max_size is definitive and we can use
3130          * the fast check. If it's not, the ms_max_size is a lower bound (once
3131          * set), and we should use the fast check as long as we're not in
3132          * try_hard and it's been less than zfs_metaslab_max_size_cache_sec
3133          * seconds since the metaslab was unloaded.
3134          */
3135         if (msp->ms_loaded ||
3136             (msp->ms_max_size != 0 && !try_hard && gethrtime() <
3137             msp->ms_unload_time + SEC2NSEC(zfs_metaslab_max_size_cache_sec)))
3138                 return (msp->ms_max_size >= asize);
3139
3140         boolean_t should_allocate;
3141         if (!WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
3142                 /*
3143                  * The metaslab segment weight indicates segments in the
3144                  * range [2^i, 2^(i+1)), where i is the index in the weight.
3145                  * Since the asize might be in the middle of the range, we
3146                  * should attempt the allocation if asize < 2^(i+1).
3147                  */
3148                 should_allocate = (asize <
3149                     1ULL << (WEIGHT_GET_INDEX(msp->ms_weight) + 1));
3150         } else {
3151                 should_allocate = (asize <=
3152                     (msp->ms_weight & ~METASLAB_WEIGHT_TYPE));
3153         }
3154
3155         return (should_allocate);
3156 }
3157
3158 static uint64_t
3159 metaslab_weight(metaslab_t *msp, boolean_t nodirty)
3160 {
3161         vdev_t *vd = msp->ms_group->mg_vd;
3162         spa_t *spa = vd->vdev_spa;
3163         uint64_t weight;
3164
3165         ASSERT(MUTEX_HELD(&msp->ms_lock));
3166
3167         metaslab_set_fragmentation(msp, nodirty);
3168
3169         /*
3170          * Update the maximum size. If the metaslab is loaded, this will
3171          * ensure that we get an accurate maximum size if newly freed space
3172          * has been added back into the free tree. If the metaslab is
3173          * unloaded, we check if there's a larger free segment in the
3174          * unflushed frees. This is a lower bound on the largest allocatable
3175          * segment size. Coalescing of adjacent entries may reveal larger
3176          * allocatable segments, but we aren't aware of those until loading
3177          * the space map into a range tree.
3178          */
3179         if (msp->ms_loaded) {
3180                 msp->ms_max_size = metaslab_largest_allocatable(msp);
3181         } else {
3182                 msp->ms_max_size = MAX(msp->ms_max_size,
3183                     metaslab_largest_unflushed_free(msp));
3184         }
3185
3186         /*
3187          * Segment-based weighting requires space map histogram support.
3188          */
3189         if (zfs_metaslab_segment_weight_enabled &&
3190             spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM) &&
3191             (msp->ms_sm == NULL || msp->ms_sm->sm_dbuf->db_size ==
3192             sizeof (space_map_phys_t))) {
3193                 weight = metaslab_segment_weight(msp);
3194         } else {
3195                 weight = metaslab_space_weight(msp);
3196         }
3197         return (weight);
3198 }
3199
3200 void
3201 metaslab_recalculate_weight_and_sort(metaslab_t *msp)
3202 {
3203         ASSERT(MUTEX_HELD(&msp->ms_lock));
3204
3205         /* note: we preserve the mask (e.g. indication of primary, etc..) */
3206         uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
3207         metaslab_group_sort(msp->ms_group, msp,
3208             metaslab_weight(msp, B_FALSE) | was_active);
3209 }
3210
3211 static int
3212 metaslab_activate_allocator(metaslab_group_t *mg, metaslab_t *msp,
3213     int allocator, uint64_t activation_weight)
3214 {
3215         metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
3216         ASSERT(MUTEX_HELD(&msp->ms_lock));
3217
3218         /*
3219          * If we're activating for the claim code, we don't want to actually
3220          * set the metaslab up for a specific allocator.
3221          */
3222         if (activation_weight == METASLAB_WEIGHT_CLAIM) {
3223                 ASSERT0(msp->ms_activation_weight);
3224                 msp->ms_activation_weight = msp->ms_weight;
3225                 metaslab_group_sort(mg, msp, msp->ms_weight |
3226                     activation_weight);
3227                 return (0);
3228         }
3229
3230         metaslab_t **mspp = (activation_weight == METASLAB_WEIGHT_PRIMARY ?
3231             &mga->mga_primary : &mga->mga_secondary);
3232
3233         mutex_enter(&mg->mg_lock);
3234         if (*mspp != NULL) {
3235                 mutex_exit(&mg->mg_lock);
3236                 return (EEXIST);
3237         }
3238
3239         *mspp = msp;
3240         ASSERT3S(msp->ms_allocator, ==, -1);
3241         msp->ms_allocator = allocator;
3242         msp->ms_primary = (activation_weight == METASLAB_WEIGHT_PRIMARY);
3243
3244         ASSERT0(msp->ms_activation_weight);
3245         msp->ms_activation_weight = msp->ms_weight;
3246         metaslab_group_sort_impl(mg, msp,
3247             msp->ms_weight | activation_weight);
3248         mutex_exit(&mg->mg_lock);
3249
3250         return (0);
3251 }
3252
3253 static int
3254 metaslab_activate(metaslab_t *msp, int allocator, uint64_t activation_weight)
3255 {
3256         ASSERT(MUTEX_HELD(&msp->ms_lock));
3257
3258         /*
3259          * The current metaslab is already activated for us so there
3260          * is nothing to do. Already activated though, doesn't mean
3261          * that this metaslab is activated for our allocator nor our
3262          * requested activation weight. The metaslab could have started
3263          * as an active one for our allocator but changed allocators
3264          * while we were waiting to grab its ms_lock or we stole it
3265          * [see find_valid_metaslab()]. This means that there is a
3266          * possibility of passivating a metaslab of another allocator
3267          * or from a different activation mask, from this thread.
3268          */
3269         if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
3270                 ASSERT(msp->ms_loaded);
3271                 return (0);
3272         }
3273
3274         int error = metaslab_load(msp);
3275         if (error != 0) {
3276                 metaslab_group_sort(msp->ms_group, msp, 0);
3277                 return (error);
3278         }
3279
3280         /*
3281          * When entering metaslab_load() we may have dropped the
3282          * ms_lock because we were loading this metaslab, or we
3283          * were waiting for another thread to load it for us. In
3284          * that scenario, we recheck the weight of the metaslab
3285          * to see if it was activated by another thread.
3286          *
3287          * If the metaslab was activated for another allocator or
3288          * it was activated with a different activation weight (e.g.
3289          * we wanted to make it a primary but it was activated as
3290          * secondary) we return error (EBUSY).
3291          *
3292          * If the metaslab was activated for the same allocator
3293          * and requested activation mask, skip activating it.
3294          */
3295         if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
3296                 if (msp->ms_allocator != allocator)
3297                         return (EBUSY);
3298
3299                 if ((msp->ms_weight & activation_weight) == 0)
3300                         return (SET_ERROR(EBUSY));
3301
3302                 EQUIV((activation_weight == METASLAB_WEIGHT_PRIMARY),
3303                     msp->ms_primary);
3304                 return (0);
3305         }
3306
3307         /*
3308          * If the metaslab has literally 0 space, it will have weight 0. In
3309          * that case, don't bother activating it. This can happen if the
3310          * metaslab had space during find_valid_metaslab, but another thread
3311          * loaded it and used all that space while we were waiting to grab the
3312          * lock.
3313          */
3314         if (msp->ms_weight == 0) {
3315                 ASSERT0(range_tree_space(msp->ms_allocatable));
3316                 return (SET_ERROR(ENOSPC));
3317         }
3318
3319         if ((error = metaslab_activate_allocator(msp->ms_group, msp,
3320             allocator, activation_weight)) != 0) {
3321                 return (error);
3322         }
3323
3324         ASSERT(msp->ms_loaded);
3325         ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
3326
3327         return (0);
3328 }
3329
3330 static void
3331 metaslab_passivate_allocator(metaslab_group_t *mg, metaslab_t *msp,
3332     uint64_t weight)
3333 {
3334         ASSERT(MUTEX_HELD(&msp->ms_lock));
3335         ASSERT(msp->ms_loaded);
3336
3337         if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
3338                 metaslab_group_sort(mg, msp, weight);
3339                 return;
3340         }
3341
3342         mutex_enter(&mg->mg_lock);
3343         ASSERT3P(msp->ms_group, ==, mg);
3344         ASSERT3S(0, <=, msp->ms_allocator);
3345         ASSERT3U(msp->ms_allocator, <, mg->mg_allocators);
3346
3347         metaslab_group_allocator_t *mga = &mg->mg_allocator[msp->ms_allocator];
3348         if (msp->ms_primary) {
3349                 ASSERT3P(mga->mga_primary, ==, msp);
3350                 ASSERT(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
3351                 mga->mga_primary = NULL;
3352         } else {
3353                 ASSERT3P(mga->mga_secondary, ==, msp);
3354                 ASSERT(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
3355                 mga->mga_secondary = NULL;
3356         }
3357         msp->ms_allocator = -1;
3358         metaslab_group_sort_impl(mg, msp, weight);
3359         mutex_exit(&mg->mg_lock);
3360 }
3361
3362 static void
3363 metaslab_passivate(metaslab_t *msp, uint64_t weight)
3364 {
3365         uint64_t size __maybe_unused = weight & ~METASLAB_WEIGHT_TYPE;
3366
3367         /*
3368          * If size < SPA_MINBLOCKSIZE, then we will not allocate from
3369          * this metaslab again.  In that case, it had better be empty,
3370          * or we would be leaving space on the table.
3371          */
3372         ASSERT(!WEIGHT_IS_SPACEBASED(msp->ms_weight) ||
3373             size >= SPA_MINBLOCKSIZE ||
3374             range_tree_space(msp->ms_allocatable) == 0);
3375         ASSERT0(weight & METASLAB_ACTIVE_MASK);
3376
3377         ASSERT(msp->ms_activation_weight != 0);
3378         msp->ms_activation_weight = 0;
3379         metaslab_passivate_allocator(msp->ms_group, msp, weight);
3380         ASSERT0(msp->ms_weight & METASLAB_ACTIVE_MASK);
3381 }
3382
3383 /*
3384  * Segment-based metaslabs are activated once and remain active until
3385  * we either fail an allocation attempt (similar to space-based metaslabs)
3386  * or have exhausted the free space in zfs_metaslab_switch_threshold
3387  * buckets since the metaslab was activated. This function checks to see
3388  * if we've exhausted the zfs_metaslab_switch_threshold buckets in the
3389  * metaslab and passivates it proactively. This will allow us to select a
3390  * metaslab with a larger contiguous region, if any, remaining within this
3391  * metaslab group. If we're in sync pass > 1, then we continue using this
3392  * metaslab so that we don't dirty more block and cause more sync passes.
3393  */
3394 static void
3395 metaslab_segment_may_passivate(metaslab_t *msp)
3396 {
3397         spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3398
3399         if (WEIGHT_IS_SPACEBASED(msp->ms_weight) || spa_sync_pass(spa) > 1)
3400                 return;
3401
3402         /*
3403          * Since we are in the middle of a sync pass, the most accurate
3404          * information that is accessible to us is the in-core range tree
3405          * histogram; calculate the new weight based on that information.
3406          */
3407         uint64_t weight = metaslab_weight_from_range_tree(msp);
3408         int activation_idx = WEIGHT_GET_INDEX(msp->ms_activation_weight);
3409         int current_idx = WEIGHT_GET_INDEX(weight);
3410
3411         if (current_idx <= activation_idx - zfs_metaslab_switch_threshold)
3412                 metaslab_passivate(msp, weight);
3413 }
3414
3415 static void
3416 metaslab_preload(void *arg)
3417 {
3418         metaslab_t *msp = arg;
3419         metaslab_class_t *mc = msp->ms_group->mg_class;
3420         spa_t *spa = mc->mc_spa;
3421         fstrans_cookie_t cookie = spl_fstrans_mark();
3422
3423         ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
3424
3425         mutex_enter(&msp->ms_lock);
3426         (void) metaslab_load(msp);
3427         metaslab_set_selected_txg(msp, spa_syncing_txg(spa));
3428         mutex_exit(&msp->ms_lock);
3429         spl_fstrans_unmark(cookie);
3430 }
3431
3432 static void
3433 metaslab_group_preload(metaslab_group_t *mg)
3434 {
3435         spa_t *spa = mg->mg_vd->vdev_spa;
3436         metaslab_t *msp;
3437         avl_tree_t *t = &mg->mg_metaslab_tree;
3438         int m = 0;
3439
3440         if (spa_shutting_down(spa) || !metaslab_preload_enabled) {
3441                 taskq_wait_outstanding(mg->mg_taskq, 0);
3442                 return;
3443         }
3444
3445         mutex_enter(&mg->mg_lock);
3446
3447         /*
3448          * Load the next potential metaslabs
3449          */
3450         for (msp = avl_first(t); msp != NULL; msp = AVL_NEXT(t, msp)) {
3451                 ASSERT3P(msp->ms_group, ==, mg);
3452
3453                 /*
3454                  * We preload only the maximum number of metaslabs specified
3455                  * by metaslab_preload_limit. If a metaslab is being forced
3456                  * to condense then we preload it too. This will ensure
3457                  * that force condensing happens in the next txg.
3458                  */
3459                 if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
3460                         continue;
3461                 }
3462
3463                 VERIFY(taskq_dispatch(mg->mg_taskq, metaslab_preload,
3464                     msp, TQ_SLEEP) != TASKQID_INVALID);
3465         }
3466         mutex_exit(&mg->mg_lock);
3467 }
3468
3469 /*
3470  * Determine if the space map's on-disk footprint is past our tolerance for
3471  * inefficiency. We would like to use the following criteria to make our
3472  * decision:
3473  *
3474  * 1. Do not condense if the size of the space map object would dramatically
3475  *    increase as a result of writing out the free space range tree.
3476  *
3477  * 2. Condense if the on on-disk space map representation is at least
3478  *    zfs_condense_pct/100 times the size of the optimal representation
3479  *    (i.e. zfs_condense_pct = 110 and in-core = 1MB, optimal = 1.1MB).
3480  *
3481  * 3. Do not condense if the on-disk size of the space map does not actually
3482  *    decrease.
3483  *
3484  * Unfortunately, we cannot compute the on-disk size of the space map in this
3485  * context because we cannot accurately compute the effects of compression, etc.
3486  * Instead, we apply the heuristic described in the block comment for
3487  * zfs_metaslab_condense_block_threshold - we only condense if the space used
3488  * is greater than a threshold number of blocks.
3489  */
3490 static boolean_t
3491 metaslab_should_condense(metaslab_t *msp)
3492 {
3493         space_map_t *sm = msp->ms_sm;
3494         vdev_t *vd = msp->ms_group->mg_vd;
3495         uint64_t vdev_blocksize = 1 << vd->vdev_ashift;
3496
3497         ASSERT(MUTEX_HELD(&msp->ms_lock));
3498         ASSERT(msp->ms_loaded);
3499         ASSERT(sm != NULL);
3500         ASSERT3U(spa_sync_pass(vd->vdev_spa), ==, 1);
3501
3502         /*
3503          * We always condense metaslabs that are empty and metaslabs for
3504          * which a condense request has been made.
3505          */
3506         if (range_tree_numsegs(msp->ms_allocatable) == 0 ||
3507             msp->ms_condense_wanted)
3508                 return (B_TRUE);
3509
3510         uint64_t record_size = MAX(sm->sm_blksz, vdev_blocksize);
3511         uint64_t object_size = space_map_length(sm);
3512         uint64_t optimal_size = space_map_estimate_optimal_size(sm,
3513             msp->ms_allocatable, SM_NO_VDEVID);
3514
3515         return (object_size >= (optimal_size * zfs_condense_pct / 100) &&
3516             object_size > zfs_metaslab_condense_block_threshold * record_size);
3517 }
3518
3519 /*
3520  * Condense the on-disk space map representation to its minimized form.
3521  * The minimized form consists of a small number of allocations followed
3522  * by the entries of the free range tree (ms_allocatable). The condensed
3523  * spacemap contains all the entries of previous TXGs (including those in
3524  * the pool-wide log spacemaps; thus this is effectively a superset of
3525  * metaslab_flush()), but this TXG's entries still need to be written.
3526  */
3527 static void
3528 metaslab_condense(metaslab_t *msp, dmu_tx_t *tx)
3529 {
3530         range_tree_t *condense_tree;
3531         space_map_t *sm = msp->ms_sm;
3532         uint64_t txg = dmu_tx_get_txg(tx);
3533         spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3534
3535         ASSERT(MUTEX_HELD(&msp->ms_lock));
3536         ASSERT(msp->ms_loaded);
3537         ASSERT(msp->ms_sm != NULL);
3538
3539         /*
3540          * In order to condense the space map, we need to change it so it
3541          * only describes which segments are currently allocated and free.
3542          *
3543          * All the current free space resides in the ms_allocatable, all
3544          * the ms_defer trees, and all the ms_allocating trees. We ignore
3545          * ms_freed because it is empty because we're in sync pass 1. We
3546          * ignore ms_freeing because these changes are not yet reflected
3547          * in the spacemap (they will be written later this txg).
3548          *
3549          * So to truncate the space map to represent all the entries of
3550          * previous TXGs we do the following:
3551          *
3552          * 1] We create a range tree (condense tree) that is 100% empty.
3553          * 2] We add to it all segments found in the ms_defer trees
3554          *    as those segments are marked as free in the original space
3555          *    map. We do the same with the ms_allocating trees for the same
3556          *    reason. Adding these segments should be a relatively
3557          *    inexpensive operation since we expect these trees to have a
3558          *    small number of nodes.
3559          * 3] We vacate any unflushed allocs, since they are not frees we
3560          *    need to add to the condense tree. Then we vacate any
3561          *    unflushed frees as they should already be part of ms_allocatable.
3562          * 4] At this point, we would ideally like to add all segments
3563          *    in the ms_allocatable tree from the condense tree. This way
3564          *    we would write all the entries of the condense tree as the
3565          *    condensed space map, which would only contain freed
3566          *    segments with everything else assumed to be allocated.
3567          *
3568          *    Doing so can be prohibitively expensive as ms_allocatable can
3569          *    be large, and therefore computationally expensive to add to
3570          *    the condense_tree. Instead we first sync out an entry marking
3571          *    everything as allocated, then the condense_tree and then the
3572          *    ms_allocatable, in the condensed space map. While this is not
3573          *    optimal, it is typically close to optimal and more importantly
3574          *    much cheaper to compute.
3575          *
3576          * 5] Finally, as both of the unflushed trees were written to our
3577          *    new and condensed metaslab space map, we basically flushed
3578          *    all the unflushed changes to disk, thus we call
3579          *    metaslab_flush_update().
3580          */
3581         ASSERT3U(spa_sync_pass(spa), ==, 1);
3582         ASSERT(range_tree_is_empty(msp->ms_freed)); /* since it is pass 1 */
3583
3584         zfs_dbgmsg("condensing: txg %llu, msp[%llu] %px, vdev id %llu, "
3585             "spa %s, smp size %llu, segments %lu, forcing condense=%s", txg,
3586             msp->ms_id, msp, msp->ms_group->mg_vd->vdev_id,
3587             spa->spa_name, space_map_length(msp->ms_sm),
3588             range_tree_numsegs(msp->ms_allocatable),
3589             msp->ms_condense_wanted ? "TRUE" : "FALSE");
3590
3591         msp->ms_condense_wanted = B_FALSE;
3592
3593         range_seg_type_t type;
3594         uint64_t shift, start;
3595         type = metaslab_calculate_range_tree_type(msp->ms_group->mg_vd, msp,
3596             &start, &shift);
3597
3598         condense_tree = range_tree_create(NULL, type, NULL, start, shift);
3599
3600         for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3601                 range_tree_walk(msp->ms_defer[t],
3602                     range_tree_add, condense_tree);
3603         }
3604
3605         for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
3606                 range_tree_walk(msp->ms_allocating[(txg + t) & TXG_MASK],
3607                     range_tree_add, condense_tree);
3608         }
3609
3610         ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
3611             metaslab_unflushed_changes_memused(msp));
3612         spa->spa_unflushed_stats.sus_memused -=
3613             metaslab_unflushed_changes_memused(msp);
3614         range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
3615         range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
3616
3617         /*
3618          * We're about to drop the metaslab's lock thus allowing other
3619          * consumers to change it's content. Set the metaslab's ms_condensing
3620          * flag to ensure that allocations on this metaslab do not occur
3621          * while we're in the middle of committing it to disk. This is only
3622          * critical for ms_allocatable as all other range trees use per TXG
3623          * views of their content.
3624          */
3625         msp->ms_condensing = B_TRUE;
3626
3627         mutex_exit(&msp->ms_lock);
3628         uint64_t object = space_map_object(msp->ms_sm);
3629         space_map_truncate(sm,
3630             spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP) ?
3631             zfs_metaslab_sm_blksz_with_log : zfs_metaslab_sm_blksz_no_log, tx);
3632
3633         /*
3634          * space_map_truncate() may have reallocated the spacemap object.
3635          * If so, update the vdev_ms_array.
3636          */
3637         if (space_map_object(msp->ms_sm) != object) {
3638                 object = space_map_object(msp->ms_sm);
3639                 dmu_write(spa->spa_meta_objset,
3640                     msp->ms_group->mg_vd->vdev_ms_array, sizeof (uint64_t) *
3641                     msp->ms_id, sizeof (uint64_t), &object, tx);
3642         }
3643
3644         /*
3645          * Note:
3646          * When the log space map feature is enabled, each space map will
3647          * always have ALLOCS followed by FREES for each sync pass. This is
3648          * typically true even when the log space map feature is disabled,
3649          * except from the case where a metaslab goes through metaslab_sync()
3650          * and gets condensed. In that case the metaslab's space map will have
3651          * ALLOCS followed by FREES (due to condensing) followed by ALLOCS
3652          * followed by FREES (due to space_map_write() in metaslab_sync()) for
3653          * sync pass 1.
3654          */
3655         range_tree_t *tmp_tree = range_tree_create(NULL, type, NULL, start,
3656             shift);
3657         range_tree_add(tmp_tree, msp->ms_start, msp->ms_size);
3658         space_map_write(sm, tmp_tree, SM_ALLOC, SM_NO_VDEVID, tx);
3659         space_map_write(sm, msp->ms_allocatable, SM_FREE, SM_NO_VDEVID, tx);
3660         space_map_write(sm, condense_tree, SM_FREE, SM_NO_VDEVID, tx);
3661
3662         range_tree_vacate(condense_tree, NULL, NULL);
3663         range_tree_destroy(condense_tree);
3664         range_tree_vacate(tmp_tree, NULL, NULL);
3665         range_tree_destroy(tmp_tree);
3666         mutex_enter(&msp->ms_lock);
3667
3668         msp->ms_condensing = B_FALSE;
3669         metaslab_flush_update(msp, tx);
3670 }
3671
3672 /*
3673  * Called when the metaslab has been flushed (its own spacemap now reflects
3674  * all the contents of the pool-wide spacemap log). Updates the metaslab's
3675  * metadata and any pool-wide related log space map data (e.g. summary,
3676  * obsolete logs, etc..) to reflect that.
3677  */
3678 static void
3679 metaslab_flush_update(metaslab_t *msp, dmu_tx_t *tx)
3680 {
3681         metaslab_group_t *mg = msp->ms_group;
3682         spa_t *spa = mg->mg_vd->vdev_spa;
3683
3684         ASSERT(MUTEX_HELD(&msp->ms_lock));
3685
3686         ASSERT3U(spa_sync_pass(spa), ==, 1);
3687         ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
3688         ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
3689
3690         /*
3691          * Just because a metaslab got flushed, that doesn't mean that
3692          * it will pass through metaslab_sync_done(). Thus, make sure to
3693          * update ms_synced_length here in case it doesn't.
3694          */
3695         msp->ms_synced_length = space_map_length(msp->ms_sm);
3696
3697         /*
3698          * We may end up here from metaslab_condense() without the
3699          * feature being active. In that case this is a no-op.
3700          */
3701         if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
3702                 return;
3703
3704         ASSERT(spa_syncing_log_sm(spa) != NULL);
3705         ASSERT(msp->ms_sm != NULL);
3706         ASSERT(metaslab_unflushed_txg(msp) != 0);
3707         ASSERT3P(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL), ==, msp);
3708
3709         VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(spa));
3710
3711         /* update metaslab's position in our flushing tree */
3712         uint64_t ms_prev_flushed_txg = metaslab_unflushed_txg(msp);
3713         mutex_enter(&spa->spa_flushed_ms_lock);
3714         avl_remove(&spa->spa_metaslabs_by_flushed, msp);
3715         metaslab_set_unflushed_txg(msp, spa_syncing_txg(spa), tx);
3716         avl_add(&spa->spa_metaslabs_by_flushed, msp);
3717         mutex_exit(&spa->spa_flushed_ms_lock);
3718
3719         /* update metaslab counts of spa_log_sm_t nodes */
3720         spa_log_sm_decrement_mscount(spa, ms_prev_flushed_txg);
3721         spa_log_sm_increment_current_mscount(spa);
3722
3723         /* cleanup obsolete logs if any */
3724         uint64_t log_blocks_before = spa_log_sm_nblocks(spa);
3725         spa_cleanup_old_sm_logs(spa, tx);
3726         uint64_t log_blocks_after = spa_log_sm_nblocks(spa);
3727         VERIFY3U(log_blocks_after, <=, log_blocks_before);
3728
3729         /* update log space map summary */
3730         uint64_t blocks_gone = log_blocks_before - log_blocks_after;
3731         spa_log_summary_add_flushed_metaslab(spa);
3732         spa_log_summary_decrement_mscount(spa, ms_prev_flushed_txg);
3733         spa_log_summary_decrement_blkcount(spa, blocks_gone);
3734 }
3735
3736 boolean_t
3737 metaslab_flush(metaslab_t *msp, dmu_tx_t *tx)
3738 {
3739         spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3740
3741         ASSERT(MUTEX_HELD(&msp->ms_lock));
3742         ASSERT3U(spa_sync_pass(spa), ==, 1);
3743         ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
3744
3745         ASSERT(msp->ms_sm != NULL);
3746         ASSERT(metaslab_unflushed_txg(msp) != 0);
3747         ASSERT(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL) != NULL);
3748
3749         /*
3750          * There is nothing wrong with flushing the same metaslab twice, as
3751          * this codepath should work on that case. However, the current
3752          * flushing scheme makes sure to avoid this situation as we would be
3753          * making all these calls without having anything meaningful to write
3754          * to disk. We assert this behavior here.
3755          */
3756         ASSERT3U(metaslab_unflushed_txg(msp), <, dmu_tx_get_txg(tx));
3757
3758         /*
3759          * We can not flush while loading, because then we would
3760          * not load the ms_unflushed_{allocs,frees}.
3761          */
3762         if (msp->ms_loading)
3763                 return (B_FALSE);
3764
3765         metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3766         metaslab_verify_weight_and_frag(msp);
3767
3768         /*
3769          * Metaslab condensing is effectively flushing. Therefore if the
3770          * metaslab can be condensed we can just condense it instead of
3771          * flushing it.
3772          *
3773          * Note that metaslab_condense() does call metaslab_flush_update()
3774          * so we can just return immediately after condensing. We also
3775          * don't need to care about setting ms_flushing or broadcasting
3776          * ms_flush_cv, even if we temporarily drop the ms_lock in
3777          * metaslab_condense(), as the metaslab is already loaded.
3778          */
3779         if (msp->ms_loaded && metaslab_should_condense(msp)) {
3780                 metaslab_group_t *mg = msp->ms_group;
3781
3782                 /*
3783                  * For all histogram operations below refer to the
3784                  * comments of metaslab_sync() where we follow a
3785                  * similar procedure.
3786                  */
3787                 metaslab_group_histogram_verify(mg);
3788                 metaslab_class_histogram_verify(mg->mg_class);
3789                 metaslab_group_histogram_remove(mg, msp);
3790
3791                 metaslab_condense(msp, tx);
3792
3793                 space_map_histogram_clear(msp->ms_sm);
3794                 space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
3795                 ASSERT(range_tree_is_empty(msp->ms_freed));
3796                 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3797                         space_map_histogram_add(msp->ms_sm,
3798                             msp->ms_defer[t], tx);
3799                 }
3800                 metaslab_aux_histograms_update(msp);
3801
3802                 metaslab_group_histogram_add(mg, msp);
3803                 metaslab_group_histogram_verify(mg);
3804                 metaslab_class_histogram_verify(mg->mg_class);
3805
3806                 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3807
3808                 /*
3809                  * Since we recreated the histogram (and potentially
3810                  * the ms_sm too while condensing) ensure that the
3811                  * weight is updated too because we are not guaranteed
3812                  * that this metaslab is dirty and will go through
3813                  * metaslab_sync_done().
3814                  */
3815                 metaslab_recalculate_weight_and_sort(msp);
3816                 return (B_TRUE);
3817         }
3818
3819         msp->ms_flushing = B_TRUE;
3820         uint64_t sm_len_before = space_map_length(msp->ms_sm);
3821
3822         mutex_exit(&msp->ms_lock);
3823         space_map_write(msp->ms_sm, msp->ms_unflushed_allocs, SM_ALLOC,
3824             SM_NO_VDEVID, tx);
3825         space_map_write(msp->ms_sm, msp->ms_unflushed_frees, SM_FREE,
3826             SM_NO_VDEVID, tx);
3827         mutex_enter(&msp->ms_lock);
3828
3829         uint64_t sm_len_after = space_map_length(msp->ms_sm);
3830         if (zfs_flags & ZFS_DEBUG_LOG_SPACEMAP) {
3831                 zfs_dbgmsg("flushing: txg %llu, spa %s, vdev_id %llu, "
3832                     "ms_id %llu, unflushed_allocs %llu, unflushed_frees %llu, "
3833                     "appended %llu bytes", dmu_tx_get_txg(tx), spa_name(spa),
3834                     msp->ms_group->mg_vd->vdev_id, msp->ms_id,
3835                     range_tree_space(msp->ms_unflushed_allocs),
3836                     range_tree_space(msp->ms_unflushed_frees),
3837                     (sm_len_after - sm_len_before));
3838         }
3839
3840         ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
3841             metaslab_unflushed_changes_memused(msp));
3842         spa->spa_unflushed_stats.sus_memused -=
3843             metaslab_unflushed_changes_memused(msp);
3844         range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
3845         range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
3846
3847         metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3848         metaslab_verify_weight_and_frag(msp);
3849
3850         metaslab_flush_update(msp, tx);
3851
3852         metaslab_verify_space(msp, dmu_tx_get_txg(tx));
3853         metaslab_verify_weight_and_frag(msp);
3854
3855         msp->ms_flushing = B_FALSE;
3856         cv_broadcast(&msp->ms_flush_cv);
3857         return (B_TRUE);
3858 }
3859
3860 /*
3861  * Write a metaslab to disk in the context of the specified transaction group.
3862  */
3863 void
3864 metaslab_sync(metaslab_t *msp, uint64_t txg)
3865 {
3866         metaslab_group_t *mg = msp->ms_group;
3867         vdev_t *vd = mg->mg_vd;
3868         spa_t *spa = vd->vdev_spa;
3869         objset_t *mos = spa_meta_objset(spa);
3870         range_tree_t *alloctree = msp->ms_allocating[txg & TXG_MASK];
3871         dmu_tx_t *tx;
3872
3873         ASSERT(!vd->vdev_ishole);
3874
3875         /*
3876          * This metaslab has just been added so there's no work to do now.
3877          */
3878         if (msp->ms_freeing == NULL) {
3879                 ASSERT3P(alloctree, ==, NULL);
3880                 return;
3881         }
3882
3883         ASSERT3P(alloctree, !=, NULL);
3884         ASSERT3P(msp->ms_freeing, !=, NULL);
3885         ASSERT3P(msp->ms_freed, !=, NULL);
3886         ASSERT3P(msp->ms_checkpointing, !=, NULL);
3887         ASSERT3P(msp->ms_trim, !=, NULL);
3888
3889         /*
3890          * Normally, we don't want to process a metaslab if there are no
3891          * allocations or frees to perform. However, if the metaslab is being
3892          * forced to condense, it's loaded and we're not beyond the final
3893          * dirty txg, we need to let it through. Not condensing beyond the
3894          * final dirty txg prevents an issue where metaslabs that need to be
3895          * condensed but were loaded for other reasons could cause a panic
3896          * here. By only checking the txg in that branch of the conditional,
3897          * we preserve the utility of the VERIFY statements in all other
3898          * cases.
3899          */
3900         if (range_tree_is_empty(alloctree) &&
3901             range_tree_is_empty(msp->ms_freeing) &&
3902             range_tree_is_empty(msp->ms_checkpointing) &&
3903             !(msp->ms_loaded && msp->ms_condense_wanted &&
3904             txg <= spa_final_dirty_txg(spa)))
3905                 return;
3906
3907
3908         VERIFY3U(txg, <=, spa_final_dirty_txg(spa));
3909
3910         /*
3911          * The only state that can actually be changing concurrently
3912          * with metaslab_sync() is the metaslab's ms_allocatable. No
3913          * other thread can be modifying this txg's alloc, freeing,
3914          * freed, or space_map_phys_t.  We drop ms_lock whenever we
3915          * could call into the DMU, because the DMU can call down to
3916          * us (e.g. via zio_free()) at any time.
3917          *
3918          * The spa_vdev_remove_thread() can be reading metaslab state
3919          * concurrently, and it is locked out by the ms_sync_lock.
3920          * Note that the ms_lock is insufficient for this, because it
3921          * is dropped by space_map_write().
3922          */
3923         tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
3924
3925         /*
3926          * Generate a log space map if one doesn't exist already.
3927          */
3928         spa_generate_syncing_log_sm(spa, tx);
3929
3930         if (msp->ms_sm == NULL) {
3931                 uint64_t new_object = space_map_alloc(mos,
3932                     spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP) ?
3933                     zfs_metaslab_sm_blksz_with_log :
3934                     zfs_metaslab_sm_blksz_no_log, tx);
3935                 VERIFY3U(new_object, !=, 0);
3936
3937                 dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
3938                     msp->ms_id, sizeof (uint64_t), &new_object, tx);
3939
3940                 VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
3941                     msp->ms_start, msp->ms_size, vd->vdev_ashift));
3942                 ASSERT(msp->ms_sm != NULL);
3943
3944                 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
3945                 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
3946                 ASSERT0(metaslab_allocated_space(msp));
3947         }
3948
3949         if (metaslab_unflushed_txg(msp) == 0 &&
3950             spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
3951                 ASSERT(spa_syncing_log_sm(spa) != NULL);
3952
3953                 metaslab_set_unflushed_txg(msp, spa_syncing_txg(spa), tx);
3954                 spa_log_sm_increment_current_mscount(spa);
3955                 spa_log_summary_add_flushed_metaslab(spa);
3956
3957                 ASSERT(msp->ms_sm != NULL);
3958                 mutex_enter(&spa->spa_flushed_ms_lock);
3959                 avl_add(&spa->spa_metaslabs_by_flushed, msp);
3960                 mutex_exit(&spa->spa_flushed_ms_lock);
3961
3962                 ASSERT(range_tree_is_empty(msp->ms_unflushed_allocs));
3963                 ASSERT(range_tree_is_empty(msp->ms_unflushed_frees));
3964         }
3965
3966         if (!range_tree_is_empty(msp->ms_checkpointing) &&
3967             vd->vdev_checkpoint_sm == NULL) {
3968                 ASSERT(spa_has_checkpoint(spa));
3969
3970                 uint64_t new_object = space_map_alloc(mos,
3971                     zfs_vdev_standard_sm_blksz, tx);
3972                 VERIFY3U(new_object, !=, 0);
3973
3974                 VERIFY0(space_map_open(&vd->vdev_checkpoint_sm,
3975                     mos, new_object, 0, vd->vdev_asize, vd->vdev_ashift));
3976                 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
3977
3978                 /*
3979                  * We save the space map object as an entry in vdev_top_zap
3980                  * so it can be retrieved when the pool is reopened after an
3981                  * export or through zdb.
3982                  */
3983                 VERIFY0(zap_add(vd->vdev_spa->spa_meta_objset,
3984                     vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
3985                     sizeof (new_object), 1, &new_object, tx));
3986         }
3987
3988         mutex_enter(&msp->ms_sync_lock);
3989         mutex_enter(&msp->ms_lock);
3990
3991         /*
3992          * Note: metaslab_condense() clears the space map's histogram.
3993          * Therefore we must verify and remove this histogram before
3994          * condensing.
3995          */
3996         metaslab_group_histogram_verify(mg);
3997         metaslab_class_histogram_verify(mg->mg_class);
3998         metaslab_group_histogram_remove(mg, msp);
3999
4000         if (spa->spa_sync_pass == 1 && msp->ms_loaded &&
4001             metaslab_should_condense(msp))
4002                 metaslab_condense(msp, tx);
4003
4004         /*
4005          * We'll be going to disk to sync our space accounting, thus we
4006          * drop the ms_lock during that time so allocations coming from
4007          * open-context (ZIL) for future TXGs do not block.
4008          */
4009         mutex_exit(&msp->ms_lock);
4010         space_map_t *log_sm = spa_syncing_log_sm(spa);
4011         if (log_sm != NULL) {
4012                 ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP));
4013
4014                 space_map_write(log_sm, alloctree, SM_ALLOC,
4015                     vd->vdev_id, tx);
4016                 space_map_write(log_sm, msp->ms_freeing, SM_FREE,
4017                     vd->vdev_id, tx);
4018                 mutex_enter(&msp->ms_lock);
4019
4020                 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
4021                     metaslab_unflushed_changes_memused(msp));
4022                 spa->spa_unflushed_stats.sus_memused -=
4023                     metaslab_unflushed_changes_memused(msp);
4024                 range_tree_remove_xor_add(alloctree,
4025                     msp->ms_unflushed_frees, msp->ms_unflushed_allocs);
4026                 range_tree_remove_xor_add(msp->ms_freeing,
4027                     msp->ms_unflushed_allocs, msp->ms_unflushed_frees);
4028                 spa->spa_unflushed_stats.sus_memused +=
4029                     metaslab_unflushed_changes_memused(msp);
4030         } else {
4031                 ASSERT(!spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP));
4032
4033                 space_map_write(msp->ms_sm, alloctree, SM_ALLOC,
4034                     SM_NO_VDEVID, tx);
4035                 space_map_write(msp->ms_sm, msp->ms_freeing, SM_FREE,
4036                     SM_NO_VDEVID, tx);
4037                 mutex_enter(&msp->ms_lock);
4038         }
4039
4040         msp->ms_allocated_space += range_tree_space(alloctree);
4041         ASSERT3U(msp->ms_allocated_space, >=,
4042             range_tree_space(msp->ms_freeing));
4043         msp->ms_allocated_space -= range_tree_space(msp->ms_freeing);
4044
4045         if (!range_tree_is_empty(msp->ms_checkpointing)) {
4046                 ASSERT(spa_has_checkpoint(spa));
4047                 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
4048
4049                 /*
4050                  * Since we are doing writes to disk and the ms_checkpointing
4051                  * tree won't be changing during that time, we drop the
4052                  * ms_lock while writing to the checkpoint space map, for the
4053                  * same reason mentioned above.
4054                  */
4055                 mutex_exit(&msp->ms_lock);
4056                 space_map_write(vd->vdev_checkpoint_sm,
4057                     msp->ms_checkpointing, SM_FREE, SM_NO_VDEVID, tx);
4058                 mutex_enter(&msp->ms_lock);
4059
4060                 spa->spa_checkpoint_info.sci_dspace +=
4061                     range_tree_space(msp->ms_checkpointing);
4062                 vd->vdev_stat.vs_checkpoint_space +=
4063                     range_tree_space(msp->ms_checkpointing);
4064                 ASSERT3U(vd->vdev_stat.vs_checkpoint_space, ==,
4065                     -space_map_allocated(vd->vdev_checkpoint_sm));
4066
4067                 range_tree_vacate(msp->ms_checkpointing, NULL, NULL);
4068         }
4069
4070         if (msp->ms_loaded) {
4071                 /*
4072                  * When the space map is loaded, we have an accurate
4073                  * histogram in the range tree. This gives us an opportunity
4074                  * to bring the space map's histogram up-to-date so we clear
4075                  * it first before updating it.
4076                  */
4077                 space_map_histogram_clear(msp->ms_sm);
4078                 space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
4079
4080                 /*
4081                  * Since we've cleared the histogram we need to add back
4082                  * any free space that has already been processed, plus
4083                  * any deferred space. This allows the on-disk histogram
4084                  * to accurately reflect all free space even if some space
4085                  * is not yet available for allocation (i.e. deferred).
4086                  */
4087                 space_map_histogram_add(msp->ms_sm, msp->ms_freed, tx);
4088
4089                 /*
4090                  * Add back any deferred free space that has not been
4091                  * added back into the in-core free tree yet. This will
4092                  * ensure that we don't end up with a space map histogram
4093                  * that is completely empty unless the metaslab is fully
4094                  * allocated.
4095                  */
4096                 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
4097                         space_map_histogram_add(msp->ms_sm,
4098                             msp->ms_defer[t], tx);
4099                 }
4100         }
4101
4102         /*
4103          * Always add the free space from this sync pass to the space
4104          * map histogram. We want to make sure that the on-disk histogram
4105          * accounts for all free space. If the space map is not loaded,
4106          * then we will lose some accuracy but will correct it the next
4107          * time we load the space map.
4108          */
4109         space_map_histogram_add(msp->ms_sm, msp->ms_freeing, tx);
4110         metaslab_aux_histograms_update(msp);
4111
4112         metaslab_group_histogram_add(mg, msp);
4113         metaslab_group_histogram_verify(mg);
4114         metaslab_class_histogram_verify(mg->mg_class);
4115
4116         /*
4117          * For sync pass 1, we avoid traversing this txg's free range tree
4118          * and instead will just swap the pointers for freeing and freed.
4119          * We can safely do this since the freed_tree is guaranteed to be
4120          * empty on the initial pass.
4121          *
4122          * Keep in mind that even if we are currently using a log spacemap
4123          * we want current frees to end up in the ms_allocatable (but not
4124          * get appended to the ms_sm) so their ranges can be reused as usual.
4125          */
4126         if (spa_sync_pass(spa) == 1) {
4127                 range_tree_swap(&msp->ms_freeing, &msp->ms_freed);
4128                 ASSERT0(msp->ms_allocated_this_txg);
4129         } else {
4130                 range_tree_vacate(msp->ms_freeing,
4131                     range_tree_add, msp->ms_freed);
4132         }
4133         msp->ms_allocated_this_txg += range_tree_space(alloctree);
4134         range_tree_vacate(alloctree, NULL, NULL);
4135
4136         ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
4137         ASSERT0(range_tree_space(msp->ms_allocating[TXG_CLEAN(txg)
4138             & TXG_MASK]));
4139         ASSERT0(range_tree_space(msp->ms_freeing));
4140         ASSERT0(range_tree_space(msp->ms_checkpointing));
4141
4142         mutex_exit(&msp->ms_lock);
4143
4144         /*
4145          * Verify that the space map object ID has been recorded in the
4146          * vdev_ms_array.
4147          */
4148         uint64_t object;
4149         VERIFY0(dmu_read(mos, vd->vdev_ms_array,
4150             msp->ms_id * sizeof (uint64_t), sizeof (uint64_t), &object, 0));
4151         VERIFY3U(object, ==, space_map_object(msp->ms_sm));
4152
4153         mutex_exit(&msp->ms_sync_lock);
4154         dmu_tx_commit(tx);
4155 }
4156
4157 static void
4158 metaslab_evict(metaslab_t *msp, uint64_t txg)
4159 {
4160         if (!msp->ms_loaded || msp->ms_disabled != 0)
4161                 return;
4162
4163         for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
4164                 VERIFY0(range_tree_space(
4165                     msp->ms_allocating[(txg + t) & TXG_MASK]));
4166         }
4167         if (msp->ms_allocator != -1)
4168                 metaslab_passivate(msp, msp->ms_weight & ~METASLAB_ACTIVE_MASK);
4169
4170         if (!metaslab_debug_unload)
4171                 metaslab_unload(msp);
4172 }
4173
4174 /*
4175  * Called after a transaction group has completely synced to mark
4176  * all of the metaslab's free space as usable.
4177  */
4178 void
4179 metaslab_sync_done(metaslab_t *msp, uint64_t txg)
4180 {
4181         metaslab_group_t *mg = msp->ms_group;
4182         vdev_t *vd = mg->mg_vd;
4183         spa_t *spa = vd->vdev_spa;
4184         range_tree_t **defer_tree;
4185         int64_t alloc_delta, defer_delta;
4186         boolean_t defer_allowed = B_TRUE;
4187
4188         ASSERT(!vd->vdev_ishole);
4189
4190         mutex_enter(&msp->ms_lock);
4191
4192         /*
4193          * If this metaslab is just becoming available, initialize its
4194          * range trees and add its capacity to the vdev.
4195          */
4196         if (msp->ms_freed == NULL) {
4197                 range_seg_type_t type;
4198                 uint64_t shift, start;
4199                 type = metaslab_calculate_range_tree_type(vd, msp, &start,
4200                     &shift);
4201
4202                 for (int t = 0; t < TXG_SIZE; t++) {
4203                         ASSERT(msp->ms_allocating[t] == NULL);
4204
4205                         msp->ms_allocating[t] = range_tree_create(NULL, type,
4206                             NULL, start, shift);
4207                 }
4208
4209                 ASSERT3P(msp->ms_freeing, ==, NULL);
4210                 msp->ms_freeing = range_tree_create(NULL, type, NULL, start,
4211                     shift);
4212
4213                 ASSERT3P(msp->ms_freed, ==, NULL);
4214                 msp->ms_freed = range_tree_create(NULL, type, NULL, start,
4215                     shift);
4216
4217                 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
4218                         ASSERT3P(msp->ms_defer[t], ==, NULL);
4219                         msp->ms_defer[t] = range_tree_create(NULL, type, NULL,
4220                             start, shift);
4221                 }
4222
4223                 ASSERT3P(msp->ms_checkpointing, ==, NULL);
4224                 msp->ms_checkpointing = range_tree_create(NULL, type, NULL,
4225                     start, shift);
4226
4227                 ASSERT3P(msp->ms_unflushed_allocs, ==, NULL);
4228                 msp->ms_unflushed_allocs = range_tree_create(NULL, type, NULL,
4229                     start, shift);
4230
4231                 metaslab_rt_arg_t *mrap = kmem_zalloc(sizeof (*mrap), KM_SLEEP);
4232                 mrap->mra_bt = &msp->ms_unflushed_frees_by_size;
4233                 mrap->mra_floor_shift = metaslab_by_size_min_shift;
4234                 ASSERT3P(msp->ms_unflushed_frees, ==, NULL);
4235                 msp->ms_unflushed_frees = range_tree_create(&metaslab_rt_ops,
4236                     type, mrap, start, shift);
4237
4238                 metaslab_space_update(vd, mg->mg_class, 0, 0, msp->ms_size);
4239         }
4240         ASSERT0(range_tree_space(msp->ms_freeing));
4241         ASSERT0(range_tree_space(msp->ms_checkpointing));
4242
4243         defer_tree = &msp->ms_defer[txg % TXG_DEFER_SIZE];
4244
4245         uint64_t free_space = metaslab_class_get_space(spa_normal_class(spa)) -
4246             metaslab_class_get_alloc(spa_normal_class(spa));
4247         if (free_space <= spa_get_slop_space(spa) || vd->vdev_removing) {
4248                 defer_allowed = B_FALSE;
4249         }
4250
4251         defer_delta = 0;
4252         alloc_delta = msp->ms_allocated_this_txg -
4253             range_tree_space(msp->ms_freed);
4254
4255         if (defer_allowed) {
4256                 defer_delta = range_tree_space(msp->ms_freed) -
4257                     range_tree_space(*defer_tree);
4258         } else {
4259                 defer_delta -= range_tree_space(*defer_tree);
4260         }
4261         metaslab_space_update(vd, mg->mg_class, alloc_delta + defer_delta,
4262             defer_delta, 0);
4263
4264         if (spa_syncing_log_sm(spa) == NULL) {
4265                 /*
4266                  * If there's a metaslab_load() in progress and we don't have
4267                  * a log space map, it means that we probably wrote to the
4268                  * metaslab's space map. If this is the case, we need to
4269                  * make sure that we wait for the load to complete so that we
4270                  * have a consistent view at the in-core side of the metaslab.
4271                  */
4272                 metaslab_load_wait(msp);
4273         } else {
4274                 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
4275         }
4276
4277         /*
4278          * When auto-trimming is enabled, free ranges which are added to
4279          * ms_allocatable are also be added to ms_trim.  The ms_trim tree is
4280          * periodically consumed by the vdev_autotrim_thread() which issues
4281          * trims for all ranges and then vacates the tree.  The ms_trim tree
4282          * can be discarded at any time with the sole consequence of recent
4283          * frees not being trimmed.
4284          */
4285         if (spa_get_autotrim(spa) == SPA_AUTOTRIM_ON) {
4286                 range_tree_walk(*defer_tree, range_tree_add, msp->ms_trim);
4287                 if (!defer_allowed) {
4288                         range_tree_walk(msp->ms_freed, range_tree_add,
4289                             msp->ms_trim);
4290                 }
4291         } else {
4292                 range_tree_vacate(msp->ms_trim, NULL, NULL);
4293         }
4294
4295         /*
4296          * Move the frees from the defer_tree back to the free
4297          * range tree (if it's loaded). Swap the freed_tree and
4298          * the defer_tree -- this is safe to do because we've
4299          * just emptied out the defer_tree.
4300          */
4301         range_tree_vacate(*defer_tree,
4302             msp->ms_loaded ? range_tree_add : NULL, msp->ms_allocatable);
4303         if (defer_allowed) {
4304                 range_tree_swap(&msp->ms_freed, defer_tree);
4305         } else {
4306                 range_tree_vacate(msp->ms_freed,
4307                     msp->ms_loaded ? range_tree_add : NULL,
4308                     msp->ms_allocatable);
4309         }
4310
4311         msp->ms_synced_length = space_map_length(msp->ms_sm);
4312
4313         msp->ms_deferspace += defer_delta;
4314         ASSERT3S(msp->ms_deferspace, >=, 0);
4315         ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
4316         if (msp->ms_deferspace != 0) {
4317                 /*
4318                  * Keep syncing this metaslab until all deferred frees
4319                  * are back in circulation.
4320                  */
4321                 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
4322         }
4323         metaslab_aux_histograms_update_done(msp, defer_allowed);
4324
4325         if (msp->ms_new) {
4326                 msp->ms_new = B_FALSE;
4327                 mutex_enter(&mg->mg_lock);
4328                 mg->mg_ms_ready++;
4329                 mutex_exit(&mg->mg_lock);
4330         }
4331
4332         /*
4333          * Re-sort metaslab within its group now that we've adjusted
4334          * its allocatable space.
4335          */
4336         metaslab_recalculate_weight_and_sort(msp);
4337
4338         ASSERT0(range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
4339         ASSERT0(range_tree_space(msp->ms_freeing));
4340         ASSERT0(range_tree_space(msp->ms_freed));
4341         ASSERT0(range_tree_space(msp->ms_checkpointing));
4342         msp->ms_allocating_total -= msp->ms_allocated_this_txg;
4343         msp->ms_allocated_this_txg = 0;
4344         mutex_exit(&msp->ms_lock);
4345 }
4346
4347 void
4348 metaslab_sync_reassess(metaslab_group_t *mg)
4349 {
4350         spa_t *spa = mg->mg_class->mc_spa;
4351
4352         spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
4353         metaslab_group_alloc_update(mg);
4354         mg->mg_fragmentation = metaslab_group_fragmentation(mg);
4355
4356         /*
4357          * Preload the next potential metaslabs but only on active
4358          * metaslab groups. We can get into a state where the metaslab
4359          * is no longer active since we dirty metaslabs as we remove a
4360          * a device, thus potentially making the metaslab group eligible
4361          * for preloading.
4362          */
4363         if (mg->mg_activation_count > 0) {
4364                 metaslab_group_preload(mg);
4365         }
4366         spa_config_exit(spa, SCL_ALLOC, FTAG);
4367 }
4368
4369 /*
4370  * When writing a ditto block (i.e. more than one DVA for a given BP) on
4371  * the same vdev as an existing DVA of this BP, then try to allocate it
4372  * on a different metaslab than existing DVAs (i.e. a unique metaslab).
4373  */
4374 static boolean_t
4375 metaslab_is_unique(metaslab_t *msp, dva_t *dva)
4376 {
4377         uint64_t dva_ms_id;
4378
4379         if (DVA_GET_ASIZE(dva) == 0)
4380                 return (B_TRUE);
4381
4382         if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
4383                 return (B_TRUE);
4384
4385         dva_ms_id = DVA_GET_OFFSET(dva) >> msp->ms_group->mg_vd->vdev_ms_shift;
4386
4387         return (msp->ms_id != dva_ms_id);
4388 }
4389
4390 /*
4391  * ==========================================================================
4392  * Metaslab allocation tracing facility
4393  * ==========================================================================
4394  */
4395 #ifdef _METASLAB_TRACING
4396
4397 /*
4398  * Add an allocation trace element to the allocation tracing list.
4399  */
4400 static void
4401 metaslab_trace_add(zio_alloc_list_t *zal, metaslab_group_t *mg,
4402     metaslab_t *msp, uint64_t psize, uint32_t dva_id, uint64_t offset,
4403     int allocator)
4404 {
4405         metaslab_alloc_trace_t *mat;
4406
4407         if (!metaslab_trace_enabled)
4408                 return;
4409
4410         /*
4411          * When the tracing list reaches its maximum we remove
4412          * the second element in the list before adding a new one.
4413          * By removing the second element we preserve the original
4414          * entry as a clue to what allocations steps have already been
4415          * performed.
4416          */
4417         if (zal->zal_size == metaslab_trace_max_entries) {
4418                 metaslab_alloc_trace_t *mat_next;
4419 #ifdef ZFS_DEBUG
4420                 panic("too many entries in allocation list");
4421 #endif
4422                 METASLABSTAT_BUMP(metaslabstat_trace_over_limit);
4423                 zal->zal_size--;
4424                 mat_next = list_next(&zal->zal_list, list_head(&zal->zal_list));
4425                 list_remove(&zal->zal_list, mat_next);
4426                 kmem_cache_free(metaslab_alloc_trace_cache, mat_next);
4427         }
4428
4429         mat = kmem_cache_alloc(metaslab_alloc_trace_cache, KM_SLEEP);
4430         list_link_init(&mat->mat_list_node);
4431         mat->mat_mg = mg;
4432         mat->mat_msp = msp;
4433         mat->mat_size = psize;
4434         mat->mat_dva_id = dva_id;
4435         mat->mat_offset = offset;
4436         mat->mat_weight = 0;
4437         mat->mat_allocator = allocator;
4438
4439         if (msp != NULL)
4440                 mat->mat_weight = msp->ms_weight;
4441
4442         /*
4443          * The list is part of the zio so locking is not required. Only
4444          * a single thread will perform allocations for a given zio.
4445          */
4446         list_insert_tail(&zal->zal_list, mat);
4447         zal->zal_size++;
4448
4449         ASSERT3U(zal->zal_size, <=, metaslab_trace_max_entries);
4450 }
4451
4452 void
4453 metaslab_trace_init(zio_alloc_list_t *zal)
4454 {
4455         list_create(&zal->zal_list, sizeof (metaslab_alloc_trace_t),
4456             offsetof(metaslab_alloc_trace_t, mat_list_node));
4457         zal->zal_size = 0;
4458 }
4459
4460 void
4461 metaslab_trace_fini(zio_alloc_list_t *zal)
4462 {
4463         metaslab_alloc_trace_t *mat;
4464
4465         while ((mat = list_remove_head(&zal->zal_list)) != NULL)
4466                 kmem_cache_free(metaslab_alloc_trace_cache, mat);
4467         list_destroy(&zal->zal_list);
4468         zal->zal_size = 0;
4469 }
4470 #else
4471
4472 #define metaslab_trace_add(zal, mg, msp, psize, id, off, alloc)
4473
4474 void
4475 metaslab_trace_init(zio_alloc_list_t *zal)
4476 {
4477 }
4478
4479 void
4480 metaslab_trace_fini(zio_alloc_list_t *zal)
4481 {
4482 }
4483
4484 #endif /* _METASLAB_TRACING */
4485
4486 /*
4487  * ==========================================================================
4488  * Metaslab block operations
4489  * ==========================================================================
4490  */
4491
4492 static void
4493 metaslab_group_alloc_increment(spa_t *spa, uint64_t vdev, void *tag, int flags,
4494     int allocator)
4495 {
4496         if (!(flags & METASLAB_ASYNC_ALLOC) ||
4497             (flags & METASLAB_DONT_THROTTLE))
4498                 return;
4499
4500         metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
4501         if (!mg->mg_class->mc_alloc_throttle_enabled)
4502                 return;
4503
4504         metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4505         (void) zfs_refcount_add(&mga->mga_alloc_queue_depth, tag);
4506 }
4507
4508 static void
4509 metaslab_group_increment_qdepth(metaslab_group_t *mg, int allocator)
4510 {
4511         metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4512         uint64_t max = mg->mg_max_alloc_queue_depth;
4513         uint64_t cur = mga->mga_cur_max_alloc_queue_depth;
4514         while (cur < max) {
4515                 if (atomic_cas_64(&mga->mga_cur_max_alloc_queue_depth,
4516                     cur, cur + 1) == cur) {
4517                         atomic_inc_64(
4518                             &mg->mg_class->mc_alloc_max_slots[allocator]);
4519                         return;
4520                 }
4521                 cur = mga->mga_cur_max_alloc_queue_depth;
4522         }
4523 }
4524
4525 void
4526 metaslab_group_alloc_decrement(spa_t *spa, uint64_t vdev, void *tag, int flags,
4527     int allocator, boolean_t io_complete)
4528 {
4529         if (!(flags & METASLAB_ASYNC_ALLOC) ||
4530             (flags & METASLAB_DONT_THROTTLE))
4531                 return;
4532
4533         metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
4534         if (!mg->mg_class->mc_alloc_throttle_enabled)
4535                 return;
4536
4537         metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4538         (void) zfs_refcount_remove(&mga->mga_alloc_queue_depth, tag);
4539         if (io_complete)
4540                 metaslab_group_increment_qdepth(mg, allocator);
4541 }
4542
4543 void
4544 metaslab_group_alloc_verify(spa_t *spa, const blkptr_t *bp, void *tag,
4545     int allocator)
4546 {
4547 #ifdef ZFS_DEBUG
4548         const dva_t *dva = bp->blk_dva;
4549         int ndvas = BP_GET_NDVAS(bp);
4550
4551         for (int d = 0; d < ndvas; d++) {
4552                 uint64_t vdev = DVA_GET_VDEV(&dva[d]);
4553                 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
4554                 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4555                 VERIFY(zfs_refcount_not_held(&mga->mga_alloc_queue_depth, tag));
4556         }
4557 #endif
4558 }
4559
4560 static uint64_t
4561 metaslab_block_alloc(metaslab_t *msp, uint64_t size, uint64_t txg)
4562 {
4563         uint64_t start;
4564         range_tree_t *rt = msp->ms_allocatable;
4565         metaslab_class_t *mc = msp->ms_group->mg_class;
4566
4567         ASSERT(MUTEX_HELD(&msp->ms_lock));
4568         VERIFY(!msp->ms_condensing);
4569         VERIFY0(msp->ms_disabled);
4570
4571         start = mc->mc_ops->msop_alloc(msp, size);
4572         if (start != -1ULL) {
4573                 metaslab_group_t *mg = msp->ms_group;
4574                 vdev_t *vd = mg->mg_vd;
4575
4576                 VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
4577                 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
4578                 VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
4579                 range_tree_remove(rt, start, size);
4580                 range_tree_clear(msp->ms_trim, start, size);
4581
4582                 if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
4583                         vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
4584
4585                 range_tree_add(msp->ms_allocating[txg & TXG_MASK], start, size);
4586                 msp->ms_allocating_total += size;
4587
4588                 /* Track the last successful allocation */
4589                 msp->ms_alloc_txg = txg;
4590                 metaslab_verify_space(msp, txg);
4591         }
4592
4593         /*
4594          * Now that we've attempted the allocation we need to update the
4595          * metaslab's maximum block size since it may have changed.
4596          */
4597         msp->ms_max_size = metaslab_largest_allocatable(msp);
4598         return (start);
4599 }
4600
4601 /*
4602  * Find the metaslab with the highest weight that is less than what we've
4603  * already tried.  In the common case, this means that we will examine each
4604  * metaslab at most once. Note that concurrent callers could reorder metaslabs
4605  * by activation/passivation once we have dropped the mg_lock. If a metaslab is
4606  * activated by another thread, and we fail to allocate from the metaslab we
4607  * have selected, we may not try the newly-activated metaslab, and instead
4608  * activate another metaslab.  This is not optimal, but generally does not cause
4609  * any problems (a possible exception being if every metaslab is completely full
4610  * except for the newly-activated metaslab which we fail to examine).
4611  */
4612 static metaslab_t *
4613 find_valid_metaslab(metaslab_group_t *mg, uint64_t activation_weight,
4614     dva_t *dva, int d, boolean_t want_unique, uint64_t asize, int allocator,
4615     boolean_t try_hard, zio_alloc_list_t *zal, metaslab_t *search,
4616     boolean_t *was_active)
4617 {
4618         avl_index_t idx;
4619         avl_tree_t *t = &mg->mg_metaslab_tree;
4620         metaslab_t *msp = avl_find(t, search, &idx);
4621         if (msp == NULL)
4622                 msp = avl_nearest(t, idx, AVL_AFTER);
4623
4624         for (; msp != NULL; msp = AVL_NEXT(t, msp)) {
4625                 int i;
4626                 if (!metaslab_should_allocate(msp, asize, try_hard)) {
4627                         metaslab_trace_add(zal, mg, msp, asize, d,
4628                             TRACE_TOO_SMALL, allocator);
4629                         continue;
4630                 }
4631
4632                 /*
4633                  * If the selected metaslab is condensing or disabled,
4634                  * skip it.
4635                  */
4636                 if (msp->ms_condensing || msp->ms_disabled > 0)
4637                         continue;
4638
4639                 *was_active = msp->ms_allocator != -1;
4640                 /*
4641                  * If we're activating as primary, this is our first allocation
4642                  * from this disk, so we don't need to check how close we are.
4643                  * If the metaslab under consideration was already active,
4644                  * we're getting desperate enough to steal another allocator's
4645                  * metaslab, so we still don't care about distances.
4646                  */
4647                 if (activation_weight == METASLAB_WEIGHT_PRIMARY || *was_active)
4648                         break;
4649
4650                 for (i = 0; i < d; i++) {
4651                         if (want_unique &&
4652                             !metaslab_is_unique(msp, &dva[i]))
4653                                 break;  /* try another metaslab */
4654                 }
4655                 if (i == d)
4656                         break;
4657         }
4658
4659         if (msp != NULL) {
4660                 search->ms_weight = msp->ms_weight;
4661                 search->ms_start = msp->ms_start + 1;
4662                 search->ms_allocator = msp->ms_allocator;
4663                 search->ms_primary = msp->ms_primary;
4664         }
4665         return (msp);
4666 }
4667
4668 static void
4669 metaslab_active_mask_verify(metaslab_t *msp)
4670 {
4671         ASSERT(MUTEX_HELD(&msp->ms_lock));
4672
4673         if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
4674                 return;
4675
4676         if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0)
4677                 return;
4678
4679         if (msp->ms_weight & METASLAB_WEIGHT_PRIMARY) {
4680                 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
4681                 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_CLAIM);
4682                 VERIFY3S(msp->ms_allocator, !=, -1);
4683                 VERIFY(msp->ms_primary);
4684                 return;
4685         }
4686
4687         if (msp->ms_weight & METASLAB_WEIGHT_SECONDARY) {
4688                 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
4689                 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_CLAIM);
4690                 VERIFY3S(msp->ms_allocator, !=, -1);
4691                 VERIFY(!msp->ms_primary);
4692                 return;
4693         }
4694
4695         if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
4696                 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
4697                 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
4698                 VERIFY3S(msp->ms_allocator, ==, -1);
4699                 return;
4700         }
4701 }
4702
4703 /* ARGSUSED */
4704 static uint64_t
4705 metaslab_group_alloc_normal(metaslab_group_t *mg, zio_alloc_list_t *zal,
4706     uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva, int d,
4707     int allocator, boolean_t try_hard)
4708 {
4709         metaslab_t *msp = NULL;
4710         uint64_t offset = -1ULL;
4711
4712         uint64_t activation_weight = METASLAB_WEIGHT_PRIMARY;
4713         for (int i = 0; i < d; i++) {
4714                 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
4715                     DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
4716                         activation_weight = METASLAB_WEIGHT_SECONDARY;
4717                 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
4718                     DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
4719                         activation_weight = METASLAB_WEIGHT_CLAIM;
4720                         break;
4721                 }
4722         }
4723
4724         /*
4725          * If we don't have enough metaslabs active to fill the entire array, we
4726          * just use the 0th slot.
4727          */
4728         if (mg->mg_ms_ready < mg->mg_allocators * 3)
4729                 allocator = 0;
4730         metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4731
4732         ASSERT3U(mg->mg_vd->vdev_ms_count, >=, 2);
4733
4734         metaslab_t *search = kmem_alloc(sizeof (*search), KM_SLEEP);
4735         search->ms_weight = UINT64_MAX;
4736         search->ms_start = 0;
4737         /*
4738          * At the end of the metaslab tree are the already-active metaslabs,
4739          * first the primaries, then the secondaries. When we resume searching
4740          * through the tree, we need to consider ms_allocator and ms_primary so
4741          * we start in the location right after where we left off, and don't
4742          * accidentally loop forever considering the same metaslabs.
4743          */
4744         search->ms_allocator = -1;
4745         search->ms_primary = B_TRUE;
4746         for (;;) {
4747                 boolean_t was_active = B_FALSE;
4748
4749                 mutex_enter(&mg->mg_lock);
4750
4751                 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
4752                     mga->mga_primary != NULL) {
4753                         msp = mga->mga_primary;
4754
4755                         /*
4756                          * Even though we don't hold the ms_lock for the
4757                          * primary metaslab, those fields should not
4758                          * change while we hold the mg_lock. Thus it is
4759                          * safe to make assertions on them.
4760                          */
4761                         ASSERT(msp->ms_primary);
4762                         ASSERT3S(msp->ms_allocator, ==, allocator);
4763                         ASSERT(msp->ms_loaded);
4764
4765                         was_active = B_TRUE;
4766                         ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
4767                 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
4768                     mga->mga_secondary != NULL) {
4769                         msp = mga->mga_secondary;
4770
4771                         /*
4772                          * See comment above about the similar assertions
4773                          * for the primary metaslab.
4774                          */
4775                         ASSERT(!msp->ms_primary);
4776                         ASSERT3S(msp->ms_allocator, ==, allocator);
4777                         ASSERT(msp->ms_loaded);
4778
4779                         was_active = B_TRUE;
4780                         ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
4781                 } else {
4782                         msp = find_valid_metaslab(mg, activation_weight, dva, d,
4783                             want_unique, asize, allocator, try_hard, zal,
4784                             search, &was_active);
4785                 }
4786
4787                 mutex_exit(&mg->mg_lock);
4788                 if (msp == NULL) {
4789                         kmem_free(search, sizeof (*search));
4790                         return (-1ULL);
4791                 }
4792                 mutex_enter(&msp->ms_lock);
4793
4794                 metaslab_active_mask_verify(msp);
4795
4796                 /*
4797                  * This code is disabled out because of issues with
4798                  * tracepoints in non-gpl kernel modules.
4799                  */
4800 #if 0
4801                 DTRACE_PROBE3(ms__activation__attempt,
4802                     metaslab_t *, msp, uint64_t, activation_weight,
4803                     boolean_t, was_active);
4804 #endif
4805
4806                 /*
4807                  * Ensure that the metaslab we have selected is still
4808                  * capable of handling our request. It's possible that
4809                  * another thread may have changed the weight while we
4810                  * were blocked on the metaslab lock. We check the
4811                  * active status first to see if we need to set_selected_txg
4812                  * a new metaslab.
4813                  */
4814                 if (was_active && !(msp->ms_weight & METASLAB_ACTIVE_MASK)) {
4815                         ASSERT3S(msp->ms_allocator, ==, -1);
4816                         mutex_exit(&msp->ms_lock);
4817                         continue;
4818                 }
4819
4820                 /*
4821                  * If the metaslab was activated for another allocator
4822                  * while we were waiting in the ms_lock above, or it's
4823                  * a primary and we're seeking a secondary (or vice versa),
4824                  * we go back and select a new metaslab.
4825                  */
4826                 if (!was_active && (msp->ms_weight & METASLAB_ACTIVE_MASK) &&
4827                     (msp->ms_allocator != -1) &&
4828                     (msp->ms_allocator != allocator || ((activation_weight ==
4829                     METASLAB_WEIGHT_PRIMARY) != msp->ms_primary))) {
4830                         ASSERT(msp->ms_loaded);
4831                         ASSERT((msp->ms_weight & METASLAB_WEIGHT_CLAIM) ||
4832                             msp->ms_allocator != -1);
4833                         mutex_exit(&msp->ms_lock);
4834                         continue;
4835                 }
4836
4837                 /*
4838                  * This metaslab was used for claiming regions allocated
4839                  * by the ZIL during pool import. Once these regions are
4840                  * claimed we don't need to keep the CLAIM bit set
4841                  * anymore. Passivate this metaslab to zero its activation
4842                  * mask.
4843                  */
4844                 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM &&
4845                     activation_weight != METASLAB_WEIGHT_CLAIM) {
4846                         ASSERT(msp->ms_loaded);
4847                         ASSERT3S(msp->ms_allocator, ==, -1);
4848                         metaslab_passivate(msp, msp->ms_weight &
4849                             ~METASLAB_WEIGHT_CLAIM);
4850                         mutex_exit(&msp->ms_lock);
4851                         continue;
4852                 }
4853
4854                 metaslab_set_selected_txg(msp, txg);
4855
4856                 int activation_error =
4857                     metaslab_activate(msp, allocator, activation_weight);
4858                 metaslab_active_mask_verify(msp);
4859
4860                 /*
4861                  * If the metaslab was activated by another thread for
4862                  * another allocator or activation_weight (EBUSY), or it
4863                  * failed because another metaslab was assigned as primary
4864                  * for this allocator (EEXIST) we continue using this
4865                  * metaslab for our allocation, rather than going on to a
4866                  * worse metaslab (we waited for that metaslab to be loaded
4867                  * after all).
4868                  *
4869                  * If the activation failed due to an I/O error or ENOSPC we
4870                  * skip to the next metaslab.
4871                  */
4872                 boolean_t activated;
4873                 if (activation_error == 0) {
4874                         activated = B_TRUE;
4875                 } else if (activation_error == EBUSY ||
4876                     activation_error == EEXIST) {
4877                         activated = B_FALSE;
4878                 } else {
4879                         mutex_exit(&msp->ms_lock);
4880                         continue;
4881                 }
4882                 ASSERT(msp->ms_loaded);
4883
4884                 /*
4885                  * Now that we have the lock, recheck to see if we should
4886                  * continue to use this metaslab for this allocation. The
4887                  * the metaslab is now loaded so metaslab_should_allocate()
4888                  * can accurately determine if the allocation attempt should
4889                  * proceed.
4890                  */
4891                 if (!metaslab_should_allocate(msp, asize, try_hard)) {
4892                         /* Passivate this metaslab and select a new one. */
4893                         metaslab_trace_add(zal, mg, msp, asize, d,
4894                             TRACE_TOO_SMALL, allocator);
4895                         goto next;
4896                 }
4897
4898                 /*
4899                  * If this metaslab is currently condensing then pick again
4900                  * as we can't manipulate this metaslab until it's committed
4901                  * to disk. If this metaslab is being initialized, we shouldn't
4902                  * allocate from it since the allocated region might be
4903                  * overwritten after allocation.
4904                  */
4905                 if (msp->ms_condensing) {
4906                         metaslab_trace_add(zal, mg, msp, asize, d,
4907                             TRACE_CONDENSING, allocator);
4908                         if (activated) {
4909                                 metaslab_passivate(msp, msp->ms_weight &
4910                                     ~METASLAB_ACTIVE_MASK);
4911                         }
4912                         mutex_exit(&msp->ms_lock);
4913                         continue;
4914                 } else if (msp->ms_disabled > 0) {
4915                         metaslab_trace_add(zal, mg, msp, asize, d,
4916                             TRACE_DISABLED, allocator);
4917                         if (activated) {
4918                                 metaslab_passivate(msp, msp->ms_weight &
4919                                     ~METASLAB_ACTIVE_MASK);
4920                         }
4921                         mutex_exit(&msp->ms_lock);
4922                         continue;
4923                 }
4924
4925                 offset = metaslab_block_alloc(msp, asize, txg);
4926                 metaslab_trace_add(zal, mg, msp, asize, d, offset, allocator);
4927
4928                 if (offset != -1ULL) {
4929                         /* Proactively passivate the metaslab, if needed */
4930                         if (activated)
4931                                 metaslab_segment_may_passivate(msp);
4932                         break;
4933                 }
4934 next:
4935                 ASSERT(msp->ms_loaded);
4936
4937                 /*
4938                  * This code is disabled out because of issues with
4939                  * tracepoints in non-gpl kernel modules.
4940                  */
4941 #if 0
4942                 DTRACE_PROBE2(ms__alloc__failure, metaslab_t *, msp,
4943                     uint64_t, asize);
4944 #endif
4945
4946                 /*
4947                  * We were unable to allocate from this metaslab so determine
4948                  * a new weight for this metaslab. Now that we have loaded
4949                  * the metaslab we can provide a better hint to the metaslab
4950                  * selector.
4951                  *
4952                  * For space-based metaslabs, we use the maximum block size.
4953                  * This information is only available when the metaslab
4954                  * is loaded and is more accurate than the generic free
4955                  * space weight that was calculated by metaslab_weight().
4956                  * This information allows us to quickly compare the maximum
4957                  * available allocation in the metaslab to the allocation
4958                  * size being requested.
4959                  *
4960                  * For segment-based metaslabs, determine the new weight
4961                  * based on the highest bucket in the range tree. We
4962                  * explicitly use the loaded segment weight (i.e. the range
4963                  * tree histogram) since it contains the space that is
4964                  * currently available for allocation and is accurate
4965                  * even within a sync pass.
4966                  */
4967                 uint64_t weight;
4968                 if (WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
4969                         weight = metaslab_largest_allocatable(msp);
4970                         WEIGHT_SET_SPACEBASED(weight);
4971                 } else {
4972                         weight = metaslab_weight_from_range_tree(msp);
4973                 }
4974
4975                 if (activated) {
4976                         metaslab_passivate(msp, weight);
4977                 } else {
4978                         /*
4979                          * For the case where we use the metaslab that is
4980                          * active for another allocator we want to make
4981                          * sure that we retain the activation mask.
4982                          *
4983                          * Note that we could attempt to use something like
4984                          * metaslab_recalculate_weight_and_sort() that
4985                          * retains the activation mask here. That function
4986                          * uses metaslab_weight() to set the weight though
4987                          * which is not as accurate as the calculations
4988                          * above.
4989                          */
4990                         weight |= msp->ms_weight & METASLAB_ACTIVE_MASK;
4991                         metaslab_group_sort(mg, msp, weight);
4992                 }
4993                 metaslab_active_mask_verify(msp);
4994
4995                 /*
4996                  * We have just failed an allocation attempt, check
4997                  * that metaslab_should_allocate() agrees. Otherwise,
4998                  * we may end up in an infinite loop retrying the same
4999                  * metaslab.
5000                  */
5001                 ASSERT(!metaslab_should_allocate(msp, asize, try_hard));
5002
5003                 mutex_exit(&msp->ms_lock);
5004         }
5005         mutex_exit(&msp->ms_lock);
5006         kmem_free(search, sizeof (*search));
5007         return (offset);
5008 }
5009
5010 static uint64_t
5011 metaslab_group_alloc(metaslab_group_t *mg, zio_alloc_list_t *zal,
5012     uint64_t asize, uint64_t txg, boolean_t want_unique, dva_t *dva, int d,
5013     int allocator, boolean_t try_hard)
5014 {
5015         uint64_t offset;
5016         ASSERT(mg->mg_initialized);
5017
5018         offset = metaslab_group_alloc_normal(mg, zal, asize, txg, want_unique,
5019             dva, d, allocator, try_hard);
5020
5021         mutex_enter(&mg->mg_lock);
5022         if (offset == -1ULL) {
5023                 mg->mg_failed_allocations++;
5024                 metaslab_trace_add(zal, mg, NULL, asize, d,
5025                     TRACE_GROUP_FAILURE, allocator);
5026                 if (asize == SPA_GANGBLOCKSIZE) {
5027                         /*
5028                          * This metaslab group was unable to allocate
5029                          * the minimum gang block size so it must be out of
5030                          * space. We must notify the allocation throttle
5031                          * to start skipping allocation attempts to this
5032                          * metaslab group until more space becomes available.
5033                          * Note: this failure cannot be caused by the
5034                          * allocation throttle since the allocation throttle
5035                          * is only responsible for skipping devices and
5036                          * not failing block allocations.
5037                          */
5038                         mg->mg_no_free_space = B_TRUE;
5039                 }
5040         }
5041         mg->mg_allocations++;
5042         mutex_exit(&mg->mg_lock);
5043         return (offset);
5044 }
5045
5046 /*
5047  * Allocate a block for the specified i/o.
5048  */
5049 int
5050 metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
5051     dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags,
5052     zio_alloc_list_t *zal, int allocator)
5053 {
5054         metaslab_group_t *mg, *fast_mg, *rotor;
5055         vdev_t *vd;
5056         boolean_t try_hard = B_FALSE;
5057
5058         ASSERT(!DVA_IS_VALID(&dva[d]));
5059
5060         /*
5061          * For testing, make some blocks above a certain size be gang blocks.
5062          * This will result in more split blocks when using device removal,
5063          * and a large number of split blocks coupled with ztest-induced
5064          * damage can result in extremely long reconstruction times.  This
5065          * will also test spilling from special to normal.
5066          */
5067         if (psize >= metaslab_force_ganging && (spa_get_random(100) < 3)) {
5068                 metaslab_trace_add(zal, NULL, NULL, psize, d, TRACE_FORCE_GANG,
5069                     allocator);
5070                 return (SET_ERROR(ENOSPC));
5071         }
5072
5073         /*
5074          * Start at the rotor and loop through all mgs until we find something.
5075          * Note that there's no locking on mc_rotor or mc_aliquot because
5076          * nothing actually breaks if we miss a few updates -- we just won't
5077          * allocate quite as evenly.  It all balances out over time.
5078          *
5079          * If we are doing ditto or log blocks, try to spread them across
5080          * consecutive vdevs.  If we're forced to reuse a vdev before we've
5081          * allocated all of our ditto blocks, then try and spread them out on
5082          * that vdev as much as possible.  If it turns out to not be possible,
5083          * gradually lower our standards until anything becomes acceptable.
5084          * Also, allocating on consecutive vdevs (as opposed to random vdevs)
5085          * gives us hope of containing our fault domains to something we're
5086          * able to reason about.  Otherwise, any two top-level vdev failures
5087          * will guarantee the loss of data.  With consecutive allocation,
5088          * only two adjacent top-level vdev failures will result in data loss.
5089          *
5090          * If we are doing gang blocks (hintdva is non-NULL), try to keep
5091          * ourselves on the same vdev as our gang block header.  That
5092          * way, we can hope for locality in vdev_cache, plus it makes our
5093          * fault domains something tractable.
5094          */
5095         if (hintdva) {
5096                 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
5097
5098                 /*
5099                  * It's possible the vdev we're using as the hint no
5100                  * longer exists or its mg has been closed (e.g. by
5101                  * device removal).  Consult the rotor when
5102                  * all else fails.
5103                  */
5104                 if (vd != NULL && vd->vdev_mg != NULL) {
5105                         mg = vd->vdev_mg;
5106
5107                         if (flags & METASLAB_HINTBP_AVOID &&
5108                             mg->mg_next != NULL)
5109                                 mg = mg->mg_next;
5110                 } else {
5111                         mg = mc->mc_rotor;
5112                 }
5113         } else if (d != 0) {
5114                 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
5115                 mg = vd->vdev_mg->mg_next;
5116         } else if (flags & METASLAB_FASTWRITE) {
5117                 mg = fast_mg = mc->mc_rotor;
5118
5119                 do {
5120                         if (fast_mg->mg_vd->vdev_pending_fastwrite <
5121                             mg->mg_vd->vdev_pending_fastwrite)
5122                                 mg = fast_mg;
5123                 } while ((fast_mg = fast_mg->mg_next) != mc->mc_rotor);
5124
5125         } else {
5126                 ASSERT(mc->mc_rotor != NULL);
5127                 mg = mc->mc_rotor;
5128         }
5129
5130         /*
5131          * If the hint put us into the wrong metaslab class, or into a
5132          * metaslab group that has been passivated, just follow the rotor.
5133          */
5134         if (mg->mg_class != mc || mg->mg_activation_count <= 0)
5135                 mg = mc->mc_rotor;
5136
5137         rotor = mg;
5138 top:
5139         do {
5140                 boolean_t allocatable;
5141
5142                 ASSERT(mg->mg_activation_count == 1);
5143                 vd = mg->mg_vd;
5144
5145                 /*
5146                  * Don't allocate from faulted devices.
5147                  */
5148                 if (try_hard) {
5149                         spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
5150                         allocatable = vdev_allocatable(vd);
5151                         spa_config_exit(spa, SCL_ZIO, FTAG);
5152                 } else {
5153                         allocatable = vdev_allocatable(vd);
5154                 }
5155
5156                 /*
5157                  * Determine if the selected metaslab group is eligible
5158                  * for allocations. If we're ganging then don't allow
5159                  * this metaslab group to skip allocations since that would
5160                  * inadvertently return ENOSPC and suspend the pool
5161                  * even though space is still available.
5162                  */
5163                 if (allocatable && !GANG_ALLOCATION(flags) && !try_hard) {
5164                         allocatable = metaslab_group_allocatable(mg, rotor,
5165                             psize, allocator, d);
5166                 }
5167
5168                 if (!allocatable) {
5169                         metaslab_trace_add(zal, mg, NULL, psize, d,
5170                             TRACE_NOT_ALLOCATABLE, allocator);
5171                         goto next;
5172                 }
5173
5174                 ASSERT(mg->mg_initialized);
5175
5176                 /*
5177                  * Avoid writing single-copy data to a failing,
5178                  * non-redundant vdev, unless we've already tried all
5179                  * other vdevs.
5180                  */
5181                 if ((vd->vdev_stat.vs_write_errors > 0 ||
5182                     vd->vdev_state < VDEV_STATE_HEALTHY) &&
5183                     d == 0 && !try_hard && vd->vdev_children == 0) {
5184                         metaslab_trace_add(zal, mg, NULL, psize, d,
5185                             TRACE_VDEV_ERROR, allocator);
5186                         goto next;
5187                 }
5188
5189                 ASSERT(mg->mg_class == mc);
5190
5191                 uint64_t asize = vdev_psize_to_asize(vd, psize);
5192                 ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
5193
5194                 /*
5195                  * If we don't need to try hard, then require that the
5196                  * block be on a different metaslab from any other DVAs
5197                  * in this BP (unique=true).  If we are trying hard, then
5198                  * allow any metaslab to be used (unique=false).
5199                  */
5200                 uint64_t offset = metaslab_group_alloc(mg, zal, asize, txg,
5201                     !try_hard, dva, d, allocator, try_hard);
5202
5203                 if (offset != -1ULL) {
5204                         /*
5205                          * If we've just selected this metaslab group,
5206                          * figure out whether the corresponding vdev is
5207                          * over- or under-used relative to the pool,
5208                          * and set an allocation bias to even it out.
5209                          *
5210                          * Bias is also used to compensate for unequally
5211                          * sized vdevs so that space is allocated fairly.
5212                          */
5213                         if (mc->mc_aliquot == 0 && metaslab_bias_enabled) {
5214                                 vdev_stat_t *vs = &vd->vdev_stat;
5215                                 int64_t vs_free = vs->vs_space - vs->vs_alloc;
5216                                 int64_t mc_free = mc->mc_space - mc->mc_alloc;
5217                                 int64_t ratio;
5218
5219                                 /*
5220                                  * Calculate how much more or less we should
5221                                  * try to allocate from this device during
5222                                  * this iteration around the rotor.
5223                                  *
5224                                  * This basically introduces a zero-centered
5225                                  * bias towards the devices with the most
5226                                  * free space, while compensating for vdev
5227                                  * size differences.
5228                                  *
5229                                  * Examples:
5230                                  *  vdev V1 = 16M/128M
5231                                  *  vdev V2 = 16M/128M
5232                                  *  ratio(V1) = 100% ratio(V2) = 100%
5233                                  *
5234                                  *  vdev V1 = 16M/128M
5235                                  *  vdev V2 = 64M/128M
5236                                  *  ratio(V1) = 127% ratio(V2) =  72%
5237                                  *
5238                                  *  vdev V1 = 16M/128M
5239                                  *  vdev V2 = 64M/512M
5240                                  *  ratio(V1) =  40% ratio(V2) = 160%
5241                                  */
5242                                 ratio = (vs_free * mc->mc_alloc_groups * 100) /
5243                                     (mc_free + 1);
5244                                 mg->mg_bias = ((ratio - 100) *
5245                                     (int64_t)mg->mg_aliquot) / 100;
5246                         } else if (!metaslab_bias_enabled) {
5247                                 mg->mg_bias = 0;
5248                         }
5249
5250                         if ((flags & METASLAB_FASTWRITE) ||
5251                             atomic_add_64_nv(&mc->mc_aliquot, asize) >=
5252                             mg->mg_aliquot + mg->mg_bias) {
5253                                 mc->mc_rotor = mg->mg_next;
5254                                 mc->mc_aliquot = 0;
5255                         }
5256
5257                         DVA_SET_VDEV(&dva[d], vd->vdev_id);
5258                         DVA_SET_OFFSET(&dva[d], offset);
5259                         DVA_SET_GANG(&dva[d],
5260                             ((flags & METASLAB_GANG_HEADER) ? 1 : 0));
5261                         DVA_SET_ASIZE(&dva[d], asize);
5262
5263                         if (flags & METASLAB_FASTWRITE) {
5264                                 atomic_add_64(&vd->vdev_pending_fastwrite,
5265                                     psize);
5266                         }
5267
5268                         return (0);
5269                 }
5270 next:
5271                 mc->mc_rotor = mg->mg_next;
5272                 mc->mc_aliquot = 0;
5273         } while ((mg = mg->mg_next) != rotor);
5274
5275         /*
5276          * If we haven't tried hard, do so now.
5277          */
5278         if (!try_hard) {
5279                 try_hard = B_TRUE;
5280                 goto top;
5281         }
5282
5283         bzero(&dva[d], sizeof (dva_t));
5284
5285         metaslab_trace_add(zal, rotor, NULL, psize, d, TRACE_ENOSPC, allocator);
5286         return (SET_ERROR(ENOSPC));
5287 }
5288
5289 void
5290 metaslab_free_concrete(vdev_t *vd, uint64_t offset, uint64_t asize,
5291     boolean_t checkpoint)
5292 {
5293         metaslab_t *msp;
5294         spa_t *spa = vd->vdev_spa;
5295
5296         ASSERT(vdev_is_concrete(vd));
5297         ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5298         ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
5299
5300         msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5301
5302         VERIFY(!msp->ms_condensing);
5303         VERIFY3U(offset, >=, msp->ms_start);
5304         VERIFY3U(offset + asize, <=, msp->ms_start + msp->ms_size);
5305         VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5306         VERIFY0(P2PHASE(asize, 1ULL << vd->vdev_ashift));
5307
5308         metaslab_check_free_impl(vd, offset, asize);
5309
5310         mutex_enter(&msp->ms_lock);
5311         if (range_tree_is_empty(msp->ms_freeing) &&
5312             range_tree_is_empty(msp->ms_checkpointing)) {
5313                 vdev_dirty(vd, VDD_METASLAB, msp, spa_syncing_txg(spa));
5314         }
5315
5316         if (checkpoint) {
5317                 ASSERT(spa_has_checkpoint(spa));
5318                 range_tree_add(msp->ms_checkpointing, offset, asize);
5319         } else {
5320                 range_tree_add(msp->ms_freeing, offset, asize);
5321         }
5322         mutex_exit(&msp->ms_lock);
5323 }
5324
5325 /* ARGSUSED */
5326 void
5327 metaslab_free_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5328     uint64_t size, void *arg)
5329 {
5330         boolean_t *checkpoint = arg;
5331
5332         ASSERT3P(checkpoint, !=, NULL);
5333
5334         if (vd->vdev_ops->vdev_op_remap != NULL)
5335                 vdev_indirect_mark_obsolete(vd, offset, size);
5336         else
5337                 metaslab_free_impl(vd, offset, size, *checkpoint);
5338 }
5339
5340 static void
5341 metaslab_free_impl(vdev_t *vd, uint64_t offset, uint64_t size,
5342     boolean_t checkpoint)
5343 {
5344         spa_t *spa = vd->vdev_spa;
5345
5346         ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5347
5348         if (spa_syncing_txg(spa) > spa_freeze_txg(spa))
5349                 return;
5350
5351         if (spa->spa_vdev_removal != NULL &&
5352             spa->spa_vdev_removal->svr_vdev_id == vd->vdev_id &&
5353             vdev_is_concrete(vd)) {
5354                 /*
5355                  * Note: we check if the vdev is concrete because when
5356                  * we complete the removal, we first change the vdev to be
5357                  * an indirect vdev (in open context), and then (in syncing
5358                  * context) clear spa_vdev_removal.
5359                  */
5360                 free_from_removing_vdev(vd, offset, size);
5361         } else if (vd->vdev_ops->vdev_op_remap != NULL) {
5362                 vdev_indirect_mark_obsolete(vd, offset, size);
5363                 vd->vdev_ops->vdev_op_remap(vd, offset, size,
5364                     metaslab_free_impl_cb, &checkpoint);
5365         } else {
5366                 metaslab_free_concrete(vd, offset, size, checkpoint);
5367         }
5368 }
5369
5370 typedef struct remap_blkptr_cb_arg {
5371         blkptr_t *rbca_bp;
5372         spa_remap_cb_t rbca_cb;
5373         vdev_t *rbca_remap_vd;
5374         uint64_t rbca_remap_offset;
5375         void *rbca_cb_arg;
5376 } remap_blkptr_cb_arg_t;
5377
5378 static void
5379 remap_blkptr_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5380     uint64_t size, void *arg)
5381 {
5382         remap_blkptr_cb_arg_t *rbca = arg;
5383         blkptr_t *bp = rbca->rbca_bp;
5384
5385         /* We can not remap split blocks. */
5386         if (size != DVA_GET_ASIZE(&bp->blk_dva[0]))
5387                 return;
5388         ASSERT0(inner_offset);
5389
5390         if (rbca->rbca_cb != NULL) {
5391                 /*
5392                  * At this point we know that we are not handling split
5393                  * blocks and we invoke the callback on the previous
5394                  * vdev which must be indirect.
5395                  */
5396                 ASSERT3P(rbca->rbca_remap_vd->vdev_ops, ==, &vdev_indirect_ops);
5397
5398                 rbca->rbca_cb(rbca->rbca_remap_vd->vdev_id,
5399                     rbca->rbca_remap_offset, size, rbca->rbca_cb_arg);
5400
5401                 /* set up remap_blkptr_cb_arg for the next call */
5402                 rbca->rbca_remap_vd = vd;
5403                 rbca->rbca_remap_offset = offset;
5404         }
5405
5406         /*
5407          * The phys birth time is that of dva[0].  This ensures that we know
5408          * when each dva was written, so that resilver can determine which
5409          * blocks need to be scrubbed (i.e. those written during the time
5410          * the vdev was offline).  It also ensures that the key used in
5411          * the ARC hash table is unique (i.e. dva[0] + phys_birth).  If
5412          * we didn't change the phys_birth, a lookup in the ARC for a
5413          * remapped BP could find the data that was previously stored at
5414          * this vdev + offset.
5415          */
5416         vdev_t *oldvd = vdev_lookup_top(vd->vdev_spa,
5417             DVA_GET_VDEV(&bp->blk_dva[0]));
5418         vdev_indirect_births_t *vib = oldvd->vdev_indirect_births;
5419         bp->blk_phys_birth = vdev_indirect_births_physbirth(vib,
5420             DVA_GET_OFFSET(&bp->blk_dva[0]), DVA_GET_ASIZE(&bp->blk_dva[0]));
5421
5422         DVA_SET_VDEV(&bp->blk_dva[0], vd->vdev_id);
5423         DVA_SET_OFFSET(&bp->blk_dva[0], offset);
5424 }
5425
5426 /*
5427  * If the block pointer contains any indirect DVAs, modify them to refer to
5428  * concrete DVAs.  Note that this will sometimes not be possible, leaving
5429  * the indirect DVA in place.  This happens if the indirect DVA spans multiple
5430  * segments in the mapping (i.e. it is a "split block").
5431  *
5432  * If the BP was remapped, calls the callback on the original dva (note the
5433  * callback can be called multiple times if the original indirect DVA refers
5434  * to another indirect DVA, etc).
5435  *
5436  * Returns TRUE if the BP was remapped.
5437  */
5438 boolean_t
5439 spa_remap_blkptr(spa_t *spa, blkptr_t *bp, spa_remap_cb_t callback, void *arg)
5440 {
5441         remap_blkptr_cb_arg_t rbca;
5442
5443         if (!zfs_remap_blkptr_enable)
5444                 return (B_FALSE);
5445
5446         if (!spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS))
5447                 return (B_FALSE);
5448
5449         /*
5450          * Dedup BP's can not be remapped, because ddt_phys_select() depends
5451          * on DVA[0] being the same in the BP as in the DDT (dedup table).
5452          */
5453         if (BP_GET_DEDUP(bp))
5454                 return (B_FALSE);
5455
5456         /*
5457          * Gang blocks can not be remapped, because
5458          * zio_checksum_gang_verifier() depends on the DVA[0] that's in
5459          * the BP used to read the gang block header (GBH) being the same
5460          * as the DVA[0] that we allocated for the GBH.
5461          */
5462         if (BP_IS_GANG(bp))
5463                 return (B_FALSE);
5464
5465         /*
5466          * Embedded BP's have no DVA to remap.
5467          */
5468         if (BP_GET_NDVAS(bp) < 1)
5469                 return (B_FALSE);
5470
5471         /*
5472          * Note: we only remap dva[0].  If we remapped other dvas, we
5473          * would no longer know what their phys birth txg is.
5474          */
5475         dva_t *dva = &bp->blk_dva[0];
5476
5477         uint64_t offset = DVA_GET_OFFSET(dva);
5478         uint64_t size = DVA_GET_ASIZE(dva);
5479         vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
5480
5481         if (vd->vdev_ops->vdev_op_remap == NULL)
5482                 return (B_FALSE);
5483
5484         rbca.rbca_bp = bp;
5485         rbca.rbca_cb = callback;
5486         rbca.rbca_remap_vd = vd;
5487         rbca.rbca_remap_offset = offset;
5488         rbca.rbca_cb_arg = arg;
5489
5490         /*
5491          * remap_blkptr_cb() will be called in order for each level of
5492          * indirection, until a concrete vdev is reached or a split block is
5493          * encountered. old_vd and old_offset are updated within the callback
5494          * as we go from the one indirect vdev to the next one (either concrete
5495          * or indirect again) in that order.
5496          */
5497         vd->vdev_ops->vdev_op_remap(vd, offset, size, remap_blkptr_cb, &rbca);
5498
5499         /* Check if the DVA wasn't remapped because it is a split block */
5500         if (DVA_GET_VDEV(&rbca.rbca_bp->blk_dva[0]) == vd->vdev_id)
5501                 return (B_FALSE);
5502
5503         return (B_TRUE);
5504 }
5505
5506 /*
5507  * Undo the allocation of a DVA which happened in the given transaction group.
5508  */
5509 void
5510 metaslab_unalloc_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
5511 {
5512         metaslab_t *msp;
5513         vdev_t *vd;
5514         uint64_t vdev = DVA_GET_VDEV(dva);
5515         uint64_t offset = DVA_GET_OFFSET(dva);
5516         uint64_t size = DVA_GET_ASIZE(dva);
5517
5518         ASSERT(DVA_IS_VALID(dva));
5519         ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5520
5521         if (txg > spa_freeze_txg(spa))
5522                 return;
5523
5524         if ((vd = vdev_lookup_top(spa, vdev)) == NULL || !DVA_IS_VALID(dva) ||
5525             (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
5526                 zfs_panic_recover("metaslab_free_dva(): bad DVA %llu:%llu:%llu",
5527                     (u_longlong_t)vdev, (u_longlong_t)offset,
5528                     (u_longlong_t)size);
5529                 return;
5530         }
5531
5532         ASSERT(!vd->vdev_removing);
5533         ASSERT(vdev_is_concrete(vd));
5534         ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
5535         ASSERT3P(vd->vdev_indirect_mapping, ==, NULL);
5536
5537         if (DVA_GET_GANG(dva))
5538                 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
5539
5540         msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5541
5542         mutex_enter(&msp->ms_lock);
5543         range_tree_remove(msp->ms_allocating[txg & TXG_MASK],
5544             offset, size);
5545         msp->ms_allocating_total -= size;
5546
5547         VERIFY(!msp->ms_condensing);
5548         VERIFY3U(offset, >=, msp->ms_start);
5549         VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
5550         VERIFY3U(range_tree_space(msp->ms_allocatable) + size, <=,
5551             msp->ms_size);
5552         VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5553         VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
5554         range_tree_add(msp->ms_allocatable, offset, size);
5555         mutex_exit(&msp->ms_lock);
5556 }
5557
5558 /*
5559  * Free the block represented by the given DVA.
5560  */
5561 void
5562 metaslab_free_dva(spa_t *spa, const dva_t *dva, boolean_t checkpoint)
5563 {
5564         uint64_t vdev = DVA_GET_VDEV(dva);
5565         uint64_t offset = DVA_GET_OFFSET(dva);
5566         uint64_t size = DVA_GET_ASIZE(dva);
5567         vdev_t *vd = vdev_lookup_top(spa, vdev);
5568
5569         ASSERT(DVA_IS_VALID(dva));
5570         ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5571
5572         if (DVA_GET_GANG(dva)) {
5573                 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
5574         }
5575
5576         metaslab_free_impl(vd, offset, size, checkpoint);
5577 }
5578
5579 /*
5580  * Reserve some allocation slots. The reservation system must be called
5581  * before we call into the allocator. If there aren't any available slots
5582  * then the I/O will be throttled until an I/O completes and its slots are
5583  * freed up. The function returns true if it was successful in placing
5584  * the reservation.
5585  */
5586 boolean_t
5587 metaslab_class_throttle_reserve(metaslab_class_t *mc, int slots, int allocator,
5588     zio_t *zio, int flags)
5589 {
5590         uint64_t available_slots = 0;
5591         boolean_t slot_reserved = B_FALSE;
5592         uint64_t max = mc->mc_alloc_max_slots[allocator];
5593
5594         ASSERT(mc->mc_alloc_throttle_enabled);
5595         mutex_enter(&mc->mc_lock);
5596
5597         uint64_t reserved_slots =
5598             zfs_refcount_count(&mc->mc_alloc_slots[allocator]);
5599         if (reserved_slots < max)
5600                 available_slots = max - reserved_slots;
5601
5602         if (slots <= available_slots || GANG_ALLOCATION(flags) ||
5603             flags & METASLAB_MUST_RESERVE) {
5604                 /*
5605                  * We reserve the slots individually so that we can unreserve
5606                  * them individually when an I/O completes.
5607                  */
5608                 for (int d = 0; d < slots; d++) {
5609                         reserved_slots =
5610                             zfs_refcount_add(&mc->mc_alloc_slots[allocator],
5611                             zio);
5612                 }
5613                 zio->io_flags |= ZIO_FLAG_IO_ALLOCATING;
5614                 slot_reserved = B_TRUE;
5615         }
5616
5617         mutex_exit(&mc->mc_lock);
5618         return (slot_reserved);
5619 }
5620
5621 void
5622 metaslab_class_throttle_unreserve(metaslab_class_t *mc, int slots,
5623     int allocator, zio_t *zio)
5624 {
5625         ASSERT(mc->mc_alloc_throttle_enabled);
5626         mutex_enter(&mc->mc_lock);
5627         for (int d = 0; d < slots; d++) {
5628                 (void) zfs_refcount_remove(&mc->mc_alloc_slots[allocator],
5629                     zio);
5630         }
5631         mutex_exit(&mc->mc_lock);
5632 }
5633
5634 static int
5635 metaslab_claim_concrete(vdev_t *vd, uint64_t offset, uint64_t size,
5636     uint64_t txg)
5637 {
5638         metaslab_t *msp;
5639         spa_t *spa = vd->vdev_spa;
5640         int error = 0;
5641
5642         if (offset >> vd->vdev_ms_shift >= vd->vdev_ms_count)
5643                 return (SET_ERROR(ENXIO));
5644
5645         ASSERT3P(vd->vdev_ms, !=, NULL);
5646         msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5647
5648         mutex_enter(&msp->ms_lock);
5649
5650         if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded) {
5651                 error = metaslab_activate(msp, 0, METASLAB_WEIGHT_CLAIM);
5652                 if (error == EBUSY) {
5653                         ASSERT(msp->ms_loaded);
5654                         ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
5655                         error = 0;
5656                 }
5657         }
5658
5659         if (error == 0 &&
5660             !range_tree_contains(msp->ms_allocatable, offset, size))
5661                 error = SET_ERROR(ENOENT);
5662
5663         if (error || txg == 0) {        /* txg == 0 indicates dry run */
5664                 mutex_exit(&msp->ms_lock);
5665                 return (error);
5666         }
5667
5668         VERIFY(!msp->ms_condensing);
5669         VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5670         VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
5671         VERIFY3U(range_tree_space(msp->ms_allocatable) - size, <=,
5672             msp->ms_size);
5673         range_tree_remove(msp->ms_allocatable, offset, size);
5674         range_tree_clear(msp->ms_trim, offset, size);
5675
5676         if (spa_writeable(spa)) {       /* don't dirty if we're zdb(1M) */
5677                 metaslab_class_t *mc = msp->ms_group->mg_class;
5678                 multilist_sublist_t *mls =
5679                     multilist_sublist_lock_obj(mc->mc_metaslab_txg_list, msp);
5680                 if (!multilist_link_active(&msp->ms_class_txg_node)) {
5681                         msp->ms_selected_txg = txg;
5682                         multilist_sublist_insert_head(mls, msp);
5683                 }
5684                 multilist_sublist_unlock(mls);
5685
5686                 if (range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
5687                         vdev_dirty(vd, VDD_METASLAB, msp, txg);
5688                 range_tree_add(msp->ms_allocating[txg & TXG_MASK],
5689                     offset, size);
5690                 msp->ms_allocating_total += size;
5691         }
5692
5693         mutex_exit(&msp->ms_lock);
5694
5695         return (0);
5696 }
5697
5698 typedef struct metaslab_claim_cb_arg_t {
5699         uint64_t        mcca_txg;
5700         int             mcca_error;
5701 } metaslab_claim_cb_arg_t;
5702
5703 /* ARGSUSED */
5704 static void
5705 metaslab_claim_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5706     uint64_t size, void *arg)
5707 {
5708         metaslab_claim_cb_arg_t *mcca_arg = arg;
5709
5710         if (mcca_arg->mcca_error == 0) {
5711                 mcca_arg->mcca_error = metaslab_claim_concrete(vd, offset,
5712                     size, mcca_arg->mcca_txg);
5713         }
5714 }
5715
5716 int
5717 metaslab_claim_impl(vdev_t *vd, uint64_t offset, uint64_t size, uint64_t txg)
5718 {
5719         if (vd->vdev_ops->vdev_op_remap != NULL) {
5720                 metaslab_claim_cb_arg_t arg;
5721
5722                 /*
5723                  * Only zdb(1M) can claim on indirect vdevs.  This is used
5724                  * to detect leaks of mapped space (that are not accounted
5725                  * for in the obsolete counts, spacemap, or bpobj).
5726                  */
5727                 ASSERT(!spa_writeable(vd->vdev_spa));
5728                 arg.mcca_error = 0;
5729                 arg.mcca_txg = txg;
5730
5731                 vd->vdev_ops->vdev_op_remap(vd, offset, size,
5732                     metaslab_claim_impl_cb, &arg);
5733
5734                 if (arg.mcca_error == 0) {
5735                         arg.mcca_error = metaslab_claim_concrete(vd,
5736                             offset, size, txg);
5737                 }
5738                 return (arg.mcca_error);
5739         } else {
5740                 return (metaslab_claim_concrete(vd, offset, size, txg));
5741         }
5742 }
5743
5744 /*
5745  * Intent log support: upon opening the pool after a crash, notify the SPA
5746  * of blocks that the intent log has allocated for immediate write, but
5747  * which are still considered free by the SPA because the last transaction
5748  * group didn't commit yet.
5749  */
5750 static int
5751 metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
5752 {
5753         uint64_t vdev = DVA_GET_VDEV(dva);
5754         uint64_t offset = DVA_GET_OFFSET(dva);
5755         uint64_t size = DVA_GET_ASIZE(dva);
5756         vdev_t *vd;
5757
5758         if ((vd = vdev_lookup_top(spa, vdev)) == NULL) {
5759                 return (SET_ERROR(ENXIO));
5760         }
5761
5762         ASSERT(DVA_IS_VALID(dva));
5763
5764         if (DVA_GET_GANG(dva))
5765                 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
5766
5767         return (metaslab_claim_impl(vd, offset, size, txg));
5768 }
5769
5770 int
5771 metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
5772     int ndvas, uint64_t txg, blkptr_t *hintbp, int flags,
5773     zio_alloc_list_t *zal, zio_t *zio, int allocator)
5774 {
5775         dva_t *dva = bp->blk_dva;
5776         dva_t *hintdva = (hintbp != NULL) ? hintbp->blk_dva : NULL;
5777         int error = 0;
5778
5779         ASSERT(bp->blk_birth == 0);
5780         ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
5781
5782         spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
5783
5784         if (mc->mc_rotor == NULL) {     /* no vdevs in this class */
5785                 spa_config_exit(spa, SCL_ALLOC, FTAG);
5786                 return (SET_ERROR(ENOSPC));
5787         }
5788
5789         ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
5790         ASSERT(BP_GET_NDVAS(bp) == 0);
5791         ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
5792         ASSERT3P(zal, !=, NULL);
5793
5794         for (int d = 0; d < ndvas; d++) {
5795                 error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
5796                     txg, flags, zal, allocator);
5797                 if (error != 0) {
5798                         for (d--; d >= 0; d--) {
5799                                 metaslab_unalloc_dva(spa, &dva[d], txg);
5800                                 metaslab_group_alloc_decrement(spa,
5801                                     DVA_GET_VDEV(&dva[d]), zio, flags,
5802                                     allocator, B_FALSE);
5803                                 bzero(&dva[d], sizeof (dva_t));
5804                         }
5805                         spa_config_exit(spa, SCL_ALLOC, FTAG);
5806                         return (error);
5807                 } else {
5808                         /*
5809                          * Update the metaslab group's queue depth
5810                          * based on the newly allocated dva.
5811                          */
5812                         metaslab_group_alloc_increment(spa,
5813                             DVA_GET_VDEV(&dva[d]), zio, flags, allocator);
5814                 }
5815
5816         }
5817         ASSERT(error == 0);
5818         ASSERT(BP_GET_NDVAS(bp) == ndvas);
5819
5820         spa_config_exit(spa, SCL_ALLOC, FTAG);
5821
5822         BP_SET_BIRTH(bp, txg, 0);
5823
5824         return (0);
5825 }
5826
5827 void
5828 metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
5829 {
5830         const dva_t *dva = bp->blk_dva;
5831         int ndvas = BP_GET_NDVAS(bp);
5832
5833         ASSERT(!BP_IS_HOLE(bp));
5834         ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
5835
5836         /*
5837          * If we have a checkpoint for the pool we need to make sure that
5838          * the blocks that we free that are part of the checkpoint won't be
5839          * reused until the checkpoint is discarded or we revert to it.
5840          *
5841          * The checkpoint flag is passed down the metaslab_free code path
5842          * and is set whenever we want to add a block to the checkpoint's
5843          * accounting. That is, we "checkpoint" blocks that existed at the
5844          * time the checkpoint was created and are therefore referenced by
5845          * the checkpointed uberblock.
5846          *
5847          * Note that, we don't checkpoint any blocks if the current
5848          * syncing txg <= spa_checkpoint_txg. We want these frees to sync
5849          * normally as they will be referenced by the checkpointed uberblock.
5850          */
5851         boolean_t checkpoint = B_FALSE;
5852         if (bp->blk_birth <= spa->spa_checkpoint_txg &&
5853             spa_syncing_txg(spa) > spa->spa_checkpoint_txg) {
5854                 /*
5855                  * At this point, if the block is part of the checkpoint
5856                  * there is no way it was created in the current txg.
5857                  */
5858                 ASSERT(!now);
5859                 ASSERT3U(spa_syncing_txg(spa), ==, txg);
5860                 checkpoint = B_TRUE;
5861         }
5862
5863         spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
5864
5865         for (int d = 0; d < ndvas; d++) {
5866                 if (now) {
5867                         metaslab_unalloc_dva(spa, &dva[d], txg);
5868                 } else {
5869                         ASSERT3U(txg, ==, spa_syncing_txg(spa));
5870                         metaslab_free_dva(spa, &dva[d], checkpoint);
5871                 }
5872         }
5873
5874         spa_config_exit(spa, SCL_FREE, FTAG);
5875 }
5876
5877 int
5878 metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
5879 {
5880         const dva_t *dva = bp->blk_dva;
5881         int ndvas = BP_GET_NDVAS(bp);
5882         int error = 0;
5883
5884         ASSERT(!BP_IS_HOLE(bp));
5885
5886         if (txg != 0) {
5887                 /*
5888                  * First do a dry run to make sure all DVAs are claimable,
5889                  * so we don't have to unwind from partial failures below.
5890                  */
5891                 if ((error = metaslab_claim(spa, bp, 0)) != 0)
5892                         return (error);
5893         }
5894
5895         spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
5896
5897         for (int d = 0; d < ndvas; d++) {
5898                 error = metaslab_claim_dva(spa, &dva[d], txg);
5899                 if (error != 0)
5900                         break;
5901         }
5902
5903         spa_config_exit(spa, SCL_ALLOC, FTAG);
5904
5905         ASSERT(error == 0 || txg == 0);
5906
5907         return (error);
5908 }
5909
5910 void
5911 metaslab_fastwrite_mark(spa_t *spa, const blkptr_t *bp)
5912 {
5913         const dva_t *dva = bp->blk_dva;
5914         int ndvas = BP_GET_NDVAS(bp);
5915         uint64_t psize = BP_GET_PSIZE(bp);
5916         int d;
5917         vdev_t *vd;
5918
5919         ASSERT(!BP_IS_HOLE(bp));
5920         ASSERT(!BP_IS_EMBEDDED(bp));
5921         ASSERT(psize > 0);
5922
5923         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
5924
5925         for (d = 0; d < ndvas; d++) {
5926                 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
5927                         continue;
5928                 atomic_add_64(&vd->vdev_pending_fastwrite, psize);
5929         }
5930
5931         spa_config_exit(spa, SCL_VDEV, FTAG);
5932 }
5933
5934 void
5935 metaslab_fastwrite_unmark(spa_t *spa, const blkptr_t *bp)
5936 {
5937         const dva_t *dva = bp->blk_dva;
5938         int ndvas = BP_GET_NDVAS(bp);
5939         uint64_t psize = BP_GET_PSIZE(bp);
5940         int d;
5941         vdev_t *vd;
5942
5943         ASSERT(!BP_IS_HOLE(bp));
5944         ASSERT(!BP_IS_EMBEDDED(bp));
5945         ASSERT(psize > 0);
5946
5947         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
5948
5949         for (d = 0; d < ndvas; d++) {
5950                 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
5951                         continue;
5952                 ASSERT3U(vd->vdev_pending_fastwrite, >=, psize);
5953                 atomic_sub_64(&vd->vdev_pending_fastwrite, psize);
5954         }
5955
5956         spa_config_exit(spa, SCL_VDEV, FTAG);
5957 }
5958
5959 /* ARGSUSED */
5960 static void
5961 metaslab_check_free_impl_cb(uint64_t inner, vdev_t *vd, uint64_t offset,
5962     uint64_t size, void *arg)
5963 {
5964         if (vd->vdev_ops == &vdev_indirect_ops)
5965                 return;
5966
5967         metaslab_check_free_impl(vd, offset, size);
5968 }
5969
5970 static void
5971 metaslab_check_free_impl(vdev_t *vd, uint64_t offset, uint64_t size)
5972 {
5973         metaslab_t *msp;
5974         spa_t *spa __maybe_unused = vd->vdev_spa;
5975
5976         if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
5977                 return;
5978
5979         if (vd->vdev_ops->vdev_op_remap != NULL) {
5980                 vd->vdev_ops->vdev_op_remap(vd, offset, size,
5981                     metaslab_check_free_impl_cb, NULL);
5982                 return;
5983         }
5984
5985         ASSERT(vdev_is_concrete(vd));
5986         ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
5987         ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5988
5989         msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5990
5991         mutex_enter(&msp->ms_lock);
5992         if (msp->ms_loaded) {
5993                 range_tree_verify_not_present(msp->ms_allocatable,
5994                     offset, size);
5995         }
5996
5997         /*
5998          * Check all segments that currently exist in the freeing pipeline.
5999          *
6000          * It would intuitively make sense to also check the current allocating
6001          * tree since metaslab_unalloc_dva() exists for extents that are
6002          * allocated and freed in the same sync pass within the same txg.
6003          * Unfortunately there are places (e.g. the ZIL) where we allocate a
6004          * segment but then we free part of it within the same txg
6005          * [see zil_sync()]. Thus, we don't call range_tree_verify() in the
6006          * current allocating tree.
6007          */
6008         range_tree_verify_not_present(msp->ms_freeing, offset, size);
6009         range_tree_verify_not_present(msp->ms_checkpointing, offset, size);
6010         range_tree_verify_not_present(msp->ms_freed, offset, size);
6011         for (int j = 0; j < TXG_DEFER_SIZE; j++)
6012                 range_tree_verify_not_present(msp->ms_defer[j], offset, size);
6013         range_tree_verify_not_present(msp->ms_trim, offset, size);
6014         mutex_exit(&msp->ms_lock);
6015 }
6016
6017 void
6018 metaslab_check_free(spa_t *spa, const blkptr_t *bp)
6019 {
6020         if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
6021                 return;
6022
6023         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6024         for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
6025                 uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
6026                 vdev_t *vd = vdev_lookup_top(spa, vdev);
6027                 uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
6028                 uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
6029
6030                 if (DVA_GET_GANG(&bp->blk_dva[i]))
6031                         size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
6032
6033                 ASSERT3P(vd, !=, NULL);
6034
6035                 metaslab_check_free_impl(vd, offset, size);
6036         }
6037         spa_config_exit(spa, SCL_VDEV, FTAG);
6038 }
6039
6040 static void
6041 metaslab_group_disable_wait(metaslab_group_t *mg)
6042 {
6043         ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
6044         while (mg->mg_disabled_updating) {
6045                 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
6046         }
6047 }
6048
6049 static void
6050 metaslab_group_disabled_increment(metaslab_group_t *mg)
6051 {
6052         ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
6053         ASSERT(mg->mg_disabled_updating);
6054
6055         while (mg->mg_ms_disabled >= max_disabled_ms) {
6056                 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
6057         }
6058         mg->mg_ms_disabled++;
6059         ASSERT3U(mg->mg_ms_disabled, <=, max_disabled_ms);
6060 }
6061
6062 /*
6063  * Mark the metaslab as disabled to prevent any allocations on this metaslab.
6064  * We must also track how many metaslabs are currently disabled within a
6065  * metaslab group and limit them to prevent allocation failures from
6066  * occurring because all metaslabs are disabled.
6067  */
6068 void
6069 metaslab_disable(metaslab_t *msp)
6070 {
6071         ASSERT(!MUTEX_HELD(&msp->ms_lock));
6072         metaslab_group_t *mg = msp->ms_group;
6073
6074         mutex_enter(&mg->mg_ms_disabled_lock);
6075
6076         /*
6077          * To keep an accurate count of how many threads have disabled
6078          * a specific metaslab group, we only allow one thread to mark
6079          * the metaslab group at a time. This ensures that the value of
6080          * ms_disabled will be accurate when we decide to mark a metaslab
6081          * group as disabled. To do this we force all other threads
6082          * to wait till the metaslab's mg_disabled_updating flag is no
6083          * longer set.
6084          */
6085         metaslab_group_disable_wait(mg);
6086         mg->mg_disabled_updating = B_TRUE;
6087         if (msp->ms_disabled == 0) {
6088                 metaslab_group_disabled_increment(mg);
6089         }
6090         mutex_enter(&msp->ms_lock);
6091         msp->ms_disabled++;
6092         mutex_exit(&msp->ms_lock);
6093
6094         mg->mg_disabled_updating = B_FALSE;
6095         cv_broadcast(&mg->mg_ms_disabled_cv);
6096         mutex_exit(&mg->mg_ms_disabled_lock);
6097 }
6098
6099 void
6100 metaslab_enable(metaslab_t *msp, boolean_t sync, boolean_t unload)
6101 {
6102         metaslab_group_t *mg = msp->ms_group;
6103         spa_t *spa = mg->mg_vd->vdev_spa;
6104
6105         /*
6106          * Wait for the outstanding IO to be synced to prevent newly
6107          * allocated blocks from being overwritten.  This used by
6108          * initialize and TRIM which are modifying unallocated space.
6109          */
6110         if (sync)
6111                 txg_wait_synced(spa_get_dsl(spa), 0);
6112
6113         mutex_enter(&mg->mg_ms_disabled_lock);
6114         mutex_enter(&msp->ms_lock);
6115         if (--msp->ms_disabled == 0) {
6116                 mg->mg_ms_disabled--;
6117                 cv_broadcast(&mg->mg_ms_disabled_cv);
6118                 if (unload)
6119                         metaslab_unload(msp);
6120         }
6121         mutex_exit(&msp->ms_lock);
6122         mutex_exit(&mg->mg_ms_disabled_lock);
6123 }
6124
6125 static void
6126 metaslab_update_ondisk_flush_data(metaslab_t *ms, dmu_tx_t *tx)
6127 {
6128         vdev_t *vd = ms->ms_group->mg_vd;
6129         spa_t *spa = vd->vdev_spa;
6130         objset_t *mos = spa_meta_objset(spa);
6131
6132         ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
6133
6134         metaslab_unflushed_phys_t entry = {
6135                 .msp_unflushed_txg = metaslab_unflushed_txg(ms),
6136         };
6137         uint64_t entry_size = sizeof (entry);
6138         uint64_t entry_offset = ms->ms_id * entry_size;
6139
6140         uint64_t object = 0;
6141         int err = zap_lookup(mos, vd->vdev_top_zap,
6142             VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1,
6143             &object);
6144         if (err == ENOENT) {
6145                 object = dmu_object_alloc(mos, DMU_OTN_UINT64_METADATA,
6146                     SPA_OLD_MAXBLOCKSIZE, DMU_OT_NONE, 0, tx);
6147                 VERIFY0(zap_add(mos, vd->vdev_top_zap,
6148                     VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1,
6149                     &object, tx));
6150         } else {
6151                 VERIFY0(err);
6152         }
6153
6154         dmu_write(spa_meta_objset(spa), object, entry_offset, entry_size,
6155             &entry, tx);
6156 }
6157
6158 void
6159 metaslab_set_unflushed_txg(metaslab_t *ms, uint64_t txg, dmu_tx_t *tx)
6160 {
6161         spa_t *spa = ms->ms_group->mg_vd->vdev_spa;
6162
6163         if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
6164                 return;
6165
6166         ms->ms_unflushed_txg = txg;
6167         metaslab_update_ondisk_flush_data(ms, tx);
6168 }
6169
6170 uint64_t
6171 metaslab_unflushed_txg(metaslab_t *ms)
6172 {
6173         return (ms->ms_unflushed_txg);
6174 }
6175
6176 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, aliquot, ULONG, ZMOD_RW,
6177         "Allocation granularity (a.k.a. stripe size)");
6178
6179 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, debug_load, INT, ZMOD_RW,
6180         "Load all metaslabs when pool is first opened");
6181
6182 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, debug_unload, INT, ZMOD_RW,
6183         "Prevent metaslabs from being unloaded");
6184
6185 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, preload_enabled, INT, ZMOD_RW,
6186         "Preload potential metaslabs during reassessment");
6187
6188 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, unload_delay, INT, ZMOD_RW,
6189         "Delay in txgs after metaslab was last used before unloading");
6190
6191 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, unload_delay_ms, INT, ZMOD_RW,
6192         "Delay in milliseconds after metaslab was last used before unloading");
6193
6194 /* BEGIN CSTYLED */
6195 ZFS_MODULE_PARAM(zfs_mg, zfs_mg_, noalloc_threshold, INT, ZMOD_RW,
6196         "Percentage of metaslab group size that should be free to make it "
6197         "eligible for allocation");
6198
6199 ZFS_MODULE_PARAM(zfs_mg, zfs_mg_, fragmentation_threshold, INT, ZMOD_RW,
6200         "Percentage of metaslab group size that should be considered eligible "
6201         "for allocations unless all metaslab groups within the metaslab class "
6202         "have also crossed this threshold");
6203
6204 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, fragmentation_threshold, INT,
6205          ZMOD_RW, "Fragmentation for metaslab to allow allocation");
6206
6207 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, fragmentation_factor_enabled, INT, ZMOD_RW,
6208         "Use the fragmentation metric to prefer less fragmented metaslabs");
6209 /* END CSTYLED */
6210
6211 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, lba_weighting_enabled, INT, ZMOD_RW,
6212         "Prefer metaslabs with lower LBAs");
6213
6214 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, bias_enabled, INT, ZMOD_RW,
6215         "Enable metaslab group biasing");
6216
6217 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, segment_weight_enabled, INT,
6218         ZMOD_RW, "Enable segment-based metaslab selection");
6219
6220 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, switch_threshold, INT, ZMOD_RW,
6221         "Segment-based metaslab selection maximum buckets before switching");
6222
6223 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, force_ganging, ULONG, ZMOD_RW,
6224         "Blocks larger than this size are forced to be gang blocks");
6225
6226 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_max_search, INT, ZMOD_RW,
6227         "Max distance (bytes) to search forward before using size tree");
6228
6229 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_use_largest_segment, INT, ZMOD_RW,
6230         "When looking in size tree, use largest segment instead of exact fit");
6231
6232 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, max_size_cache_sec, ULONG,
6233         ZMOD_RW, "How long to trust the cached max chunk size of a metaslab");
6234
6235 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, mem_limit, INT, ZMOD_RW,
6236         "Percentage of memory that can be used to store metaslab range trees");