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