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