]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/metaslab.c
Fix zdb segfault
[mirror_zfs.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.
9bd274dd 23 * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
2e528b49 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>
93cf2076 34#include <sys/spa_impl.h>
f3a7f661 35#include <sys/zfeature.h>
34dc7c2f 36
d1d7e268 37#define WITH_DF_BLOCK_ALLOCATOR
6d974228
GW
38
39/*
40 * Allow allocations to switch to gang blocks quickly. We do this to
41 * avoid having to load lots of space_maps in a given txg. There are,
42 * however, some cases where we want to avoid "fast" ganging and instead
43 * we want to do an exhaustive search of all metaslabs on this device.
672692c7 44 * Currently we don't allow any gang, slog, or dump device related allocations
6d974228
GW
45 * to "fast" gang.
46 */
47#define CAN_FASTGANG(flags) \
48 (!((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER | \
49 METASLAB_GANG_AVOID)))
22c81dd8 50
93cf2076
GW
51#define METASLAB_WEIGHT_PRIMARY (1ULL << 63)
52#define METASLAB_WEIGHT_SECONDARY (1ULL << 62)
53#define METASLAB_ACTIVE_MASK \
54 (METASLAB_WEIGHT_PRIMARY | METASLAB_WEIGHT_SECONDARY)
55
34dc7c2f
BB
56uint64_t metaslab_aliquot = 512ULL << 10;
57uint64_t metaslab_gang_bang = SPA_MAXBLOCKSIZE + 1; /* force gang blocks */
58
e51be066
GW
59/*
60 * The in-core space map representation is more compact than its on-disk form.
61 * The zfs_condense_pct determines how much more compact the in-core
62 * space_map representation must be before we compact it on-disk.
63 * Values should be greater than or equal to 100.
64 */
65int zfs_condense_pct = 200;
66
ac72fac3
GW
67/*
68 * The zfs_mg_noalloc_threshold defines which metaslab groups should
69 * be eligible for allocation. The value is defined as a percentage of
f3a7f661 70 * free space. Metaslab groups that have more free space than
ac72fac3
GW
71 * zfs_mg_noalloc_threshold are always eligible for allocations. Once
72 * a metaslab group's free space is less than or equal to the
73 * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
74 * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
75 * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
76 * groups are allowed to accept allocations. Gang blocks are always
77 * eligible to allocate on any metaslab group. The default value of 0 means
78 * no metaslab group will be excluded based on this criterion.
79 */
80int zfs_mg_noalloc_threshold = 0;
6d974228 81
f3a7f661
GW
82/*
83 * Metaslab groups are considered eligible for allocations if their
84 * fragmenation metric (measured as a percentage) is less than or equal to
85 * zfs_mg_fragmentation_threshold. If a metaslab group exceeds this threshold
86 * then it will be skipped unless all metaslab groups within the metaslab
87 * class have also crossed this threshold.
88 */
89int zfs_mg_fragmentation_threshold = 85;
90
91/*
92 * Allow metaslabs to keep their active state as long as their fragmentation
93 * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
94 * active metaslab that exceeds this threshold will no longer keep its active
95 * status allowing better metaslabs to be selected.
96 */
97int zfs_metaslab_fragmentation_threshold = 70;
98
428870ff 99/*
aa7d06a9 100 * When set will load all metaslabs when pool is first opened.
428870ff 101 */
aa7d06a9
GW
102int metaslab_debug_load = 0;
103
104/*
105 * When set will prevent metaslabs from being unloaded.
106 */
107int metaslab_debug_unload = 0;
428870ff 108
9babb374
BB
109/*
110 * Minimum size which forces the dynamic allocator to change
428870ff 111 * it's allocation strategy. Once the space map cannot satisfy
9babb374
BB
112 * an allocation of this size then it switches to using more
113 * aggressive strategy (i.e search by size rather than offset).
114 */
115uint64_t metaslab_df_alloc_threshold = SPA_MAXBLOCKSIZE;
116
117/*
118 * The minimum free space, in percent, which must be available
119 * in a space map to continue allocations in a first-fit fashion.
120 * Once the space_map's free space drops below this level we dynamically
121 * switch to using best-fit allocations.
122 */
428870ff
BB
123int metaslab_df_free_pct = 4;
124
125/*
126 * A metaslab is considered "free" if it contains a contiguous
127 * segment which is greater than metaslab_min_alloc_size.
128 */
129uint64_t metaslab_min_alloc_size = DMU_MAX_ACCESS;
130
131/*
93cf2076 132 * Percentage of all cpus that can be used by the metaslab taskq.
428870ff 133 */
93cf2076 134int metaslab_load_pct = 50;
428870ff
BB
135
136/*
93cf2076
GW
137 * Determines how many txgs a metaslab may remain loaded without having any
138 * allocations from it. As long as a metaslab continues to be used we will
139 * keep it loaded.
428870ff 140 */
93cf2076 141int metaslab_unload_delay = TXG_SIZE * 2;
9babb374 142
93cf2076
GW
143/*
144 * Max number of metaslabs per group to preload.
145 */
146int metaslab_preload_limit = SPA_DVAS_PER_BP;
147
148/*
149 * Enable/disable preloading of metaslab.
150 */
f3a7f661 151int metaslab_preload_enabled = B_TRUE;
93cf2076
GW
152
153/*
f3a7f661 154 * Enable/disable fragmentation weighting on metaslabs.
93cf2076 155 */
f3a7f661 156int metaslab_fragmentation_factor_enabled = B_TRUE;
93cf2076 157
f3a7f661
GW
158/*
159 * Enable/disable lba weighting (i.e. outer tracks are given preference).
160 */
161int metaslab_lba_weighting_enabled = B_TRUE;
162
163/*
164 * Enable/disable metaslab group biasing.
165 */
166int metaslab_bias_enabled = B_TRUE;
167
168static uint64_t metaslab_fragmentation(metaslab_t *);
93cf2076 169
34dc7c2f
BB
170/*
171 * ==========================================================================
172 * Metaslab classes
173 * ==========================================================================
174 */
175metaslab_class_t *
93cf2076 176metaslab_class_create(spa_t *spa, metaslab_ops_t *ops)
34dc7c2f
BB
177{
178 metaslab_class_t *mc;
179
b8d06fca 180 mc = kmem_zalloc(sizeof (metaslab_class_t), KM_PUSHPAGE);
34dc7c2f 181
428870ff 182 mc->mc_spa = spa;
34dc7c2f 183 mc->mc_rotor = NULL;
9babb374 184 mc->mc_ops = ops;
920dd524 185 mutex_init(&mc->mc_fastwrite_lock, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
186
187 return (mc);
188}
189
190void
191metaslab_class_destroy(metaslab_class_t *mc)
192{
428870ff
BB
193 ASSERT(mc->mc_rotor == NULL);
194 ASSERT(mc->mc_alloc == 0);
195 ASSERT(mc->mc_deferred == 0);
196 ASSERT(mc->mc_space == 0);
197 ASSERT(mc->mc_dspace == 0);
34dc7c2f 198
920dd524 199 mutex_destroy(&mc->mc_fastwrite_lock);
34dc7c2f
BB
200 kmem_free(mc, sizeof (metaslab_class_t));
201}
202
428870ff
BB
203int
204metaslab_class_validate(metaslab_class_t *mc)
34dc7c2f 205{
428870ff
BB
206 metaslab_group_t *mg;
207 vdev_t *vd;
34dc7c2f 208
428870ff
BB
209 /*
210 * Must hold one of the spa_config locks.
211 */
212 ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
213 spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
34dc7c2f 214
428870ff
BB
215 if ((mg = mc->mc_rotor) == NULL)
216 return (0);
217
218 do {
219 vd = mg->mg_vd;
220 ASSERT(vd->vdev_mg != NULL);
221 ASSERT3P(vd->vdev_top, ==, vd);
222 ASSERT3P(mg->mg_class, ==, mc);
223 ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
224 } while ((mg = mg->mg_next) != mc->mc_rotor);
225
226 return (0);
34dc7c2f
BB
227}
228
229void
428870ff
BB
230metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
231 int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
34dc7c2f 232{
428870ff
BB
233 atomic_add_64(&mc->mc_alloc, alloc_delta);
234 atomic_add_64(&mc->mc_deferred, defer_delta);
235 atomic_add_64(&mc->mc_space, space_delta);
236 atomic_add_64(&mc->mc_dspace, dspace_delta);
237}
34dc7c2f 238
428870ff
BB
239uint64_t
240metaslab_class_get_alloc(metaslab_class_t *mc)
241{
242 return (mc->mc_alloc);
243}
34dc7c2f 244
428870ff
BB
245uint64_t
246metaslab_class_get_deferred(metaslab_class_t *mc)
247{
248 return (mc->mc_deferred);
249}
34dc7c2f 250
428870ff
BB
251uint64_t
252metaslab_class_get_space(metaslab_class_t *mc)
253{
254 return (mc->mc_space);
255}
34dc7c2f 256
428870ff
BB
257uint64_t
258metaslab_class_get_dspace(metaslab_class_t *mc)
259{
260 return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
34dc7c2f
BB
261}
262
f3a7f661
GW
263void
264metaslab_class_histogram_verify(metaslab_class_t *mc)
265{
266 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
267 uint64_t *mc_hist;
268 int i, c;
269
270 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
271 return;
272
273 mc_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
274 KM_PUSHPAGE);
275
276 for (c = 0; c < rvd->vdev_children; c++) {
277 vdev_t *tvd = rvd->vdev_child[c];
278 metaslab_group_t *mg = tvd->vdev_mg;
279
280 /*
281 * Skip any holes, uninitialized top-levels, or
282 * vdevs that are not in this metalab class.
283 */
284 if (tvd->vdev_ishole || tvd->vdev_ms_shift == 0 ||
285 mg->mg_class != mc) {
286 continue;
287 }
288
289 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
290 mc_hist[i] += mg->mg_histogram[i];
291 }
292
293 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
294 VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
295
296 kmem_free(mc_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
297}
298
299/*
300 * Calculate the metaslab class's fragmentation metric. The metric
301 * is weighted based on the space contribution of each metaslab group.
302 * The return value will be a number between 0 and 100 (inclusive), or
303 * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
304 * zfs_frag_table for more information about the metric.
305 */
306uint64_t
307metaslab_class_fragmentation(metaslab_class_t *mc)
308{
309 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
310 uint64_t fragmentation = 0;
311 int c;
312
313 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
314
315 for (c = 0; c < rvd->vdev_children; c++) {
316 vdev_t *tvd = rvd->vdev_child[c];
317 metaslab_group_t *mg = tvd->vdev_mg;
318
319 /*
320 * Skip any holes, uninitialized top-levels, or
321 * vdevs that are not in this metalab class.
322 */
323 if (tvd->vdev_ishole || tvd->vdev_ms_shift == 0 ||
324 mg->mg_class != mc) {
325 continue;
326 }
327
328 /*
329 * If a metaslab group does not contain a fragmentation
330 * metric then just bail out.
331 */
332 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
333 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
334 return (ZFS_FRAG_INVALID);
335 }
336
337 /*
338 * Determine how much this metaslab_group is contributing
339 * to the overall pool fragmentation metric.
340 */
341 fragmentation += mg->mg_fragmentation *
342 metaslab_group_get_space(mg);
343 }
344 fragmentation /= metaslab_class_get_space(mc);
345
346 ASSERT3U(fragmentation, <=, 100);
347 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
348 return (fragmentation);
349}
350
351/*
352 * Calculate the amount of expandable space that is available in
353 * this metaslab class. If a device is expanded then its expandable
354 * space will be the amount of allocatable space that is currently not
355 * part of this metaslab class.
356 */
357uint64_t
358metaslab_class_expandable_space(metaslab_class_t *mc)
359{
360 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
361 uint64_t space = 0;
362 int c;
363
364 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
365 for (c = 0; c < rvd->vdev_children; c++) {
366 vdev_t *tvd = rvd->vdev_child[c];
367 metaslab_group_t *mg = tvd->vdev_mg;
368
369 if (tvd->vdev_ishole || tvd->vdev_ms_shift == 0 ||
370 mg->mg_class != mc) {
371 continue;
372 }
373
374 space += tvd->vdev_max_asize - tvd->vdev_asize;
375 }
376 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
377 return (space);
378}
379
34dc7c2f
BB
380/*
381 * ==========================================================================
382 * Metaslab groups
383 * ==========================================================================
384 */
385static int
386metaslab_compare(const void *x1, const void *x2)
387{
388 const metaslab_t *m1 = x1;
389 const metaslab_t *m2 = x2;
390
391 if (m1->ms_weight < m2->ms_weight)
392 return (1);
393 if (m1->ms_weight > m2->ms_weight)
394 return (-1);
395
396 /*
397 * If the weights are identical, use the offset to force uniqueness.
398 */
93cf2076 399 if (m1->ms_start < m2->ms_start)
34dc7c2f 400 return (-1);
93cf2076 401 if (m1->ms_start > m2->ms_start)
34dc7c2f
BB
402 return (1);
403
404 ASSERT3P(m1, ==, m2);
405
406 return (0);
407}
408
ac72fac3
GW
409/*
410 * Update the allocatable flag and the metaslab group's capacity.
411 * The allocatable flag is set to true if the capacity is below
412 * the zfs_mg_noalloc_threshold. If a metaslab group transitions
413 * from allocatable to non-allocatable or vice versa then the metaslab
414 * group's class is updated to reflect the transition.
415 */
416static void
417metaslab_group_alloc_update(metaslab_group_t *mg)
418{
419 vdev_t *vd = mg->mg_vd;
420 metaslab_class_t *mc = mg->mg_class;
421 vdev_stat_t *vs = &vd->vdev_stat;
422 boolean_t was_allocatable;
423
424 ASSERT(vd == vd->vdev_top);
425
426 mutex_enter(&mg->mg_lock);
427 was_allocatable = mg->mg_allocatable;
428
429 mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
430 (vs->vs_space + 1);
431
f3a7f661
GW
432 /*
433 * A metaslab group is considered allocatable if it has plenty
434 * of free space or is not heavily fragmented. We only take
435 * fragmentation into account if the metaslab group has a valid
436 * fragmentation metric (i.e. a value between 0 and 100).
437 */
438 mg->mg_allocatable = (mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
439 (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
440 mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
ac72fac3
GW
441
442 /*
443 * The mc_alloc_groups maintains a count of the number of
444 * groups in this metaslab class that are still above the
445 * zfs_mg_noalloc_threshold. This is used by the allocating
446 * threads to determine if they should avoid allocations to
447 * a given group. The allocator will avoid allocations to a group
448 * if that group has reached or is below the zfs_mg_noalloc_threshold
449 * and there are still other groups that are above the threshold.
450 * When a group transitions from allocatable to non-allocatable or
451 * vice versa we update the metaslab class to reflect that change.
452 * When the mc_alloc_groups value drops to 0 that means that all
453 * groups have reached the zfs_mg_noalloc_threshold making all groups
454 * eligible for allocations. This effectively means that all devices
455 * are balanced again.
456 */
457 if (was_allocatable && !mg->mg_allocatable)
458 mc->mc_alloc_groups--;
459 else if (!was_allocatable && mg->mg_allocatable)
460 mc->mc_alloc_groups++;
f3a7f661 461
ac72fac3
GW
462 mutex_exit(&mg->mg_lock);
463}
464
34dc7c2f
BB
465metaslab_group_t *
466metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
467{
468 metaslab_group_t *mg;
469
b8d06fca 470 mg = kmem_zalloc(sizeof (metaslab_group_t), KM_PUSHPAGE);
34dc7c2f
BB
471 mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
472 avl_create(&mg->mg_metaslab_tree, metaslab_compare,
473 sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
34dc7c2f 474 mg->mg_vd = vd;
428870ff
BB
475 mg->mg_class = mc;
476 mg->mg_activation_count = 0;
34dc7c2f 477
3c51c5cb 478 mg->mg_taskq = taskq_create("metaslab_group_taskq", metaslab_load_pct,
93cf2076
GW
479 minclsyspri, 10, INT_MAX, TASKQ_THREADS_CPU_PCT);
480
34dc7c2f
BB
481 return (mg);
482}
483
484void
485metaslab_group_destroy(metaslab_group_t *mg)
486{
428870ff
BB
487 ASSERT(mg->mg_prev == NULL);
488 ASSERT(mg->mg_next == NULL);
489 /*
490 * We may have gone below zero with the activation count
491 * either because we never activated in the first place or
492 * because we're done, and possibly removing the vdev.
493 */
494 ASSERT(mg->mg_activation_count <= 0);
495
3c51c5cb 496 taskq_destroy(mg->mg_taskq);
34dc7c2f
BB
497 avl_destroy(&mg->mg_metaslab_tree);
498 mutex_destroy(&mg->mg_lock);
499 kmem_free(mg, sizeof (metaslab_group_t));
500}
501
428870ff
BB
502void
503metaslab_group_activate(metaslab_group_t *mg)
504{
505 metaslab_class_t *mc = mg->mg_class;
506 metaslab_group_t *mgprev, *mgnext;
507
508 ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
509
510 ASSERT(mc->mc_rotor != mg);
511 ASSERT(mg->mg_prev == NULL);
512 ASSERT(mg->mg_next == NULL);
513 ASSERT(mg->mg_activation_count <= 0);
514
515 if (++mg->mg_activation_count <= 0)
516 return;
517
518 mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
ac72fac3 519 metaslab_group_alloc_update(mg);
428870ff
BB
520
521 if ((mgprev = mc->mc_rotor) == NULL) {
522 mg->mg_prev = mg;
523 mg->mg_next = mg;
524 } else {
525 mgnext = mgprev->mg_next;
526 mg->mg_prev = mgprev;
527 mg->mg_next = mgnext;
528 mgprev->mg_next = mg;
529 mgnext->mg_prev = mg;
530 }
531 mc->mc_rotor = mg;
532}
533
534void
535metaslab_group_passivate(metaslab_group_t *mg)
536{
537 metaslab_class_t *mc = mg->mg_class;
538 metaslab_group_t *mgprev, *mgnext;
539
540 ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
541
542 if (--mg->mg_activation_count != 0) {
543 ASSERT(mc->mc_rotor != mg);
544 ASSERT(mg->mg_prev == NULL);
545 ASSERT(mg->mg_next == NULL);
546 ASSERT(mg->mg_activation_count < 0);
547 return;
548 }
549
93cf2076 550 taskq_wait(mg->mg_taskq);
f3a7f661 551 metaslab_group_alloc_update(mg);
93cf2076 552
428870ff
BB
553 mgprev = mg->mg_prev;
554 mgnext = mg->mg_next;
555
556 if (mg == mgnext) {
557 mc->mc_rotor = NULL;
558 } else {
559 mc->mc_rotor = mgnext;
560 mgprev->mg_next = mgnext;
561 mgnext->mg_prev = mgprev;
562 }
563
564 mg->mg_prev = NULL;
565 mg->mg_next = NULL;
566}
567
f3a7f661
GW
568uint64_t
569metaslab_group_get_space(metaslab_group_t *mg)
570{
571 return ((1ULL << mg->mg_vd->vdev_ms_shift) * mg->mg_vd->vdev_ms_count);
572}
573
574void
575metaslab_group_histogram_verify(metaslab_group_t *mg)
576{
577 uint64_t *mg_hist;
578 vdev_t *vd = mg->mg_vd;
579 uint64_t ashift = vd->vdev_ashift;
580 int i, m;
581
582 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
583 return;
584
585 mg_hist = kmem_zalloc(sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE,
586 KM_PUSHPAGE);
587
588 ASSERT3U(RANGE_TREE_HISTOGRAM_SIZE, >=,
589 SPACE_MAP_HISTOGRAM_SIZE + ashift);
590
591 for (m = 0; m < vd->vdev_ms_count; m++) {
592 metaslab_t *msp = vd->vdev_ms[m];
593
594 if (msp->ms_sm == NULL)
595 continue;
596
597 for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
598 mg_hist[i + ashift] +=
599 msp->ms_sm->sm_phys->smp_histogram[i];
600 }
601
602 for (i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i ++)
603 VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
604
605 kmem_free(mg_hist, sizeof (uint64_t) * RANGE_TREE_HISTOGRAM_SIZE);
606}
607
34dc7c2f 608static void
f3a7f661 609metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
34dc7c2f 610{
f3a7f661
GW
611 metaslab_class_t *mc = mg->mg_class;
612 uint64_t ashift = mg->mg_vd->vdev_ashift;
613 int i;
614
615 ASSERT(MUTEX_HELD(&msp->ms_lock));
616 if (msp->ms_sm == NULL)
617 return;
618
34dc7c2f 619 mutex_enter(&mg->mg_lock);
f3a7f661
GW
620 for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
621 mg->mg_histogram[i + ashift] +=
622 msp->ms_sm->sm_phys->smp_histogram[i];
623 mc->mc_histogram[i + ashift] +=
624 msp->ms_sm->sm_phys->smp_histogram[i];
625 }
626 mutex_exit(&mg->mg_lock);
627}
628
629void
630metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
631{
632 metaslab_class_t *mc = mg->mg_class;
633 uint64_t ashift = mg->mg_vd->vdev_ashift;
634 int i;
635
636 ASSERT(MUTEX_HELD(&msp->ms_lock));
637 if (msp->ms_sm == NULL)
638 return;
639
640 mutex_enter(&mg->mg_lock);
641 for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
642 ASSERT3U(mg->mg_histogram[i + ashift], >=,
643 msp->ms_sm->sm_phys->smp_histogram[i]);
644 ASSERT3U(mc->mc_histogram[i + ashift], >=,
645 msp->ms_sm->sm_phys->smp_histogram[i]);
646
647 mg->mg_histogram[i + ashift] -=
648 msp->ms_sm->sm_phys->smp_histogram[i];
649 mc->mc_histogram[i + ashift] -=
650 msp->ms_sm->sm_phys->smp_histogram[i];
651 }
652 mutex_exit(&mg->mg_lock);
653}
654
655static void
656metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
657{
34dc7c2f 658 ASSERT(msp->ms_group == NULL);
f3a7f661 659 mutex_enter(&mg->mg_lock);
34dc7c2f
BB
660 msp->ms_group = mg;
661 msp->ms_weight = 0;
662 avl_add(&mg->mg_metaslab_tree, msp);
663 mutex_exit(&mg->mg_lock);
f3a7f661
GW
664
665 mutex_enter(&msp->ms_lock);
666 metaslab_group_histogram_add(mg, msp);
667 mutex_exit(&msp->ms_lock);
34dc7c2f
BB
668}
669
670static void
671metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
672{
f3a7f661
GW
673 mutex_enter(&msp->ms_lock);
674 metaslab_group_histogram_remove(mg, msp);
675 mutex_exit(&msp->ms_lock);
676
34dc7c2f
BB
677 mutex_enter(&mg->mg_lock);
678 ASSERT(msp->ms_group == mg);
679 avl_remove(&mg->mg_metaslab_tree, msp);
680 msp->ms_group = NULL;
681 mutex_exit(&mg->mg_lock);
682}
683
684static void
685metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
686{
687 /*
688 * Although in principle the weight can be any value, in
f3a7f661 689 * practice we do not use values in the range [1, 511].
34dc7c2f 690 */
f3a7f661 691 ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
34dc7c2f
BB
692 ASSERT(MUTEX_HELD(&msp->ms_lock));
693
694 mutex_enter(&mg->mg_lock);
695 ASSERT(msp->ms_group == mg);
696 avl_remove(&mg->mg_metaslab_tree, msp);
697 msp->ms_weight = weight;
698 avl_add(&mg->mg_metaslab_tree, msp);
699 mutex_exit(&mg->mg_lock);
700}
701
f3a7f661
GW
702/*
703 * Calculate the fragmentation for a given metaslab group. We can use
704 * a simple average here since all metaslabs within the group must have
705 * the same size. The return value will be a value between 0 and 100
706 * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
707 * group have a fragmentation metric.
708 */
709uint64_t
710metaslab_group_fragmentation(metaslab_group_t *mg)
711{
712 vdev_t *vd = mg->mg_vd;
713 uint64_t fragmentation = 0;
714 uint64_t valid_ms = 0;
715 int m;
716
717 for (m = 0; m < vd->vdev_ms_count; m++) {
718 metaslab_t *msp = vd->vdev_ms[m];
719
720 if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
721 continue;
722
723 valid_ms++;
724 fragmentation += msp->ms_fragmentation;
725 }
726
727 if (valid_ms <= vd->vdev_ms_count / 2)
728 return (ZFS_FRAG_INVALID);
729
730 fragmentation /= valid_ms;
731 ASSERT3U(fragmentation, <=, 100);
732 return (fragmentation);
733}
734
ac72fac3
GW
735/*
736 * Determine if a given metaslab group should skip allocations. A metaslab
f3a7f661
GW
737 * group should avoid allocations if its free capacity is less than the
738 * zfs_mg_noalloc_threshold or its fragmentation metric is greater than
739 * zfs_mg_fragmentation_threshold and there is at least one metaslab group
ac72fac3
GW
740 * that can still handle allocations.
741 */
742static boolean_t
743metaslab_group_allocatable(metaslab_group_t *mg)
744{
745 vdev_t *vd = mg->mg_vd;
746 spa_t *spa = vd->vdev_spa;
747 metaslab_class_t *mc = mg->mg_class;
748
749 /*
f3a7f661
GW
750 * We use two key metrics to determine if a metaslab group is
751 * considered allocatable -- free space and fragmentation. If
752 * the free space is greater than the free space threshold and
753 * the fragmentation is less than the fragmentation threshold then
754 * consider the group allocatable. There are two case when we will
755 * not consider these key metrics. The first is if the group is
756 * associated with a slog device and the second is if all groups
757 * in this metaslab class have already been consider ineligible
758 * for allocations.
ac72fac3 759 */
f3a7f661
GW
760 return ((mg->mg_free_capacity > zfs_mg_noalloc_threshold &&
761 (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
762 mg->mg_fragmentation <= zfs_mg_fragmentation_threshold)) ||
ac72fac3
GW
763 mc != spa_normal_class(spa) || mc->mc_alloc_groups == 0);
764}
765
428870ff
BB
766/*
767 * ==========================================================================
93cf2076 768 * Range tree callbacks
428870ff
BB
769 * ==========================================================================
770 */
93cf2076
GW
771
772/*
773 * Comparison function for the private size-ordered tree. Tree is sorted
774 * by size, larger sizes at the end of the tree.
775 */
428870ff 776static int
93cf2076 777metaslab_rangesize_compare(const void *x1, const void *x2)
428870ff 778{
93cf2076
GW
779 const range_seg_t *r1 = x1;
780 const range_seg_t *r2 = x2;
781 uint64_t rs_size1 = r1->rs_end - r1->rs_start;
782 uint64_t rs_size2 = r2->rs_end - r2->rs_start;
428870ff 783
93cf2076 784 if (rs_size1 < rs_size2)
428870ff 785 return (-1);
93cf2076 786 if (rs_size1 > rs_size2)
428870ff
BB
787 return (1);
788
93cf2076 789 if (r1->rs_start < r2->rs_start)
428870ff 790 return (-1);
93cf2076
GW
791
792 if (r1->rs_start > r2->rs_start)
428870ff
BB
793 return (1);
794
795 return (0);
796}
797
34dc7c2f 798/*
93cf2076
GW
799 * Create any block allocator specific components. The current allocators
800 * rely on using both a size-ordered range_tree_t and an array of uint64_t's.
34dc7c2f 801 */
93cf2076
GW
802static void
803metaslab_rt_create(range_tree_t *rt, void *arg)
34dc7c2f 804{
93cf2076 805 metaslab_t *msp = arg;
34dc7c2f 806
93cf2076
GW
807 ASSERT3P(rt->rt_arg, ==, msp);
808 ASSERT(msp->ms_tree == NULL);
34dc7c2f 809
93cf2076
GW
810 avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
811 sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
9babb374
BB
812}
813
93cf2076
GW
814/*
815 * Destroy the block allocator specific components.
816 */
9babb374 817static void
93cf2076 818metaslab_rt_destroy(range_tree_t *rt, void *arg)
9babb374 819{
93cf2076 820 metaslab_t *msp = arg;
428870ff 821
93cf2076
GW
822 ASSERT3P(rt->rt_arg, ==, msp);
823 ASSERT3P(msp->ms_tree, ==, rt);
824 ASSERT0(avl_numnodes(&msp->ms_size_tree));
428870ff 825
93cf2076 826 avl_destroy(&msp->ms_size_tree);
9babb374
BB
827}
828
829static void
93cf2076 830metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg)
9babb374 831{
93cf2076 832 metaslab_t *msp = arg;
9babb374 833
93cf2076
GW
834 ASSERT3P(rt->rt_arg, ==, msp);
835 ASSERT3P(msp->ms_tree, ==, rt);
836 VERIFY(!msp->ms_condensing);
837 avl_add(&msp->ms_size_tree, rs);
34dc7c2f
BB
838}
839
34dc7c2f 840static void
93cf2076 841metaslab_rt_remove(range_tree_t *rt, range_seg_t *rs, void *arg)
34dc7c2f 842{
93cf2076
GW
843 metaslab_t *msp = arg;
844
845 ASSERT3P(rt->rt_arg, ==, msp);
846 ASSERT3P(msp->ms_tree, ==, rt);
847 VERIFY(!msp->ms_condensing);
848 avl_remove(&msp->ms_size_tree, rs);
34dc7c2f
BB
849}
850
34dc7c2f 851static void
93cf2076 852metaslab_rt_vacate(range_tree_t *rt, void *arg)
34dc7c2f 853{
93cf2076
GW
854 metaslab_t *msp = arg;
855
856 ASSERT3P(rt->rt_arg, ==, msp);
857 ASSERT3P(msp->ms_tree, ==, rt);
858
859 /*
860 * Normally one would walk the tree freeing nodes along the way.
861 * Since the nodes are shared with the range trees we can avoid
862 * walking all nodes and just reinitialize the avl tree. The nodes
863 * will be freed by the range tree, so we don't want to free them here.
864 */
865 avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
866 sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
34dc7c2f
BB
867}
868
93cf2076
GW
869static range_tree_ops_t metaslab_rt_ops = {
870 metaslab_rt_create,
871 metaslab_rt_destroy,
872 metaslab_rt_add,
873 metaslab_rt_remove,
874 metaslab_rt_vacate
875};
876
877/*
878 * ==========================================================================
879 * Metaslab block operations
880 * ==========================================================================
881 */
882
9babb374 883/*
428870ff 884 * Return the maximum contiguous segment within the metaslab.
9babb374 885 */
9babb374 886uint64_t
93cf2076 887metaslab_block_maxsize(metaslab_t *msp)
9babb374 888{
93cf2076
GW
889 avl_tree_t *t = &msp->ms_size_tree;
890 range_seg_t *rs;
9babb374 891
93cf2076 892 if (t == NULL || (rs = avl_last(t)) == NULL)
9babb374
BB
893 return (0ULL);
894
93cf2076
GW
895 return (rs->rs_end - rs->rs_start);
896}
897
898uint64_t
899metaslab_block_alloc(metaslab_t *msp, uint64_t size)
900{
901 uint64_t start;
902 range_tree_t *rt = msp->ms_tree;
903
904 VERIFY(!msp->ms_condensing);
905
906 start = msp->ms_ops->msop_alloc(msp, size);
907 if (start != -1ULL) {
908 vdev_t *vd = msp->ms_group->mg_vd;
909
910 VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
911 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
912 VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
913 range_tree_remove(rt, start, size);
914 }
915 return (start);
916}
917
918/*
919 * ==========================================================================
920 * Common allocator routines
921 * ==========================================================================
922 */
923
924#if defined(WITH_FF_BLOCK_ALLOCATOR) || \
925 defined(WITH_DF_BLOCK_ALLOCATOR) || \
926 defined(WITH_CF_BLOCK_ALLOCATOR)
927/*
928 * This is a helper function that can be used by the allocator to find
929 * a suitable block to allocate. This will search the specified AVL
930 * tree looking for a block that matches the specified criteria.
931 */
932static uint64_t
933metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
934 uint64_t align)
935{
936 range_seg_t *rs, rsearch;
937 avl_index_t where;
938
939 rsearch.rs_start = *cursor;
940 rsearch.rs_end = *cursor + size;
941
942 rs = avl_find(t, &rsearch, &where);
943 if (rs == NULL)
944 rs = avl_nearest(t, where, AVL_AFTER);
945
946 while (rs != NULL) {
947 uint64_t offset = P2ROUNDUP(rs->rs_start, align);
948
949 if (offset + size <= rs->rs_end) {
950 *cursor = offset + size;
951 return (offset);
952 }
953 rs = AVL_NEXT(t, rs);
954 }
955
956 /*
957 * If we know we've searched the whole map (*cursor == 0), give up.
958 * Otherwise, reset the cursor to the beginning and try again.
959 */
960 if (*cursor == 0)
961 return (-1ULL);
962
963 *cursor = 0;
964 return (metaslab_block_picker(t, cursor, size, align));
9babb374 965}
93cf2076 966#endif /* WITH_FF/DF/CF_BLOCK_ALLOCATOR */
9babb374 967
22c81dd8 968#if defined(WITH_FF_BLOCK_ALLOCATOR)
428870ff
BB
969/*
970 * ==========================================================================
971 * The first-fit block allocator
972 * ==========================================================================
973 */
974static uint64_t
93cf2076 975metaslab_ff_alloc(metaslab_t *msp, uint64_t size)
9babb374 976{
93cf2076
GW
977 /*
978 * Find the largest power of 2 block size that evenly divides the
979 * requested size. This is used to try to allocate blocks with similar
980 * alignment from the same area of the metaslab (i.e. same cursor
981 * bucket) but it does not guarantee that other allocations sizes
982 * may exist in the same region.
983 */
428870ff 984 uint64_t align = size & -size;
9bd274dd 985 uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
93cf2076 986 avl_tree_t *t = &msp->ms_tree->rt_root;
9babb374 987
428870ff 988 return (metaslab_block_picker(t, cursor, size, align));
9babb374
BB
989}
990
93cf2076 991static metaslab_ops_t metaslab_ff_ops = {
f3a7f661 992 metaslab_ff_alloc
428870ff 993};
9babb374 994
93cf2076 995metaslab_ops_t *zfs_metaslab_ops = &metaslab_ff_ops;
22c81dd8
BB
996#endif /* WITH_FF_BLOCK_ALLOCATOR */
997
998#if defined(WITH_DF_BLOCK_ALLOCATOR)
428870ff
BB
999/*
1000 * ==========================================================================
1001 * Dynamic block allocator -
1002 * Uses the first fit allocation scheme until space get low and then
1003 * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
1004 * and metaslab_df_free_pct to determine when to switch the allocation scheme.
1005 * ==========================================================================
1006 */
9babb374 1007static uint64_t
93cf2076 1008metaslab_df_alloc(metaslab_t *msp, uint64_t size)
9babb374 1009{
93cf2076
GW
1010 /*
1011 * Find the largest power of 2 block size that evenly divides the
1012 * requested size. This is used to try to allocate blocks with similar
1013 * alignment from the same area of the metaslab (i.e. same cursor
1014 * bucket) but it does not guarantee that other allocations sizes
1015 * may exist in the same region.
1016 */
9babb374 1017 uint64_t align = size & -size;
9bd274dd 1018 uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
93cf2076
GW
1019 range_tree_t *rt = msp->ms_tree;
1020 avl_tree_t *t = &rt->rt_root;
1021 uint64_t max_size = metaslab_block_maxsize(msp);
1022 int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
9babb374 1023
93cf2076
GW
1024 ASSERT(MUTEX_HELD(&msp->ms_lock));
1025 ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
9babb374
BB
1026
1027 if (max_size < size)
1028 return (-1ULL);
1029
1030 /*
1031 * If we're running low on space switch to using the size
1032 * sorted AVL tree (best-fit).
1033 */
1034 if (max_size < metaslab_df_alloc_threshold ||
1035 free_pct < metaslab_df_free_pct) {
93cf2076 1036 t = &msp->ms_size_tree;
9babb374
BB
1037 *cursor = 0;
1038 }
1039
1040 return (metaslab_block_picker(t, cursor, size, 1ULL));
1041}
1042
93cf2076 1043static metaslab_ops_t metaslab_df_ops = {
f3a7f661 1044 metaslab_df_alloc
34dc7c2f
BB
1045};
1046
93cf2076 1047metaslab_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
22c81dd8
BB
1048#endif /* WITH_DF_BLOCK_ALLOCATOR */
1049
93cf2076 1050#if defined(WITH_CF_BLOCK_ALLOCATOR)
428870ff
BB
1051/*
1052 * ==========================================================================
93cf2076
GW
1053 * Cursor fit block allocator -
1054 * Select the largest region in the metaslab, set the cursor to the beginning
1055 * of the range and the cursor_end to the end of the range. As allocations
1056 * are made advance the cursor. Continue allocating from the cursor until
1057 * the range is exhausted and then find a new range.
428870ff
BB
1058 * ==========================================================================
1059 */
1060static uint64_t
93cf2076 1061metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
428870ff 1062{
93cf2076
GW
1063 range_tree_t *rt = msp->ms_tree;
1064 avl_tree_t *t = &msp->ms_size_tree;
1065 uint64_t *cursor = &msp->ms_lbas[0];
1066 uint64_t *cursor_end = &msp->ms_lbas[1];
428870ff
BB
1067 uint64_t offset = 0;
1068
93cf2076
GW
1069 ASSERT(MUTEX_HELD(&msp->ms_lock));
1070 ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&rt->rt_root));
428870ff 1071
93cf2076 1072 ASSERT3U(*cursor_end, >=, *cursor);
428870ff 1073
93cf2076
GW
1074 if ((*cursor + size) > *cursor_end) {
1075 range_seg_t *rs;
428870ff 1076
93cf2076
GW
1077 rs = avl_last(&msp->ms_size_tree);
1078 if (rs == NULL || (rs->rs_end - rs->rs_start) < size)
1079 return (-1ULL);
428870ff 1080
93cf2076
GW
1081 *cursor = rs->rs_start;
1082 *cursor_end = rs->rs_end;
428870ff 1083 }
93cf2076
GW
1084
1085 offset = *cursor;
1086 *cursor += size;
1087
428870ff
BB
1088 return (offset);
1089}
1090
93cf2076 1091static metaslab_ops_t metaslab_cf_ops = {
f3a7f661 1092 metaslab_cf_alloc
428870ff
BB
1093};
1094
93cf2076
GW
1095metaslab_ops_t *zfs_metaslab_ops = &metaslab_cf_ops;
1096#endif /* WITH_CF_BLOCK_ALLOCATOR */
22c81dd8
BB
1097
1098#if defined(WITH_NDF_BLOCK_ALLOCATOR)
93cf2076
GW
1099/*
1100 * ==========================================================================
1101 * New dynamic fit allocator -
1102 * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
1103 * contiguous blocks. If no region is found then just use the largest segment
1104 * that remains.
1105 * ==========================================================================
1106 */
1107
1108/*
1109 * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
1110 * to request from the allocator.
1111 */
428870ff
BB
1112uint64_t metaslab_ndf_clump_shift = 4;
1113
1114static uint64_t
93cf2076 1115metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
428870ff 1116{
93cf2076 1117 avl_tree_t *t = &msp->ms_tree->rt_root;
428870ff 1118 avl_index_t where;
93cf2076 1119 range_seg_t *rs, rsearch;
9bd274dd 1120 uint64_t hbit = highbit64(size);
93cf2076
GW
1121 uint64_t *cursor = &msp->ms_lbas[hbit - 1];
1122 uint64_t max_size = metaslab_block_maxsize(msp);
428870ff 1123
93cf2076
GW
1124 ASSERT(MUTEX_HELD(&msp->ms_lock));
1125 ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
428870ff
BB
1126
1127 if (max_size < size)
1128 return (-1ULL);
1129
93cf2076
GW
1130 rsearch.rs_start = *cursor;
1131 rsearch.rs_end = *cursor + size;
428870ff 1132
93cf2076
GW
1133 rs = avl_find(t, &rsearch, &where);
1134 if (rs == NULL || (rs->rs_end - rs->rs_start) < size) {
1135 t = &msp->ms_size_tree;
428870ff 1136
93cf2076
GW
1137 rsearch.rs_start = 0;
1138 rsearch.rs_end = MIN(max_size,
428870ff 1139 1ULL << (hbit + metaslab_ndf_clump_shift));
93cf2076
GW
1140 rs = avl_find(t, &rsearch, &where);
1141 if (rs == NULL)
1142 rs = avl_nearest(t, where, AVL_AFTER);
1143 ASSERT(rs != NULL);
428870ff
BB
1144 }
1145
93cf2076
GW
1146 if ((rs->rs_end - rs->rs_start) >= size) {
1147 *cursor = rs->rs_start + size;
1148 return (rs->rs_start);
428870ff
BB
1149 }
1150 return (-1ULL);
1151}
1152
93cf2076 1153static metaslab_ops_t metaslab_ndf_ops = {
f3a7f661 1154 metaslab_ndf_alloc
428870ff
BB
1155};
1156
93cf2076 1157metaslab_ops_t *zfs_metaslab_ops = &metaslab_ndf_ops;
22c81dd8 1158#endif /* WITH_NDF_BLOCK_ALLOCATOR */
9babb374 1159
93cf2076 1160
34dc7c2f
BB
1161/*
1162 * ==========================================================================
1163 * Metaslabs
1164 * ==========================================================================
1165 */
93cf2076
GW
1166
1167/*
1168 * Wait for any in-progress metaslab loads to complete.
1169 */
1170void
1171metaslab_load_wait(metaslab_t *msp)
1172{
1173 ASSERT(MUTEX_HELD(&msp->ms_lock));
1174
1175 while (msp->ms_loading) {
1176 ASSERT(!msp->ms_loaded);
1177 cv_wait(&msp->ms_load_cv, &msp->ms_lock);
1178 }
1179}
1180
1181int
1182metaslab_load(metaslab_t *msp)
1183{
1184 int error = 0;
1185 int t;
1186
1187 ASSERT(MUTEX_HELD(&msp->ms_lock));
1188 ASSERT(!msp->ms_loaded);
1189 ASSERT(!msp->ms_loading);
1190
1191 msp->ms_loading = B_TRUE;
1192
1193 /*
1194 * If the space map has not been allocated yet, then treat
1195 * all the space in the metaslab as free and add it to the
1196 * ms_tree.
1197 */
1198 if (msp->ms_sm != NULL)
1199 error = space_map_load(msp->ms_sm, msp->ms_tree, SM_FREE);
1200 else
1201 range_tree_add(msp->ms_tree, msp->ms_start, msp->ms_size);
1202
1203 msp->ms_loaded = (error == 0);
1204 msp->ms_loading = B_FALSE;
1205
1206 if (msp->ms_loaded) {
1207 for (t = 0; t < TXG_DEFER_SIZE; t++) {
1208 range_tree_walk(msp->ms_defertree[t],
1209 range_tree_remove, msp->ms_tree);
1210 }
1211 }
1212 cv_broadcast(&msp->ms_load_cv);
1213 return (error);
1214}
1215
1216void
1217metaslab_unload(metaslab_t *msp)
1218{
1219 ASSERT(MUTEX_HELD(&msp->ms_lock));
1220 range_tree_vacate(msp->ms_tree, NULL, NULL);
1221 msp->ms_loaded = B_FALSE;
1222 msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
1223}
1224
34dc7c2f 1225metaslab_t *
93cf2076 1226metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object, uint64_t txg)
34dc7c2f
BB
1227{
1228 vdev_t *vd = mg->mg_vd;
93cf2076 1229 objset_t *mos = vd->vdev_spa->spa_meta_objset;
34dc7c2f
BB
1230 metaslab_t *msp;
1231
b8d06fca 1232 msp = kmem_zalloc(sizeof (metaslab_t), KM_PUSHPAGE);
34dc7c2f 1233 mutex_init(&msp->ms_lock, NULL, MUTEX_DEFAULT, NULL);
93cf2076
GW
1234 cv_init(&msp->ms_load_cv, NULL, CV_DEFAULT, NULL);
1235 msp->ms_id = id;
1236 msp->ms_start = id << vd->vdev_ms_shift;
1237 msp->ms_size = 1ULL << vd->vdev_ms_shift;
34dc7c2f 1238
93cf2076
GW
1239 /*
1240 * We only open space map objects that already exist. All others
1241 * will be opened when we finally allocate an object for it.
1242 */
1243 if (object != 0) {
1244 VERIFY0(space_map_open(&msp->ms_sm, mos, object, msp->ms_start,
1245 msp->ms_size, vd->vdev_ashift, &msp->ms_lock));
1246 ASSERT(msp->ms_sm != NULL);
1247 }
34dc7c2f
BB
1248
1249 /*
93cf2076
GW
1250 * We create the main range tree here, but we don't create the
1251 * alloctree and freetree until metaslab_sync_done(). This serves
34dc7c2f
BB
1252 * two purposes: it allows metaslab_sync_done() to detect the
1253 * addition of new space; and for debugging, it ensures that we'd
1254 * data fault on any attempt to use this metaslab before it's ready.
1255 */
93cf2076 1256 msp->ms_tree = range_tree_create(&metaslab_rt_ops, msp, &msp->ms_lock);
34dc7c2f
BB
1257 metaslab_group_add(mg, msp);
1258
f3a7f661 1259 msp->ms_fragmentation = metaslab_fragmentation(msp);
93cf2076 1260 msp->ms_ops = mg->mg_class->mc_ops;
428870ff 1261
34dc7c2f
BB
1262 /*
1263 * If we're opening an existing pool (txg == 0) or creating
1264 * a new one (txg == TXG_INITIAL), all space is available now.
1265 * If we're adding space to an existing pool, the new space
1266 * does not become available until after this txg has synced.
1267 */
1268 if (txg <= TXG_INITIAL)
1269 metaslab_sync_done(msp, 0);
1270
93cf2076
GW
1271 /*
1272 * If metaslab_debug_load is set and we're initializing a metaslab
1273 * that has an allocated space_map object then load the its space
1274 * map so that can verify frees.
1275 */
1276 if (metaslab_debug_load && msp->ms_sm != NULL) {
1277 mutex_enter(&msp->ms_lock);
1278 VERIFY0(metaslab_load(msp));
1279 mutex_exit(&msp->ms_lock);
1280 }
1281
34dc7c2f 1282 if (txg != 0) {
34dc7c2f 1283 vdev_dirty(vd, 0, NULL, txg);
428870ff 1284 vdev_dirty(vd, VDD_METASLAB, msp, txg);
34dc7c2f
BB
1285 }
1286
1287 return (msp);
1288}
1289
1290void
1291metaslab_fini(metaslab_t *msp)
1292{
d6320ddb 1293 int t;
34dc7c2f 1294
93cf2076 1295 metaslab_group_t *mg = msp->ms_group;
34dc7c2f
BB
1296
1297 metaslab_group_remove(mg, msp);
1298
1299 mutex_enter(&msp->ms_lock);
1300
93cf2076
GW
1301 VERIFY(msp->ms_group == NULL);
1302 vdev_space_update(mg->mg_vd, -space_map_allocated(msp->ms_sm),
1303 0, -msp->ms_size);
1304 space_map_close(msp->ms_sm);
1305
1306 metaslab_unload(msp);
1307 range_tree_destroy(msp->ms_tree);
34dc7c2f 1308
d6320ddb 1309 for (t = 0; t < TXG_SIZE; t++) {
93cf2076
GW
1310 range_tree_destroy(msp->ms_alloctree[t]);
1311 range_tree_destroy(msp->ms_freetree[t]);
34dc7c2f
BB
1312 }
1313
e51be066 1314 for (t = 0; t < TXG_DEFER_SIZE; t++) {
93cf2076 1315 range_tree_destroy(msp->ms_defertree[t]);
e51be066 1316 }
428870ff 1317
c99c9001 1318 ASSERT0(msp->ms_deferspace);
428870ff 1319
34dc7c2f 1320 mutex_exit(&msp->ms_lock);
93cf2076 1321 cv_destroy(&msp->ms_load_cv);
34dc7c2f
BB
1322 mutex_destroy(&msp->ms_lock);
1323
1324 kmem_free(msp, sizeof (metaslab_t));
1325}
1326
f3a7f661
GW
1327#define FRAGMENTATION_TABLE_SIZE 17
1328
93cf2076 1329/*
f3a7f661
GW
1330 * This table defines a segment size based fragmentation metric that will
1331 * allow each metaslab to derive its own fragmentation value. This is done
1332 * by calculating the space in each bucket of the spacemap histogram and
1333 * multiplying that by the fragmetation metric in this table. Doing
1334 * this for all buckets and dividing it by the total amount of free
1335 * space in this metaslab (i.e. the total free space in all buckets) gives
1336 * us the fragmentation metric. This means that a high fragmentation metric
1337 * equates to most of the free space being comprised of small segments.
1338 * Conversely, if the metric is low, then most of the free space is in
1339 * large segments. A 10% change in fragmentation equates to approximately
1340 * double the number of segments.
93cf2076 1341 *
f3a7f661
GW
1342 * This table defines 0% fragmented space using 16MB segments. Testing has
1343 * shown that segments that are greater than or equal to 16MB do not suffer
1344 * from drastic performance problems. Using this value, we derive the rest
1345 * of the table. Since the fragmentation value is never stored on disk, it
1346 * is possible to change these calculations in the future.
1347 */
1348int zfs_frag_table[FRAGMENTATION_TABLE_SIZE] = {
1349 100, /* 512B */
1350 100, /* 1K */
1351 98, /* 2K */
1352 95, /* 4K */
1353 90, /* 8K */
1354 80, /* 16K */
1355 70, /* 32K */
1356 60, /* 64K */
1357 50, /* 128K */
1358 40, /* 256K */
1359 30, /* 512K */
1360 20, /* 1M */
1361 15, /* 2M */
1362 10, /* 4M */
1363 5, /* 8M */
1364 0 /* 16M */
1365};
1366
1367/*
1368 * Calclate the metaslab's fragmentation metric. A return value
1369 * of ZFS_FRAG_INVALID means that the metaslab has not been upgraded and does
1370 * not support this metric. Otherwise, the return value should be in the
1371 * range [0, 100].
93cf2076
GW
1372 */
1373static uint64_t
f3a7f661 1374metaslab_fragmentation(metaslab_t *msp)
93cf2076 1375{
f3a7f661
GW
1376 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1377 uint64_t fragmentation = 0;
1378 uint64_t total = 0;
1379 boolean_t feature_enabled = spa_feature_is_enabled(spa,
1380 SPA_FEATURE_SPACEMAP_HISTOGRAM);
93cf2076
GW
1381 int i;
1382
f3a7f661
GW
1383 if (!feature_enabled)
1384 return (ZFS_FRAG_INVALID);
1385
93cf2076 1386 /*
f3a7f661
GW
1387 * A null space map means that the entire metaslab is free
1388 * and thus is not fragmented.
93cf2076 1389 */
f3a7f661
GW
1390 if (msp->ms_sm == NULL)
1391 return (0);
1392
1393 /*
1394 * If this metaslab's space_map has not been upgraded, flag it
1395 * so that we upgrade next time we encounter it.
1396 */
1397 if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
93cf2076
GW
1398 vdev_t *vd = msp->ms_group->mg_vd;
1399
8b0a0840
TC
1400 if (spa_writeable(vd->vdev_spa)) {
1401 uint64_t txg = spa_syncing_txg(spa);
1402
1403 msp->ms_condense_wanted = B_TRUE;
1404 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
1405 spa_dbgmsg(spa, "txg %llu, requesting force condense: "
1406 "msp %p, vd %p", txg, msp, vd);
1407 }
f3a7f661 1408 return (ZFS_FRAG_INVALID);
93cf2076
GW
1409 }
1410
f3a7f661
GW
1411 for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1412 uint64_t space = 0;
1413 uint8_t shift = msp->ms_sm->sm_shift;
1414 int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
1415 FRAGMENTATION_TABLE_SIZE - 1);
93cf2076 1416
93cf2076
GW
1417 if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
1418 continue;
1419
f3a7f661
GW
1420 space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
1421 total += space;
1422
1423 ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
1424 fragmentation += space * zfs_frag_table[idx];
93cf2076 1425 }
f3a7f661
GW
1426
1427 if (total > 0)
1428 fragmentation /= total;
1429 ASSERT3U(fragmentation, <=, 100);
1430 return (fragmentation);
93cf2076 1431}
34dc7c2f 1432
f3a7f661
GW
1433/*
1434 * Compute a weight -- a selection preference value -- for the given metaslab.
1435 * This is based on the amount of free space, the level of fragmentation,
1436 * the LBA range, and whether the metaslab is loaded.
1437 */
34dc7c2f
BB
1438static uint64_t
1439metaslab_weight(metaslab_t *msp)
1440{
1441 metaslab_group_t *mg = msp->ms_group;
34dc7c2f
BB
1442 vdev_t *vd = mg->mg_vd;
1443 uint64_t weight, space;
1444
1445 ASSERT(MUTEX_HELD(&msp->ms_lock));
1446
c2e42f9d
GW
1447 /*
1448 * This vdev is in the process of being removed so there is nothing
1449 * for us to do here.
1450 */
1451 if (vd->vdev_removing) {
93cf2076 1452 ASSERT0(space_map_allocated(msp->ms_sm));
c2e42f9d
GW
1453 ASSERT0(vd->vdev_ms_shift);
1454 return (0);
1455 }
1456
34dc7c2f
BB
1457 /*
1458 * The baseline weight is the metaslab's free space.
1459 */
93cf2076 1460 space = msp->ms_size - space_map_allocated(msp->ms_sm);
f3a7f661
GW
1461
1462 msp->ms_fragmentation = metaslab_fragmentation(msp);
1463 if (metaslab_fragmentation_factor_enabled &&
1464 msp->ms_fragmentation != ZFS_FRAG_INVALID) {
1465 /*
1466 * Use the fragmentation information to inversely scale
1467 * down the baseline weight. We need to ensure that we
1468 * don't exclude this metaslab completely when it's 100%
1469 * fragmented. To avoid this we reduce the fragmented value
1470 * by 1.
1471 */
1472 space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
1473
1474 /*
1475 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
1476 * this metaslab again. The fragmentation metric may have
1477 * decreased the space to something smaller than
1478 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
1479 * so that we can consume any remaining space.
1480 */
1481 if (space > 0 && space < SPA_MINBLOCKSIZE)
1482 space = SPA_MINBLOCKSIZE;
1483 }
34dc7c2f
BB
1484 weight = space;
1485
1486 /*
1487 * Modern disks have uniform bit density and constant angular velocity.
1488 * Therefore, the outer recording zones are faster (higher bandwidth)
1489 * than the inner zones by the ratio of outer to inner track diameter,
1490 * which is typically around 2:1. We account for this by assigning
1491 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
1492 * In effect, this means that we'll select the metaslab with the most
1493 * free bandwidth rather than simply the one with the most free space.
1494 */
f3a7f661
GW
1495 if (metaslab_lba_weighting_enabled) {
1496 weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
1497 ASSERT(weight >= space && weight <= 2 * space);
1498 }
428870ff 1499
f3a7f661
GW
1500 /*
1501 * If this metaslab is one we're actively using, adjust its
1502 * weight to make it preferable to any inactive metaslab so
1503 * we'll polish it off. If the fragmentation on this metaslab
1504 * has exceed our threshold, then don't mark it active.
1505 */
1506 if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
1507 msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
428870ff
BB
1508 weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
1509 }
34dc7c2f 1510
93cf2076 1511 return (weight);
34dc7c2f
BB
1512}
1513
1514static int
6d974228 1515metaslab_activate(metaslab_t *msp, uint64_t activation_weight)
34dc7c2f 1516{
34dc7c2f
BB
1517 ASSERT(MUTEX_HELD(&msp->ms_lock));
1518
1519 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
93cf2076
GW
1520 metaslab_load_wait(msp);
1521 if (!msp->ms_loaded) {
1522 int error = metaslab_load(msp);
1523 if (error) {
428870ff
BB
1524 metaslab_group_sort(msp->ms_group, msp, 0);
1525 return (error);
1526 }
34dc7c2f 1527 }
9babb374 1528
34dc7c2f
BB
1529 metaslab_group_sort(msp->ms_group, msp,
1530 msp->ms_weight | activation_weight);
1531 }
93cf2076 1532 ASSERT(msp->ms_loaded);
34dc7c2f
BB
1533 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
1534
1535 return (0);
1536}
1537
1538static void
1539metaslab_passivate(metaslab_t *msp, uint64_t size)
1540{
1541 /*
1542 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
1543 * this metaslab again. In that case, it had better be empty,
1544 * or we would be leaving space on the table.
1545 */
93cf2076 1546 ASSERT(size >= SPA_MINBLOCKSIZE || range_tree_space(msp->ms_tree) == 0);
34dc7c2f
BB
1547 metaslab_group_sort(msp->ms_group, msp, MIN(msp->ms_weight, size));
1548 ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
1549}
1550
93cf2076
GW
1551static void
1552metaslab_preload(void *arg)
1553{
1554 metaslab_t *msp = arg;
1555 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1556
080b3100
GW
1557 ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
1558
93cf2076
GW
1559 mutex_enter(&msp->ms_lock);
1560 metaslab_load_wait(msp);
1561 if (!msp->ms_loaded)
1562 (void) metaslab_load(msp);
1563
1564 /*
1565 * Set the ms_access_txg value so that we don't unload it right away.
1566 */
1567 msp->ms_access_txg = spa_syncing_txg(spa) + metaslab_unload_delay + 1;
1568 mutex_exit(&msp->ms_lock);
1569}
1570
1571static void
1572metaslab_group_preload(metaslab_group_t *mg)
1573{
1574 spa_t *spa = mg->mg_vd->vdev_spa;
1575 metaslab_t *msp;
1576 avl_tree_t *t = &mg->mg_metaslab_tree;
1577 int m = 0;
1578
1579 if (spa_shutting_down(spa) || !metaslab_preload_enabled) {
1580 taskq_wait(mg->mg_taskq);
1581 return;
1582 }
93cf2076 1583
080b3100 1584 mutex_enter(&mg->mg_lock);
93cf2076 1585 /*
080b3100 1586 * Load the next potential metaslabs
93cf2076 1587 */
080b3100
GW
1588 msp = avl_first(t);
1589 while (msp != NULL) {
1590 metaslab_t *msp_next = AVL_NEXT(t, msp);
93cf2076 1591
f3a7f661
GW
1592 /*
1593 * We preload only the maximum number of metaslabs specified
1594 * by metaslab_preload_limit. If a metaslab is being forced
1595 * to condense then we preload it too. This will ensure
1596 * that force condensing happens in the next txg.
1597 */
1598 if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
1599 msp = msp_next;
1600 continue;
1601 }
93cf2076 1602
080b3100
GW
1603 /*
1604 * We must drop the metaslab group lock here to preserve
1605 * lock ordering with the ms_lock (when grabbing both
1606 * the mg_lock and the ms_lock, the ms_lock must be taken
1607 * first). As a result, it is possible that the ordering
1608 * of the metaslabs within the avl tree may change before
1609 * we reacquire the lock. The metaslab cannot be removed from
1610 * the tree while we're in syncing context so it is safe to
1611 * drop the mg_lock here. If the metaslabs are reordered
1612 * nothing will break -- we just may end up loading a
1613 * less than optimal one.
1614 */
1615 mutex_exit(&mg->mg_lock);
93cf2076
GW
1616 VERIFY(taskq_dispatch(mg->mg_taskq, metaslab_preload,
1617 msp, TQ_PUSHPAGE) != 0);
080b3100
GW
1618 mutex_enter(&mg->mg_lock);
1619 msp = msp_next;
93cf2076
GW
1620 }
1621 mutex_exit(&mg->mg_lock);
1622}
1623
e51be066 1624/*
93cf2076
GW
1625 * Determine if the space map's on-disk footprint is past our tolerance
1626 * for inefficiency. We would like to use the following criteria to make
1627 * our decision:
e51be066
GW
1628 *
1629 * 1. The size of the space map object should not dramatically increase as a
93cf2076 1630 * result of writing out the free space range tree.
e51be066
GW
1631 *
1632 * 2. The minimal on-disk space map representation is zfs_condense_pct/100
93cf2076
GW
1633 * times the size than the free space range tree representation
1634 * (i.e. zfs_condense_pct = 110 and in-core = 1MB, minimal = 1.1.MB).
e51be066
GW
1635 *
1636 * Checking the first condition is tricky since we don't want to walk
1637 * the entire AVL tree calculating the estimated on-disk size. Instead we
93cf2076
GW
1638 * use the size-ordered range tree in the metaslab and calculate the
1639 * size required to write out the largest segment in our free tree. If the
e51be066
GW
1640 * size required to represent that segment on disk is larger than the space
1641 * map object then we avoid condensing this map.
1642 *
1643 * To determine the second criterion we use a best-case estimate and assume
1644 * each segment can be represented on-disk as a single 64-bit entry. We refer
1645 * to this best-case estimate as the space map's minimal form.
1646 */
1647static boolean_t
1648metaslab_should_condense(metaslab_t *msp)
1649{
93cf2076
GW
1650 space_map_t *sm = msp->ms_sm;
1651 range_seg_t *rs;
e51be066
GW
1652 uint64_t size, entries, segsz;
1653
1654 ASSERT(MUTEX_HELD(&msp->ms_lock));
93cf2076 1655 ASSERT(msp->ms_loaded);
e51be066
GW
1656
1657 /*
93cf2076 1658 * Use the ms_size_tree range tree, which is ordered by size, to
f3a7f661
GW
1659 * obtain the largest segment in the free tree. We always condense
1660 * metaslabs that are empty and metaslabs for which a condense
1661 * request has been made.
e51be066 1662 */
93cf2076 1663 rs = avl_last(&msp->ms_size_tree);
f3a7f661 1664 if (rs == NULL || msp->ms_condense_wanted)
e51be066
GW
1665 return (B_TRUE);
1666
1667 /*
1668 * Calculate the number of 64-bit entries this segment would
1669 * require when written to disk. If this single segment would be
1670 * larger on-disk than the entire current on-disk structure, then
1671 * clearly condensing will increase the on-disk structure size.
1672 */
93cf2076 1673 size = (rs->rs_end - rs->rs_start) >> sm->sm_shift;
e51be066
GW
1674 entries = size / (MIN(size, SM_RUN_MAX));
1675 segsz = entries * sizeof (uint64_t);
1676
93cf2076
GW
1677 return (segsz <= space_map_length(msp->ms_sm) &&
1678 space_map_length(msp->ms_sm) >= (zfs_condense_pct *
1679 sizeof (uint64_t) * avl_numnodes(&msp->ms_tree->rt_root)) / 100);
e51be066
GW
1680}
1681
1682/*
1683 * Condense the on-disk space map representation to its minimized form.
1684 * The minimized form consists of a small number of allocations followed by
93cf2076 1685 * the entries of the free range tree.
e51be066
GW
1686 */
1687static void
1688metaslab_condense(metaslab_t *msp, uint64_t txg, dmu_tx_t *tx)
1689{
1690 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
93cf2076
GW
1691 range_tree_t *freetree = msp->ms_freetree[txg & TXG_MASK];
1692 range_tree_t *condense_tree;
1693 space_map_t *sm = msp->ms_sm;
e51be066
GW
1694 int t;
1695
1696 ASSERT(MUTEX_HELD(&msp->ms_lock));
1697 ASSERT3U(spa_sync_pass(spa), ==, 1);
93cf2076 1698 ASSERT(msp->ms_loaded);
e51be066 1699
f3a7f661 1700
e51be066 1701 spa_dbgmsg(spa, "condensing: txg %llu, msp[%llu] %p, "
f3a7f661
GW
1702 "smp size %llu, segments %lu, forcing condense=%s", txg,
1703 msp->ms_id, msp, space_map_length(msp->ms_sm),
1704 avl_numnodes(&msp->ms_tree->rt_root),
1705 msp->ms_condense_wanted ? "TRUE" : "FALSE");
1706
1707 msp->ms_condense_wanted = B_FALSE;
e51be066
GW
1708
1709 /*
93cf2076 1710 * Create an range tree that is 100% allocated. We remove segments
e51be066
GW
1711 * that have been freed in this txg, any deferred frees that exist,
1712 * and any allocation in the future. Removing segments should be
93cf2076
GW
1713 * a relatively inexpensive operation since we expect these trees to
1714 * have a small number of nodes.
e51be066 1715 */
93cf2076
GW
1716 condense_tree = range_tree_create(NULL, NULL, &msp->ms_lock);
1717 range_tree_add(condense_tree, msp->ms_start, msp->ms_size);
e51be066
GW
1718
1719 /*
93cf2076 1720 * Remove what's been freed in this txg from the condense_tree.
e51be066 1721 * Since we're in sync_pass 1, we know that all the frees from
93cf2076 1722 * this txg are in the freetree.
e51be066 1723 */
93cf2076 1724 range_tree_walk(freetree, range_tree_remove, condense_tree);
e51be066 1725
93cf2076
GW
1726 for (t = 0; t < TXG_DEFER_SIZE; t++) {
1727 range_tree_walk(msp->ms_defertree[t],
1728 range_tree_remove, condense_tree);
1729 }
e51be066 1730
93cf2076
GW
1731 for (t = 1; t < TXG_CONCURRENT_STATES; t++) {
1732 range_tree_walk(msp->ms_alloctree[(txg + t) & TXG_MASK],
1733 range_tree_remove, condense_tree);
1734 }
e51be066
GW
1735
1736 /*
1737 * We're about to drop the metaslab's lock thus allowing
1738 * other consumers to change it's content. Set the
93cf2076 1739 * metaslab's ms_condensing flag to ensure that
e51be066
GW
1740 * allocations on this metaslab do not occur while we're
1741 * in the middle of committing it to disk. This is only critical
93cf2076 1742 * for the ms_tree as all other range trees use per txg
e51be066
GW
1743 * views of their content.
1744 */
93cf2076 1745 msp->ms_condensing = B_TRUE;
e51be066
GW
1746
1747 mutex_exit(&msp->ms_lock);
93cf2076 1748 space_map_truncate(sm, tx);
e51be066
GW
1749 mutex_enter(&msp->ms_lock);
1750
1751 /*
1752 * While we would ideally like to create a space_map representation
1753 * that consists only of allocation records, doing so can be
93cf2076 1754 * prohibitively expensive because the in-core free tree can be
e51be066 1755 * large, and therefore computationally expensive to subtract
93cf2076
GW
1756 * from the condense_tree. Instead we sync out two trees, a cheap
1757 * allocation only tree followed by the in-core free tree. While not
e51be066
GW
1758 * optimal, this is typically close to optimal, and much cheaper to
1759 * compute.
1760 */
93cf2076
GW
1761 space_map_write(sm, condense_tree, SM_ALLOC, tx);
1762 range_tree_vacate(condense_tree, NULL, NULL);
1763 range_tree_destroy(condense_tree);
e51be066 1764
93cf2076
GW
1765 space_map_write(sm, msp->ms_tree, SM_FREE, tx);
1766 msp->ms_condensing = B_FALSE;
e51be066
GW
1767}
1768
34dc7c2f
BB
1769/*
1770 * Write a metaslab to disk in the context of the specified transaction group.
1771 */
1772void
1773metaslab_sync(metaslab_t *msp, uint64_t txg)
1774{
93cf2076
GW
1775 metaslab_group_t *mg = msp->ms_group;
1776 vdev_t *vd = mg->mg_vd;
34dc7c2f 1777 spa_t *spa = vd->vdev_spa;
428870ff 1778 objset_t *mos = spa_meta_objset(spa);
93cf2076
GW
1779 range_tree_t *alloctree = msp->ms_alloctree[txg & TXG_MASK];
1780 range_tree_t **freetree = &msp->ms_freetree[txg & TXG_MASK];
1781 range_tree_t **freed_tree =
1782 &msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK];
34dc7c2f 1783 dmu_tx_t *tx;
93cf2076 1784 uint64_t object = space_map_object(msp->ms_sm);
34dc7c2f 1785
428870ff
BB
1786 ASSERT(!vd->vdev_ishole);
1787
e51be066
GW
1788 /*
1789 * This metaslab has just been added so there's no work to do now.
1790 */
93cf2076
GW
1791 if (*freetree == NULL) {
1792 ASSERT3P(alloctree, ==, NULL);
e51be066
GW
1793 return;
1794 }
1795
93cf2076
GW
1796 ASSERT3P(alloctree, !=, NULL);
1797 ASSERT3P(*freetree, !=, NULL);
1798 ASSERT3P(*freed_tree, !=, NULL);
e51be066 1799
f3a7f661
GW
1800 /*
1801 * Normally, we don't want to process a metaslab if there
1802 * are no allocations or frees to perform. However, if the metaslab
1803 * is being forced to condense we need to let it through.
1804 */
93cf2076 1805 if (range_tree_space(alloctree) == 0 &&
f3a7f661
GW
1806 range_tree_space(*freetree) == 0 &&
1807 !msp->ms_condense_wanted)
428870ff 1808 return;
34dc7c2f
BB
1809
1810 /*
1811 * The only state that can actually be changing concurrently with
93cf2076
GW
1812 * metaslab_sync() is the metaslab's ms_tree. No other thread can
1813 * be modifying this txg's alloctree, freetree, freed_tree, or
1814 * space_map_phys_t. Therefore, we only hold ms_lock to satify
1815 * space_map ASSERTs. We drop it whenever we call into the DMU,
1816 * because the DMU can call down to us (e.g. via zio_free()) at
1817 * any time.
34dc7c2f 1818 */
428870ff
BB
1819
1820 tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
34dc7c2f 1821
93cf2076
GW
1822 if (msp->ms_sm == NULL) {
1823 uint64_t new_object;
1824
1825 new_object = space_map_alloc(mos, tx);
1826 VERIFY3U(new_object, !=, 0);
1827
1828 VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
1829 msp->ms_start, msp->ms_size, vd->vdev_ashift,
1830 &msp->ms_lock));
1831 ASSERT(msp->ms_sm != NULL);
34dc7c2f
BB
1832 }
1833
428870ff
BB
1834 mutex_enter(&msp->ms_lock);
1835
93cf2076 1836 if (msp->ms_loaded && spa_sync_pass(spa) == 1 &&
e51be066
GW
1837 metaslab_should_condense(msp)) {
1838 metaslab_condense(msp, txg, tx);
1839 } else {
93cf2076
GW
1840 space_map_write(msp->ms_sm, alloctree, SM_ALLOC, tx);
1841 space_map_write(msp->ms_sm, *freetree, SM_FREE, tx);
e51be066 1842 }
428870ff 1843
f3a7f661
GW
1844 metaslab_group_histogram_verify(mg);
1845 metaslab_class_histogram_verify(mg->mg_class);
1846 metaslab_group_histogram_remove(mg, msp);
93cf2076
GW
1847 if (msp->ms_loaded) {
1848 /*
1849 * When the space map is loaded, we have an accruate
1850 * histogram in the range tree. This gives us an opportunity
1851 * to bring the space map's histogram up-to-date so we clear
1852 * it first before updating it.
1853 */
1854 space_map_histogram_clear(msp->ms_sm);
1855 space_map_histogram_add(msp->ms_sm, msp->ms_tree, tx);
1856 } else {
1857 /*
1858 * Since the space map is not loaded we simply update the
1859 * exisiting histogram with what was freed in this txg. This
1860 * means that the on-disk histogram may not have an accurate
1861 * view of the free space but it's close enough to allow
1862 * us to make allocation decisions.
1863 */
1864 space_map_histogram_add(msp->ms_sm, *freetree, tx);
1865 }
f3a7f661
GW
1866 metaslab_group_histogram_add(mg, msp);
1867 metaslab_group_histogram_verify(mg);
1868 metaslab_class_histogram_verify(mg->mg_class);
34dc7c2f 1869
e51be066 1870 /*
93cf2076
GW
1871 * For sync pass 1, we avoid traversing this txg's free range tree
1872 * and instead will just swap the pointers for freetree and
1873 * freed_tree. We can safely do this since the freed_tree is
e51be066
GW
1874 * guaranteed to be empty on the initial pass.
1875 */
1876 if (spa_sync_pass(spa) == 1) {
93cf2076 1877 range_tree_swap(freetree, freed_tree);
e51be066 1878 } else {
93cf2076 1879 range_tree_vacate(*freetree, range_tree_add, *freed_tree);
34dc7c2f 1880 }
f3a7f661 1881 range_tree_vacate(alloctree, NULL, NULL);
34dc7c2f 1882
93cf2076
GW
1883 ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
1884 ASSERT0(range_tree_space(msp->ms_freetree[txg & TXG_MASK]));
34dc7c2f
BB
1885
1886 mutex_exit(&msp->ms_lock);
1887
93cf2076
GW
1888 if (object != space_map_object(msp->ms_sm)) {
1889 object = space_map_object(msp->ms_sm);
1890 dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
1891 msp->ms_id, sizeof (uint64_t), &object, tx);
1892 }
34dc7c2f
BB
1893 dmu_tx_commit(tx);
1894}
1895
1896/*
1897 * Called after a transaction group has completely synced to mark
1898 * all of the metaslab's free space as usable.
1899 */
1900void
1901metaslab_sync_done(metaslab_t *msp, uint64_t txg)
1902{
34dc7c2f
BB
1903 metaslab_group_t *mg = msp->ms_group;
1904 vdev_t *vd = mg->mg_vd;
93cf2076
GW
1905 range_tree_t **freed_tree;
1906 range_tree_t **defer_tree;
428870ff 1907 int64_t alloc_delta, defer_delta;
d6320ddb 1908 int t;
428870ff
BB
1909
1910 ASSERT(!vd->vdev_ishole);
34dc7c2f
BB
1911
1912 mutex_enter(&msp->ms_lock);
1913
1914 /*
1915 * If this metaslab is just becoming available, initialize its
93cf2076
GW
1916 * alloctrees, freetrees, and defertree and add its capacity to
1917 * the vdev.
34dc7c2f 1918 */
93cf2076 1919 if (msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK] == NULL) {
d6320ddb 1920 for (t = 0; t < TXG_SIZE; t++) {
93cf2076
GW
1921 ASSERT(msp->ms_alloctree[t] == NULL);
1922 ASSERT(msp->ms_freetree[t] == NULL);
1923
1924 msp->ms_alloctree[t] = range_tree_create(NULL, msp,
1925 &msp->ms_lock);
1926 msp->ms_freetree[t] = range_tree_create(NULL, msp,
1927 &msp->ms_lock);
34dc7c2f 1928 }
428870ff 1929
e51be066 1930 for (t = 0; t < TXG_DEFER_SIZE; t++) {
93cf2076 1931 ASSERT(msp->ms_defertree[t] == NULL);
e51be066 1932
93cf2076
GW
1933 msp->ms_defertree[t] = range_tree_create(NULL, msp,
1934 &msp->ms_lock);
1935 }
428870ff 1936
93cf2076 1937 vdev_space_update(vd, 0, 0, msp->ms_size);
34dc7c2f
BB
1938 }
1939
93cf2076
GW
1940 freed_tree = &msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK];
1941 defer_tree = &msp->ms_defertree[txg % TXG_DEFER_SIZE];
1942
1943 alloc_delta = space_map_alloc_delta(msp->ms_sm);
1944 defer_delta = range_tree_space(*freed_tree) -
1945 range_tree_space(*defer_tree);
428870ff
BB
1946
1947 vdev_space_update(vd, alloc_delta + defer_delta, defer_delta, 0);
34dc7c2f 1948
93cf2076
GW
1949 ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
1950 ASSERT0(range_tree_space(msp->ms_freetree[txg & TXG_MASK]));
34dc7c2f
BB
1951
1952 /*
93cf2076 1953 * If there's a metaslab_load() in progress, wait for it to complete
34dc7c2f 1954 * so that we have a consistent view of the in-core space map.
34dc7c2f 1955 */
93cf2076 1956 metaslab_load_wait(msp);
c2e42f9d
GW
1957
1958 /*
93cf2076
GW
1959 * Move the frees from the defer_tree back to the free
1960 * range tree (if it's loaded). Swap the freed_tree and the
1961 * defer_tree -- this is safe to do because we've just emptied out
1962 * the defer_tree.
c2e42f9d 1963 */
93cf2076
GW
1964 range_tree_vacate(*defer_tree,
1965 msp->ms_loaded ? range_tree_add : NULL, msp->ms_tree);
1966 range_tree_swap(freed_tree, defer_tree);
34dc7c2f 1967
93cf2076 1968 space_map_update(msp->ms_sm);
34dc7c2f 1969
428870ff
BB
1970 msp->ms_deferspace += defer_delta;
1971 ASSERT3S(msp->ms_deferspace, >=, 0);
93cf2076 1972 ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
428870ff
BB
1973 if (msp->ms_deferspace != 0) {
1974 /*
1975 * Keep syncing this metaslab until all deferred frees
1976 * are back in circulation.
1977 */
1978 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
1979 }
1980
93cf2076
GW
1981 if (msp->ms_loaded && msp->ms_access_txg < txg) {
1982 for (t = 1; t < TXG_CONCURRENT_STATES; t++) {
1983 VERIFY0(range_tree_space(
1984 msp->ms_alloctree[(txg + t) & TXG_MASK]));
1985 }
34dc7c2f 1986
93cf2076
GW
1987 if (!metaslab_debug_unload)
1988 metaslab_unload(msp);
34dc7c2f
BB
1989 }
1990
1991 metaslab_group_sort(mg, msp, metaslab_weight(msp));
34dc7c2f
BB
1992 mutex_exit(&msp->ms_lock);
1993}
1994
428870ff
BB
1995void
1996metaslab_sync_reassess(metaslab_group_t *mg)
1997{
1be627f5 1998 metaslab_group_alloc_update(mg);
f3a7f661 1999 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
6d974228 2000
428870ff 2001 /*
93cf2076 2002 * Preload the next potential metaslabs
428870ff 2003 */
93cf2076 2004 metaslab_group_preload(mg);
428870ff
BB
2005}
2006
34dc7c2f
BB
2007static uint64_t
2008metaslab_distance(metaslab_t *msp, dva_t *dva)
2009{
2010 uint64_t ms_shift = msp->ms_group->mg_vd->vdev_ms_shift;
2011 uint64_t offset = DVA_GET_OFFSET(dva) >> ms_shift;
93cf2076 2012 uint64_t start = msp->ms_id;
34dc7c2f
BB
2013
2014 if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
2015 return (1ULL << 63);
2016
2017 if (offset < start)
2018 return ((start - offset) << ms_shift);
2019 if (offset > start)
2020 return ((offset - start) << ms_shift);
2021 return (0);
2022}
2023
2024static uint64_t
6d974228 2025metaslab_group_alloc(metaslab_group_t *mg, uint64_t psize, uint64_t asize,
672692c7 2026 uint64_t txg, uint64_t min_distance, dva_t *dva, int d)
34dc7c2f 2027{
6d974228 2028 spa_t *spa = mg->mg_vd->vdev_spa;
34dc7c2f
BB
2029 metaslab_t *msp = NULL;
2030 uint64_t offset = -1ULL;
2031 avl_tree_t *t = &mg->mg_metaslab_tree;
2032 uint64_t activation_weight;
2033 uint64_t target_distance;
2034 int i;
2035
2036 activation_weight = METASLAB_WEIGHT_PRIMARY;
9babb374
BB
2037 for (i = 0; i < d; i++) {
2038 if (DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
34dc7c2f 2039 activation_weight = METASLAB_WEIGHT_SECONDARY;
9babb374
BB
2040 break;
2041 }
2042 }
34dc7c2f
BB
2043
2044 for (;;) {
9babb374
BB
2045 boolean_t was_active;
2046
34dc7c2f
BB
2047 mutex_enter(&mg->mg_lock);
2048 for (msp = avl_first(t); msp; msp = AVL_NEXT(t, msp)) {
6d974228
GW
2049 if (msp->ms_weight < asize) {
2050 spa_dbgmsg(spa, "%s: failed to meet weight "
2051 "requirement: vdev %llu, txg %llu, mg %p, "
2052 "msp %p, psize %llu, asize %llu, "
672692c7
GW
2053 "weight %llu", spa_name(spa),
2054 mg->mg_vd->vdev_id, txg,
2055 mg, msp, psize, asize, msp->ms_weight);
34dc7c2f
BB
2056 mutex_exit(&mg->mg_lock);
2057 return (-1ULL);
2058 }
7a614407
GW
2059
2060 /*
2061 * If the selected metaslab is condensing, skip it.
2062 */
93cf2076 2063 if (msp->ms_condensing)
7a614407
GW
2064 continue;
2065
9babb374 2066 was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
34dc7c2f
BB
2067 if (activation_weight == METASLAB_WEIGHT_PRIMARY)
2068 break;
2069
2070 target_distance = min_distance +
93cf2076
GW
2071 (space_map_allocated(msp->ms_sm) != 0 ? 0 :
2072 min_distance >> 1);
34dc7c2f
BB
2073
2074 for (i = 0; i < d; i++)
2075 if (metaslab_distance(msp, &dva[i]) <
2076 target_distance)
2077 break;
2078 if (i == d)
2079 break;
2080 }
2081 mutex_exit(&mg->mg_lock);
2082 if (msp == NULL)
2083 return (-1ULL);
2084
ac72fac3
GW
2085 mutex_enter(&msp->ms_lock);
2086
34dc7c2f
BB
2087 /*
2088 * Ensure that the metaslab we have selected is still
2089 * capable of handling our request. It's possible that
2090 * another thread may have changed the weight while we
2091 * were blocked on the metaslab lock.
2092 */
6d974228 2093 if (msp->ms_weight < asize || (was_active &&
9babb374
BB
2094 !(msp->ms_weight & METASLAB_ACTIVE_MASK) &&
2095 activation_weight == METASLAB_WEIGHT_PRIMARY)) {
34dc7c2f
BB
2096 mutex_exit(&msp->ms_lock);
2097 continue;
2098 }
2099
2100 if ((msp->ms_weight & METASLAB_WEIGHT_SECONDARY) &&
2101 activation_weight == METASLAB_WEIGHT_PRIMARY) {
2102 metaslab_passivate(msp,
2103 msp->ms_weight & ~METASLAB_ACTIVE_MASK);
2104 mutex_exit(&msp->ms_lock);
2105 continue;
2106 }
2107
6d974228 2108 if (metaslab_activate(msp, activation_weight) != 0) {
34dc7c2f
BB
2109 mutex_exit(&msp->ms_lock);
2110 continue;
2111 }
2112
7a614407
GW
2113 /*
2114 * If this metaslab is currently condensing then pick again as
2115 * we can't manipulate this metaslab until it's committed
2116 * to disk.
2117 */
93cf2076 2118 if (msp->ms_condensing) {
7a614407
GW
2119 mutex_exit(&msp->ms_lock);
2120 continue;
2121 }
2122
93cf2076 2123 if ((offset = metaslab_block_alloc(msp, asize)) != -1ULL)
34dc7c2f
BB
2124 break;
2125
93cf2076 2126 metaslab_passivate(msp, metaslab_block_maxsize(msp));
34dc7c2f
BB
2127 mutex_exit(&msp->ms_lock);
2128 }
2129
93cf2076 2130 if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
34dc7c2f
BB
2131 vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
2132
93cf2076
GW
2133 range_tree_add(msp->ms_alloctree[txg & TXG_MASK], offset, asize);
2134 msp->ms_access_txg = txg + metaslab_unload_delay;
34dc7c2f
BB
2135
2136 mutex_exit(&msp->ms_lock);
2137
2138 return (offset);
2139}
2140
2141/*
2142 * Allocate a block for the specified i/o.
2143 */
2144static int
2145metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
b128c09f 2146 dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags)
34dc7c2f 2147{
920dd524 2148 metaslab_group_t *mg, *fast_mg, *rotor;
34dc7c2f
BB
2149 vdev_t *vd;
2150 int dshift = 3;
2151 int all_zero;
fb5f0bc8
BB
2152 int zio_lock = B_FALSE;
2153 boolean_t allocatable;
34dc7c2f
BB
2154 uint64_t offset = -1ULL;
2155 uint64_t asize;
2156 uint64_t distance;
2157
2158 ASSERT(!DVA_IS_VALID(&dva[d]));
2159
2160 /*
2161 * For testing, make some blocks above a certain size be gang blocks.
2162 */
428870ff 2163 if (psize >= metaslab_gang_bang && (ddi_get_lbolt() & 3) == 0)
2e528b49 2164 return (SET_ERROR(ENOSPC));
34dc7c2f 2165
920dd524
ED
2166 if (flags & METASLAB_FASTWRITE)
2167 mutex_enter(&mc->mc_fastwrite_lock);
2168
34dc7c2f
BB
2169 /*
2170 * Start at the rotor and loop through all mgs until we find something.
428870ff 2171 * Note that there's no locking on mc_rotor or mc_aliquot because
34dc7c2f
BB
2172 * nothing actually breaks if we miss a few updates -- we just won't
2173 * allocate quite as evenly. It all balances out over time.
2174 *
2175 * If we are doing ditto or log blocks, try to spread them across
2176 * consecutive vdevs. If we're forced to reuse a vdev before we've
2177 * allocated all of our ditto blocks, then try and spread them out on
2178 * that vdev as much as possible. If it turns out to not be possible,
2179 * gradually lower our standards until anything becomes acceptable.
2180 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
2181 * gives us hope of containing our fault domains to something we're
2182 * able to reason about. Otherwise, any two top-level vdev failures
2183 * will guarantee the loss of data. With consecutive allocation,
2184 * only two adjacent top-level vdev failures will result in data loss.
2185 *
2186 * If we are doing gang blocks (hintdva is non-NULL), try to keep
2187 * ourselves on the same vdev as our gang block header. That
2188 * way, we can hope for locality in vdev_cache, plus it makes our
2189 * fault domains something tractable.
2190 */
2191 if (hintdva) {
2192 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
428870ff
BB
2193
2194 /*
2195 * It's possible the vdev we're using as the hint no
2196 * longer exists (i.e. removed). Consult the rotor when
2197 * all else fails.
2198 */
2199 if (vd != NULL) {
34dc7c2f 2200 mg = vd->vdev_mg;
428870ff
BB
2201
2202 if (flags & METASLAB_HINTBP_AVOID &&
2203 mg->mg_next != NULL)
2204 mg = mg->mg_next;
2205 } else {
2206 mg = mc->mc_rotor;
2207 }
34dc7c2f
BB
2208 } else if (d != 0) {
2209 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
2210 mg = vd->vdev_mg->mg_next;
920dd524
ED
2211 } else if (flags & METASLAB_FASTWRITE) {
2212 mg = fast_mg = mc->mc_rotor;
2213
2214 do {
2215 if (fast_mg->mg_vd->vdev_pending_fastwrite <
2216 mg->mg_vd->vdev_pending_fastwrite)
2217 mg = fast_mg;
2218 } while ((fast_mg = fast_mg->mg_next) != mc->mc_rotor);
2219
34dc7c2f
BB
2220 } else {
2221 mg = mc->mc_rotor;
2222 }
2223
2224 /*
428870ff
BB
2225 * If the hint put us into the wrong metaslab class, or into a
2226 * metaslab group that has been passivated, just follow the rotor.
34dc7c2f 2227 */
428870ff 2228 if (mg->mg_class != mc || mg->mg_activation_count <= 0)
34dc7c2f
BB
2229 mg = mc->mc_rotor;
2230
2231 rotor = mg;
2232top:
2233 all_zero = B_TRUE;
2234 do {
428870ff
BB
2235 ASSERT(mg->mg_activation_count == 1);
2236
34dc7c2f 2237 vd = mg->mg_vd;
fb5f0bc8 2238
34dc7c2f 2239 /*
b128c09f 2240 * Don't allocate from faulted devices.
34dc7c2f 2241 */
fb5f0bc8
BB
2242 if (zio_lock) {
2243 spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
2244 allocatable = vdev_allocatable(vd);
2245 spa_config_exit(spa, SCL_ZIO, FTAG);
2246 } else {
2247 allocatable = vdev_allocatable(vd);
2248 }
ac72fac3
GW
2249
2250 /*
2251 * Determine if the selected metaslab group is eligible
2252 * for allocations. If we're ganging or have requested
2253 * an allocation for the smallest gang block size
2254 * then we don't want to avoid allocating to the this
2255 * metaslab group. If we're in this condition we should
2256 * try to allocate from any device possible so that we
2257 * don't inadvertently return ENOSPC and suspend the pool
2258 * even though space is still available.
2259 */
2260 if (allocatable && CAN_FASTGANG(flags) &&
2261 psize > SPA_GANGBLOCKSIZE)
2262 allocatable = metaslab_group_allocatable(mg);
2263
fb5f0bc8 2264 if (!allocatable)
34dc7c2f 2265 goto next;
fb5f0bc8 2266
34dc7c2f
BB
2267 /*
2268 * Avoid writing single-copy data to a failing vdev
43a696ed 2269 * unless the user instructs us that it is okay.
34dc7c2f
BB
2270 */
2271 if ((vd->vdev_stat.vs_write_errors > 0 ||
2272 vd->vdev_state < VDEV_STATE_HEALTHY) &&
f3a7f661 2273 d == 0 && dshift == 3 && vd->vdev_children == 0) {
34dc7c2f
BB
2274 all_zero = B_FALSE;
2275 goto next;
2276 }
2277
2278 ASSERT(mg->mg_class == mc);
2279
2280 distance = vd->vdev_asize >> dshift;
2281 if (distance <= (1ULL << vd->vdev_ms_shift))
2282 distance = 0;
2283 else
2284 all_zero = B_FALSE;
2285
2286 asize = vdev_psize_to_asize(vd, psize);
2287 ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
2288
6d974228 2289 offset = metaslab_group_alloc(mg, psize, asize, txg, distance,
672692c7 2290 dva, d);
34dc7c2f
BB
2291 if (offset != -1ULL) {
2292 /*
2293 * If we've just selected this metaslab group,
2294 * figure out whether the corresponding vdev is
2295 * over- or under-used relative to the pool,
2296 * and set an allocation bias to even it out.
2297 */
f3a7f661 2298 if (mc->mc_aliquot == 0 && metaslab_bias_enabled) {
34dc7c2f 2299 vdev_stat_t *vs = &vd->vdev_stat;
428870ff 2300 int64_t vu, cu;
34dc7c2f 2301
6d974228
GW
2302 vu = (vs->vs_alloc * 100) / (vs->vs_space + 1);
2303 cu = (mc->mc_alloc * 100) / (mc->mc_space + 1);
34dc7c2f
BB
2304
2305 /*
6d974228
GW
2306 * Calculate how much more or less we should
2307 * try to allocate from this device during
2308 * this iteration around the rotor.
2309 * For example, if a device is 80% full
2310 * and the pool is 20% full then we should
2311 * reduce allocations by 60% on this device.
2312 *
2313 * mg_bias = (20 - 80) * 512K / 100 = -307K
2314 *
2315 * This reduces allocations by 307K for this
2316 * iteration.
34dc7c2f 2317 */
428870ff 2318 mg->mg_bias = ((cu - vu) *
6d974228 2319 (int64_t)mg->mg_aliquot) / 100;
f3a7f661
GW
2320 } else if (!metaslab_bias_enabled) {
2321 mg->mg_bias = 0;
34dc7c2f
BB
2322 }
2323
920dd524
ED
2324 if ((flags & METASLAB_FASTWRITE) ||
2325 atomic_add_64_nv(&mc->mc_aliquot, asize) >=
34dc7c2f
BB
2326 mg->mg_aliquot + mg->mg_bias) {
2327 mc->mc_rotor = mg->mg_next;
428870ff 2328 mc->mc_aliquot = 0;
34dc7c2f
BB
2329 }
2330
2331 DVA_SET_VDEV(&dva[d], vd->vdev_id);
2332 DVA_SET_OFFSET(&dva[d], offset);
b128c09f 2333 DVA_SET_GANG(&dva[d], !!(flags & METASLAB_GANG_HEADER));
34dc7c2f
BB
2334 DVA_SET_ASIZE(&dva[d], asize);
2335
920dd524
ED
2336 if (flags & METASLAB_FASTWRITE) {
2337 atomic_add_64(&vd->vdev_pending_fastwrite,
2338 psize);
2339 mutex_exit(&mc->mc_fastwrite_lock);
2340 }
2341
34dc7c2f
BB
2342 return (0);
2343 }
2344next:
2345 mc->mc_rotor = mg->mg_next;
428870ff 2346 mc->mc_aliquot = 0;
34dc7c2f
BB
2347 } while ((mg = mg->mg_next) != rotor);
2348
2349 if (!all_zero) {
2350 dshift++;
2351 ASSERT(dshift < 64);
2352 goto top;
2353 }
2354
9babb374 2355 if (!allocatable && !zio_lock) {
fb5f0bc8
BB
2356 dshift = 3;
2357 zio_lock = B_TRUE;
2358 goto top;
2359 }
2360
34dc7c2f
BB
2361 bzero(&dva[d], sizeof (dva_t));
2362
920dd524
ED
2363 if (flags & METASLAB_FASTWRITE)
2364 mutex_exit(&mc->mc_fastwrite_lock);
2e528b49
MA
2365
2366 return (SET_ERROR(ENOSPC));
34dc7c2f
BB
2367}
2368
2369/*
2370 * Free the block represented by DVA in the context of the specified
2371 * transaction group.
2372 */
2373static void
2374metaslab_free_dva(spa_t *spa, const dva_t *dva, uint64_t txg, boolean_t now)
2375{
2376 uint64_t vdev = DVA_GET_VDEV(dva);
2377 uint64_t offset = DVA_GET_OFFSET(dva);
2378 uint64_t size = DVA_GET_ASIZE(dva);
2379 vdev_t *vd;
2380 metaslab_t *msp;
2381
2382 ASSERT(DVA_IS_VALID(dva));
2383
2384 if (txg > spa_freeze_txg(spa))
2385 return;
2386
2387 if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
2388 (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
2389 cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
2390 (u_longlong_t)vdev, (u_longlong_t)offset);
2391 ASSERT(0);
2392 return;
2393 }
2394
2395 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
2396
2397 if (DVA_GET_GANG(dva))
2398 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
2399
2400 mutex_enter(&msp->ms_lock);
2401
2402 if (now) {
93cf2076 2403 range_tree_remove(msp->ms_alloctree[txg & TXG_MASK],
34dc7c2f 2404 offset, size);
93cf2076
GW
2405
2406 VERIFY(!msp->ms_condensing);
2407 VERIFY3U(offset, >=, msp->ms_start);
2408 VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
2409 VERIFY3U(range_tree_space(msp->ms_tree) + size, <=,
2410 msp->ms_size);
2411 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
2412 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
2413 range_tree_add(msp->ms_tree, offset, size);
34dc7c2f 2414 } else {
93cf2076 2415 if (range_tree_space(msp->ms_freetree[txg & TXG_MASK]) == 0)
34dc7c2f 2416 vdev_dirty(vd, VDD_METASLAB, msp, txg);
93cf2076
GW
2417 range_tree_add(msp->ms_freetree[txg & TXG_MASK],
2418 offset, size);
34dc7c2f
BB
2419 }
2420
2421 mutex_exit(&msp->ms_lock);
2422}
2423
2424/*
2425 * Intent log support: upon opening the pool after a crash, notify the SPA
2426 * of blocks that the intent log has allocated for immediate write, but
2427 * which are still considered free by the SPA because the last transaction
2428 * group didn't commit yet.
2429 */
2430static int
2431metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
2432{
2433 uint64_t vdev = DVA_GET_VDEV(dva);
2434 uint64_t offset = DVA_GET_OFFSET(dva);
2435 uint64_t size = DVA_GET_ASIZE(dva);
2436 vdev_t *vd;
2437 metaslab_t *msp;
428870ff 2438 int error = 0;
34dc7c2f
BB
2439
2440 ASSERT(DVA_IS_VALID(dva));
2441
2442 if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
2443 (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
2e528b49 2444 return (SET_ERROR(ENXIO));
34dc7c2f
BB
2445
2446 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
2447
2448 if (DVA_GET_GANG(dva))
2449 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
2450
2451 mutex_enter(&msp->ms_lock);
2452
93cf2076 2453 if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded)
6d974228 2454 error = metaslab_activate(msp, METASLAB_WEIGHT_SECONDARY);
428870ff 2455
93cf2076 2456 if (error == 0 && !range_tree_contains(msp->ms_tree, offset, size))
2e528b49 2457 error = SET_ERROR(ENOENT);
428870ff 2458
b128c09f 2459 if (error || txg == 0) { /* txg == 0 indicates dry run */
34dc7c2f
BB
2460 mutex_exit(&msp->ms_lock);
2461 return (error);
2462 }
2463
93cf2076
GW
2464 VERIFY(!msp->ms_condensing);
2465 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
2466 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
2467 VERIFY3U(range_tree_space(msp->ms_tree) - size, <=, msp->ms_size);
2468 range_tree_remove(msp->ms_tree, offset, size);
b128c09f 2469
fb5f0bc8 2470 if (spa_writeable(spa)) { /* don't dirty if we're zdb(1M) */
93cf2076 2471 if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
b128c09f 2472 vdev_dirty(vd, VDD_METASLAB, msp, txg);
93cf2076 2473 range_tree_add(msp->ms_alloctree[txg & TXG_MASK], offset, size);
b128c09f 2474 }
34dc7c2f
BB
2475
2476 mutex_exit(&msp->ms_lock);
2477
2478 return (0);
2479}
2480
2481int
2482metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
b128c09f 2483 int ndvas, uint64_t txg, blkptr_t *hintbp, int flags)
34dc7c2f
BB
2484{
2485 dva_t *dva = bp->blk_dva;
2486 dva_t *hintdva = hintbp->blk_dva;
d6320ddb 2487 int d, error = 0;
34dc7c2f 2488
b128c09f 2489 ASSERT(bp->blk_birth == 0);
428870ff 2490 ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
b128c09f
BB
2491
2492 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
2493
2494 if (mc->mc_rotor == NULL) { /* no vdevs in this class */
2495 spa_config_exit(spa, SCL_ALLOC, FTAG);
2e528b49 2496 return (SET_ERROR(ENOSPC));
b128c09f 2497 }
34dc7c2f
BB
2498
2499 ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
2500 ASSERT(BP_GET_NDVAS(bp) == 0);
2501 ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
2502
d6320ddb 2503 for (d = 0; d < ndvas; d++) {
34dc7c2f 2504 error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
b128c09f 2505 txg, flags);
93cf2076 2506 if (error != 0) {
34dc7c2f
BB
2507 for (d--; d >= 0; d--) {
2508 metaslab_free_dva(spa, &dva[d], txg, B_TRUE);
2509 bzero(&dva[d], sizeof (dva_t));
2510 }
b128c09f 2511 spa_config_exit(spa, SCL_ALLOC, FTAG);
34dc7c2f
BB
2512 return (error);
2513 }
2514 }
2515 ASSERT(error == 0);
2516 ASSERT(BP_GET_NDVAS(bp) == ndvas);
2517
b128c09f
BB
2518 spa_config_exit(spa, SCL_ALLOC, FTAG);
2519
428870ff 2520 BP_SET_BIRTH(bp, txg, txg);
b128c09f 2521
34dc7c2f
BB
2522 return (0);
2523}
2524
2525void
2526metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
2527{
2528 const dva_t *dva = bp->blk_dva;
d6320ddb 2529 int d, ndvas = BP_GET_NDVAS(bp);
34dc7c2f
BB
2530
2531 ASSERT(!BP_IS_HOLE(bp));
428870ff 2532 ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
b128c09f
BB
2533
2534 spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
34dc7c2f 2535
d6320ddb 2536 for (d = 0; d < ndvas; d++)
34dc7c2f 2537 metaslab_free_dva(spa, &dva[d], txg, now);
b128c09f
BB
2538
2539 spa_config_exit(spa, SCL_FREE, FTAG);
34dc7c2f
BB
2540}
2541
2542int
2543metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
2544{
2545 const dva_t *dva = bp->blk_dva;
2546 int ndvas = BP_GET_NDVAS(bp);
d6320ddb 2547 int d, error = 0;
34dc7c2f
BB
2548
2549 ASSERT(!BP_IS_HOLE(bp));
2550
b128c09f
BB
2551 if (txg != 0) {
2552 /*
2553 * First do a dry run to make sure all DVAs are claimable,
2554 * so we don't have to unwind from partial failures below.
2555 */
2556 if ((error = metaslab_claim(spa, bp, 0)) != 0)
2557 return (error);
2558 }
2559
2560 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
2561
d6320ddb 2562 for (d = 0; d < ndvas; d++)
34dc7c2f 2563 if ((error = metaslab_claim_dva(spa, &dva[d], txg)) != 0)
b128c09f
BB
2564 break;
2565
2566 spa_config_exit(spa, SCL_ALLOC, FTAG);
2567
2568 ASSERT(error == 0 || txg == 0);
34dc7c2f 2569
b128c09f 2570 return (error);
34dc7c2f 2571}
920dd524 2572
d1d7e268
MK
2573void
2574metaslab_fastwrite_mark(spa_t *spa, const blkptr_t *bp)
920dd524
ED
2575{
2576 const dva_t *dva = bp->blk_dva;
2577 int ndvas = BP_GET_NDVAS(bp);
2578 uint64_t psize = BP_GET_PSIZE(bp);
2579 int d;
2580 vdev_t *vd;
2581
2582 ASSERT(!BP_IS_HOLE(bp));
9b67f605 2583 ASSERT(!BP_IS_EMBEDDED(bp));
920dd524
ED
2584 ASSERT(psize > 0);
2585
2586 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2587
2588 for (d = 0; d < ndvas; d++) {
2589 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
2590 continue;
2591 atomic_add_64(&vd->vdev_pending_fastwrite, psize);
2592 }
2593
2594 spa_config_exit(spa, SCL_VDEV, FTAG);
2595}
2596
d1d7e268
MK
2597void
2598metaslab_fastwrite_unmark(spa_t *spa, const blkptr_t *bp)
920dd524
ED
2599{
2600 const dva_t *dva = bp->blk_dva;
2601 int ndvas = BP_GET_NDVAS(bp);
2602 uint64_t psize = BP_GET_PSIZE(bp);
2603 int d;
2604 vdev_t *vd;
2605
2606 ASSERT(!BP_IS_HOLE(bp));
9b67f605 2607 ASSERT(!BP_IS_EMBEDDED(bp));
920dd524
ED
2608 ASSERT(psize > 0);
2609
2610 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2611
2612 for (d = 0; d < ndvas; d++) {
2613 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
2614 continue;
2615 ASSERT3U(vd->vdev_pending_fastwrite, >=, psize);
2616 atomic_sub_64(&vd->vdev_pending_fastwrite, psize);
2617 }
2618
2619 spa_config_exit(spa, SCL_VDEV, FTAG);
2620}
30b92c1d 2621
13fe0198
MA
2622void
2623metaslab_check_free(spa_t *spa, const blkptr_t *bp)
2624{
2625 int i, j;
2626
2627 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
2628 return;
2629
2630 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2631 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
93cf2076
GW
2632 uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
2633 vdev_t *vd = vdev_lookup_top(spa, vdev);
2634 uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
13fe0198 2635 uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
93cf2076 2636 metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
13fe0198 2637
93cf2076
GW
2638 if (msp->ms_loaded)
2639 range_tree_verify(msp->ms_tree, offset, size);
13fe0198
MA
2640
2641 for (j = 0; j < TXG_SIZE; j++)
93cf2076 2642 range_tree_verify(msp->ms_freetree[j], offset, size);
13fe0198 2643 for (j = 0; j < TXG_DEFER_SIZE; j++)
93cf2076 2644 range_tree_verify(msp->ms_defertree[j], offset, size);
13fe0198
MA
2645 }
2646 spa_config_exit(spa, SCL_VDEV, FTAG);
2647}
2648
30b92c1d 2649#if defined(_KERNEL) && defined(HAVE_SPL)
aa7d06a9 2650module_param(metaslab_debug_load, int, 0644);
aa7d06a9 2651module_param(metaslab_debug_unload, int, 0644);
f3a7f661
GW
2652module_param(metaslab_preload_enabled, int, 0644);
2653module_param(zfs_mg_noalloc_threshold, int, 0644);
2654module_param(zfs_mg_fragmentation_threshold, int, 0644);
2655module_param(zfs_metaslab_fragmentation_threshold, int, 0644);
2656module_param(metaslab_fragmentation_factor_enabled, int, 0644);
2657module_param(metaslab_lba_weighting_enabled, int, 0644);
2658module_param(metaslab_bias_enabled, int, 0644);
2659
93cf2076
GW
2660MODULE_PARM_DESC(metaslab_debug_load,
2661 "load all metaslabs when pool is first opened");
1ce04573
BB
2662MODULE_PARM_DESC(metaslab_debug_unload,
2663 "prevent metaslabs from being unloaded");
f3a7f661
GW
2664MODULE_PARM_DESC(metaslab_preload_enabled,
2665 "preload potential metaslabs during reassessment");
f4a4046b 2666
f4a4046b
TC
2667MODULE_PARM_DESC(zfs_mg_noalloc_threshold,
2668 "percentage of free space for metaslab group to allow allocation");
f3a7f661
GW
2669MODULE_PARM_DESC(zfs_mg_fragmentation_threshold,
2670 "fragmentation for metaslab group to allow allocation");
2671
2672MODULE_PARM_DESC(zfs_metaslab_fragmentation_threshold,
2673 "fragmentation for metaslab to allow allocation");
2674MODULE_PARM_DESC(metaslab_fragmentation_factor_enabled,
2675 "use the fragmentation metric to prefer less fragmented metaslabs");
2676MODULE_PARM_DESC(metaslab_lba_weighting_enabled,
2677 "prefer metaslabs with lower LBAs");
2678MODULE_PARM_DESC(metaslab_bias_enabled,
2679 "enable metaslab group biasing");
30b92c1d 2680#endif /* _KERNEL && HAVE_SPL */