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