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