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