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