]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/metaslab.c
Illumos #3561, #3116
[mirror_zfs.git] / module / zfs / metaslab.c
CommitLineData
34dc7c2f
BB
1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
428870ff 22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
ebf8e3a2 23 * Copyright (c) 2012 by Delphix. All rights reserved.
34dc7c2f
BB
24 */
25
34dc7c2f 26#include <sys/zfs_context.h>
34dc7c2f
BB
27#include <sys/dmu.h>
28#include <sys/dmu_tx.h>
29#include <sys/space_map.h>
30#include <sys/metaslab_impl.h>
31#include <sys/vdev_impl.h>
32#include <sys/zio.h>
33
6d974228
GW
34#define WITH_DF_BLOCK_ALLOCATOR
35
36/*
37 * Allow allocations to switch to gang blocks quickly. We do this to
38 * avoid having to load lots of space_maps in a given txg. There are,
39 * however, some cases where we want to avoid "fast" ganging and instead
40 * we want to do an exhaustive search of all metaslabs on this device.
ebf8e3a2 41 * Currently we don't allow any gang, zil, or dump device related allocations
6d974228
GW
42 * to "fast" gang.
43 */
44#define CAN_FASTGANG(flags) \
45 (!((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER | \
46 METASLAB_GANG_AVOID)))
22c81dd8 47
34dc7c2f
BB
48uint64_t metaslab_aliquot = 512ULL << 10;
49uint64_t metaslab_gang_bang = SPA_MAXBLOCKSIZE + 1; /* force gang blocks */
50
e51be066
GW
51/*
52 * The in-core space map representation is more compact than its on-disk form.
53 * The zfs_condense_pct determines how much more compact the in-core
54 * space_map representation must be before we compact it on-disk.
55 * Values should be greater than or equal to 100.
56 */
57int zfs_condense_pct = 200;
58
6d974228
GW
59/*
60 * This value defines the number of allowed allocation failures per vdev.
61 * If a device reaches this threshold in a given txg then we consider skipping
62 * allocations on that device.
63 */
64int zfs_mg_alloc_failures;
65
428870ff
BB
66/*
67 * Metaslab debugging: when set, keeps all space maps in core to verify frees.
68 */
30b92c1d 69int metaslab_debug = 0;
428870ff 70
9babb374
BB
71/*
72 * Minimum size which forces the dynamic allocator to change
428870ff 73 * it's allocation strategy. Once the space map cannot satisfy
9babb374
BB
74 * an allocation of this size then it switches to using more
75 * aggressive strategy (i.e search by size rather than offset).
76 */
77uint64_t metaslab_df_alloc_threshold = SPA_MAXBLOCKSIZE;
78
79/*
80 * The minimum free space, in percent, which must be available
81 * in a space map to continue allocations in a first-fit fashion.
82 * Once the space_map's free space drops below this level we dynamically
83 * switch to using best-fit allocations.
84 */
428870ff
BB
85int metaslab_df_free_pct = 4;
86
87/*
88 * A metaslab is considered "free" if it contains a contiguous
89 * segment which is greater than metaslab_min_alloc_size.
90 */
91uint64_t metaslab_min_alloc_size = DMU_MAX_ACCESS;
92
93/*
94 * Max number of space_maps to prefetch.
95 */
96int metaslab_prefetch_limit = SPA_DVAS_PER_BP;
97
98/*
99 * Percentage bonus multiplier for metaslabs that are in the bonus area.
100 */
101int metaslab_smo_bonus_pct = 150;
9babb374 102
34dc7c2f
BB
103/*
104 * ==========================================================================
105 * Metaslab classes
106 * ==========================================================================
107 */
108metaslab_class_t *
428870ff 109metaslab_class_create(spa_t *spa, space_map_ops_t *ops)
34dc7c2f
BB
110{
111 metaslab_class_t *mc;
112
b8d06fca 113 mc = kmem_zalloc(sizeof (metaslab_class_t), KM_PUSHPAGE);
34dc7c2f 114
428870ff 115 mc->mc_spa = spa;
34dc7c2f 116 mc->mc_rotor = NULL;
9babb374 117 mc->mc_ops = ops;
920dd524 118 mutex_init(&mc->mc_fastwrite_lock, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
119
120 return (mc);
121}
122
123void
124metaslab_class_destroy(metaslab_class_t *mc)
125{
428870ff
BB
126 ASSERT(mc->mc_rotor == NULL);
127 ASSERT(mc->mc_alloc == 0);
128 ASSERT(mc->mc_deferred == 0);
129 ASSERT(mc->mc_space == 0);
130 ASSERT(mc->mc_dspace == 0);
34dc7c2f 131
920dd524 132 mutex_destroy(&mc->mc_fastwrite_lock);
34dc7c2f
BB
133 kmem_free(mc, sizeof (metaslab_class_t));
134}
135
428870ff
BB
136int
137metaslab_class_validate(metaslab_class_t *mc)
34dc7c2f 138{
428870ff
BB
139 metaslab_group_t *mg;
140 vdev_t *vd;
34dc7c2f 141
428870ff
BB
142 /*
143 * Must hold one of the spa_config locks.
144 */
145 ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
146 spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
34dc7c2f 147
428870ff
BB
148 if ((mg = mc->mc_rotor) == NULL)
149 return (0);
150
151 do {
152 vd = mg->mg_vd;
153 ASSERT(vd->vdev_mg != NULL);
154 ASSERT3P(vd->vdev_top, ==, vd);
155 ASSERT3P(mg->mg_class, ==, mc);
156 ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
157 } while ((mg = mg->mg_next) != mc->mc_rotor);
158
159 return (0);
34dc7c2f
BB
160}
161
162void
428870ff
BB
163metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
164 int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
34dc7c2f 165{
428870ff
BB
166 atomic_add_64(&mc->mc_alloc, alloc_delta);
167 atomic_add_64(&mc->mc_deferred, defer_delta);
168 atomic_add_64(&mc->mc_space, space_delta);
169 atomic_add_64(&mc->mc_dspace, dspace_delta);
170}
34dc7c2f 171
428870ff
BB
172uint64_t
173metaslab_class_get_alloc(metaslab_class_t *mc)
174{
175 return (mc->mc_alloc);
176}
34dc7c2f 177
428870ff
BB
178uint64_t
179metaslab_class_get_deferred(metaslab_class_t *mc)
180{
181 return (mc->mc_deferred);
182}
34dc7c2f 183
428870ff
BB
184uint64_t
185metaslab_class_get_space(metaslab_class_t *mc)
186{
187 return (mc->mc_space);
188}
34dc7c2f 189
428870ff
BB
190uint64_t
191metaslab_class_get_dspace(metaslab_class_t *mc)
192{
193 return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
34dc7c2f
BB
194}
195
196/*
197 * ==========================================================================
198 * Metaslab groups
199 * ==========================================================================
200 */
201static int
202metaslab_compare(const void *x1, const void *x2)
203{
204 const metaslab_t *m1 = x1;
205 const metaslab_t *m2 = x2;
206
207 if (m1->ms_weight < m2->ms_weight)
208 return (1);
209 if (m1->ms_weight > m2->ms_weight)
210 return (-1);
211
212 /*
213 * If the weights are identical, use the offset to force uniqueness.
214 */
e51be066 215 if (m1->ms_map->sm_start < m2->ms_map->sm_start)
34dc7c2f 216 return (-1);
e51be066 217 if (m1->ms_map->sm_start > m2->ms_map->sm_start)
34dc7c2f
BB
218 return (1);
219
220 ASSERT3P(m1, ==, m2);
221
222 return (0);
223}
224
225metaslab_group_t *
226metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
227{
228 metaslab_group_t *mg;
229
b8d06fca 230 mg = kmem_zalloc(sizeof (metaslab_group_t), KM_PUSHPAGE);
34dc7c2f
BB
231 mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
232 avl_create(&mg->mg_metaslab_tree, metaslab_compare,
233 sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
34dc7c2f 234 mg->mg_vd = vd;
428870ff
BB
235 mg->mg_class = mc;
236 mg->mg_activation_count = 0;
34dc7c2f
BB
237
238 return (mg);
239}
240
241void
242metaslab_group_destroy(metaslab_group_t *mg)
243{
428870ff
BB
244 ASSERT(mg->mg_prev == NULL);
245 ASSERT(mg->mg_next == NULL);
246 /*
247 * We may have gone below zero with the activation count
248 * either because we never activated in the first place or
249 * because we're done, and possibly removing the vdev.
250 */
251 ASSERT(mg->mg_activation_count <= 0);
252
34dc7c2f
BB
253 avl_destroy(&mg->mg_metaslab_tree);
254 mutex_destroy(&mg->mg_lock);
255 kmem_free(mg, sizeof (metaslab_group_t));
256}
257
428870ff
BB
258void
259metaslab_group_activate(metaslab_group_t *mg)
260{
261 metaslab_class_t *mc = mg->mg_class;
262 metaslab_group_t *mgprev, *mgnext;
263
264 ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
265
266 ASSERT(mc->mc_rotor != mg);
267 ASSERT(mg->mg_prev == NULL);
268 ASSERT(mg->mg_next == NULL);
269 ASSERT(mg->mg_activation_count <= 0);
270
271 if (++mg->mg_activation_count <= 0)
272 return;
273
274 mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
275
276 if ((mgprev = mc->mc_rotor) == NULL) {
277 mg->mg_prev = mg;
278 mg->mg_next = mg;
279 } else {
280 mgnext = mgprev->mg_next;
281 mg->mg_prev = mgprev;
282 mg->mg_next = mgnext;
283 mgprev->mg_next = mg;
284 mgnext->mg_prev = mg;
285 }
286 mc->mc_rotor = mg;
287}
288
289void
290metaslab_group_passivate(metaslab_group_t *mg)
291{
292 metaslab_class_t *mc = mg->mg_class;
293 metaslab_group_t *mgprev, *mgnext;
294
295 ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
296
297 if (--mg->mg_activation_count != 0) {
298 ASSERT(mc->mc_rotor != mg);
299 ASSERT(mg->mg_prev == NULL);
300 ASSERT(mg->mg_next == NULL);
301 ASSERT(mg->mg_activation_count < 0);
302 return;
303 }
304
305 mgprev = mg->mg_prev;
306 mgnext = mg->mg_next;
307
308 if (mg == mgnext) {
309 mc->mc_rotor = NULL;
310 } else {
311 mc->mc_rotor = mgnext;
312 mgprev->mg_next = mgnext;
313 mgnext->mg_prev = mgprev;
314 }
315
316 mg->mg_prev = NULL;
317 mg->mg_next = NULL;
318}
319
34dc7c2f
BB
320static void
321metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
322{
323 mutex_enter(&mg->mg_lock);
324 ASSERT(msp->ms_group == NULL);
325 msp->ms_group = mg;
326 msp->ms_weight = 0;
327 avl_add(&mg->mg_metaslab_tree, msp);
328 mutex_exit(&mg->mg_lock);
329}
330
331static void
332metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
333{
334 mutex_enter(&mg->mg_lock);
335 ASSERT(msp->ms_group == mg);
336 avl_remove(&mg->mg_metaslab_tree, msp);
337 msp->ms_group = NULL;
338 mutex_exit(&mg->mg_lock);
339}
340
341static void
342metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
343{
344 /*
345 * Although in principle the weight can be any value, in
346 * practice we do not use values in the range [1, 510].
347 */
348 ASSERT(weight >= SPA_MINBLOCKSIZE-1 || weight == 0);
349 ASSERT(MUTEX_HELD(&msp->ms_lock));
350
351 mutex_enter(&mg->mg_lock);
352 ASSERT(msp->ms_group == mg);
353 avl_remove(&mg->mg_metaslab_tree, msp);
354 msp->ms_weight = weight;
355 avl_add(&mg->mg_metaslab_tree, msp);
356 mutex_exit(&mg->mg_lock);
357}
358
428870ff
BB
359/*
360 * ==========================================================================
361 * Common allocator routines
362 * ==========================================================================
363 */
364static int
365metaslab_segsize_compare(const void *x1, const void *x2)
366{
367 const space_seg_t *s1 = x1;
368 const space_seg_t *s2 = x2;
369 uint64_t ss_size1 = s1->ss_end - s1->ss_start;
370 uint64_t ss_size2 = s2->ss_end - s2->ss_start;
371
372 if (ss_size1 < ss_size2)
373 return (-1);
374 if (ss_size1 > ss_size2)
375 return (1);
376
377 if (s1->ss_start < s2->ss_start)
378 return (-1);
379 if (s1->ss_start > s2->ss_start)
380 return (1);
381
382 return (0);
383}
384
22c81dd8
BB
385#if defined(WITH_FF_BLOCK_ALLOCATOR) || \
386 defined(WITH_DF_BLOCK_ALLOCATOR) || \
387 defined(WITH_CDF_BLOCK_ALLOCATOR)
34dc7c2f 388/*
9babb374
BB
389 * This is a helper function that can be used by the allocator to find
390 * a suitable block to allocate. This will search the specified AVL
391 * tree looking for a block that matches the specified criteria.
34dc7c2f 392 */
34dc7c2f 393static uint64_t
9babb374
BB
394metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
395 uint64_t align)
34dc7c2f 396{
34dc7c2f
BB
397 space_seg_t *ss, ssearch;
398 avl_index_t where;
399
400 ssearch.ss_start = *cursor;
401 ssearch.ss_end = *cursor + size;
402
403 ss = avl_find(t, &ssearch, &where);
404 if (ss == NULL)
405 ss = avl_nearest(t, where, AVL_AFTER);
406
407 while (ss != NULL) {
408 uint64_t offset = P2ROUNDUP(ss->ss_start, align);
409
410 if (offset + size <= ss->ss_end) {
411 *cursor = offset + size;
412 return (offset);
413 }
414 ss = AVL_NEXT(t, ss);
415 }
416
417 /*
418 * If we know we've searched the whole map (*cursor == 0), give up.
419 * Otherwise, reset the cursor to the beginning and try again.
420 */
421 if (*cursor == 0)
422 return (-1ULL);
423
424 *cursor = 0;
9babb374
BB
425 return (metaslab_block_picker(t, cursor, size, align));
426}
22c81dd8 427#endif /* WITH_FF/DF/CDF_BLOCK_ALLOCATOR */
9babb374 428
9babb374 429static void
428870ff 430metaslab_pp_load(space_map_t *sm)
9babb374 431{
428870ff
BB
432 space_seg_t *ss;
433
9babb374 434 ASSERT(sm->sm_ppd == NULL);
b8d06fca 435 sm->sm_ppd = kmem_zalloc(64 * sizeof (uint64_t), KM_PUSHPAGE);
428870ff 436
b8d06fca 437 sm->sm_pp_root = kmem_alloc(sizeof (avl_tree_t), KM_PUSHPAGE);
428870ff
BB
438 avl_create(sm->sm_pp_root, metaslab_segsize_compare,
439 sizeof (space_seg_t), offsetof(struct space_seg, ss_pp_node));
440
441 for (ss = avl_first(&sm->sm_root); ss; ss = AVL_NEXT(&sm->sm_root, ss))
442 avl_add(sm->sm_pp_root, ss);
9babb374
BB
443}
444
445static void
428870ff 446metaslab_pp_unload(space_map_t *sm)
9babb374 447{
428870ff
BB
448 void *cookie = NULL;
449
9babb374
BB
450 kmem_free(sm->sm_ppd, 64 * sizeof (uint64_t));
451 sm->sm_ppd = NULL;
9babb374 452
428870ff
BB
453 while (avl_destroy_nodes(sm->sm_pp_root, &cookie) != NULL) {
454 /* tear down the tree */
455 }
9babb374 456
428870ff
BB
457 avl_destroy(sm->sm_pp_root);
458 kmem_free(sm->sm_pp_root, sizeof (avl_tree_t));
459 sm->sm_pp_root = NULL;
34dc7c2f
BB
460}
461
462/* ARGSUSED */
463static void
428870ff 464metaslab_pp_claim(space_map_t *sm, uint64_t start, uint64_t size)
34dc7c2f
BB
465{
466 /* No need to update cursor */
467}
468
469/* ARGSUSED */
470static void
428870ff 471metaslab_pp_free(space_map_t *sm, uint64_t start, uint64_t size)
34dc7c2f
BB
472{
473 /* No need to update cursor */
474}
475
9babb374 476/*
428870ff 477 * Return the maximum contiguous segment within the metaslab.
9babb374 478 */
9babb374 479uint64_t
428870ff 480metaslab_pp_maxsize(space_map_t *sm)
9babb374
BB
481{
482 avl_tree_t *t = sm->sm_pp_root;
483 space_seg_t *ss;
484
485 if (t == NULL || (ss = avl_last(t)) == NULL)
486 return (0ULL);
487
488 return (ss->ss_end - ss->ss_start);
489}
490
22c81dd8 491#if defined(WITH_FF_BLOCK_ALLOCATOR)
428870ff
BB
492/*
493 * ==========================================================================
494 * The first-fit block allocator
495 * ==========================================================================
496 */
497static uint64_t
498metaslab_ff_alloc(space_map_t *sm, uint64_t size)
9babb374 499{
428870ff
BB
500 avl_tree_t *t = &sm->sm_root;
501 uint64_t align = size & -size;
502 uint64_t *cursor = (uint64_t *)sm->sm_ppd + highbit(align) - 1;
9babb374 503
428870ff 504 return (metaslab_block_picker(t, cursor, size, align));
9babb374
BB
505}
506
428870ff
BB
507/* ARGSUSED */
508boolean_t
509metaslab_ff_fragmented(space_map_t *sm)
9babb374 510{
428870ff 511 return (B_TRUE);
9babb374
BB
512}
513
428870ff
BB
514static space_map_ops_t metaslab_ff_ops = {
515 metaslab_pp_load,
516 metaslab_pp_unload,
517 metaslab_ff_alloc,
518 metaslab_pp_claim,
519 metaslab_pp_free,
520 metaslab_pp_maxsize,
521 metaslab_ff_fragmented
522};
9babb374 523
22c81dd8
BB
524space_map_ops_t *zfs_metaslab_ops = &metaslab_ff_ops;
525#endif /* WITH_FF_BLOCK_ALLOCATOR */
526
527#if defined(WITH_DF_BLOCK_ALLOCATOR)
428870ff
BB
528/*
529 * ==========================================================================
530 * Dynamic block allocator -
531 * Uses the first fit allocation scheme until space get low and then
532 * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
533 * and metaslab_df_free_pct to determine when to switch the allocation scheme.
534 * ==========================================================================
535 */
9babb374
BB
536static uint64_t
537metaslab_df_alloc(space_map_t *sm, uint64_t size)
538{
539 avl_tree_t *t = &sm->sm_root;
540 uint64_t align = size & -size;
541 uint64_t *cursor = (uint64_t *)sm->sm_ppd + highbit(align) - 1;
428870ff 542 uint64_t max_size = metaslab_pp_maxsize(sm);
9babb374
BB
543 int free_pct = sm->sm_space * 100 / sm->sm_size;
544
545 ASSERT(MUTEX_HELD(sm->sm_lock));
546 ASSERT3U(avl_numnodes(&sm->sm_root), ==, avl_numnodes(sm->sm_pp_root));
547
548 if (max_size < size)
549 return (-1ULL);
550
551 /*
552 * If we're running low on space switch to using the size
553 * sorted AVL tree (best-fit).
554 */
555 if (max_size < metaslab_df_alloc_threshold ||
556 free_pct < metaslab_df_free_pct) {
557 t = sm->sm_pp_root;
558 *cursor = 0;
559 }
560
561 return (metaslab_block_picker(t, cursor, size, 1ULL));
562}
563
428870ff
BB
564static boolean_t
565metaslab_df_fragmented(space_map_t *sm)
9babb374 566{
428870ff
BB
567 uint64_t max_size = metaslab_pp_maxsize(sm);
568 int free_pct = sm->sm_space * 100 / sm->sm_size;
9babb374 569
428870ff
BB
570 if (max_size >= metaslab_df_alloc_threshold &&
571 free_pct >= metaslab_df_free_pct)
572 return (B_FALSE);
573
574 return (B_TRUE);
9babb374
BB
575}
576
577static space_map_ops_t metaslab_df_ops = {
428870ff
BB
578 metaslab_pp_load,
579 metaslab_pp_unload,
9babb374 580 metaslab_df_alloc,
428870ff
BB
581 metaslab_pp_claim,
582 metaslab_pp_free,
583 metaslab_pp_maxsize,
584 metaslab_df_fragmented
34dc7c2f
BB
585};
586
22c81dd8
BB
587space_map_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
588#endif /* WITH_DF_BLOCK_ALLOCATOR */
589
428870ff
BB
590/*
591 * ==========================================================================
592 * Other experimental allocators
593 * ==========================================================================
594 */
22c81dd8 595#if defined(WITH_CDF_BLOCK_ALLOCATOR)
428870ff
BB
596static uint64_t
597metaslab_cdf_alloc(space_map_t *sm, uint64_t size)
598{
599 avl_tree_t *t = &sm->sm_root;
600 uint64_t *cursor = (uint64_t *)sm->sm_ppd;
601 uint64_t *extent_end = (uint64_t *)sm->sm_ppd + 1;
602 uint64_t max_size = metaslab_pp_maxsize(sm);
603 uint64_t rsize = size;
604 uint64_t offset = 0;
605
606 ASSERT(MUTEX_HELD(sm->sm_lock));
607 ASSERT3U(avl_numnodes(&sm->sm_root), ==, avl_numnodes(sm->sm_pp_root));
608
609 if (max_size < size)
610 return (-1ULL);
611
612 ASSERT3U(*extent_end, >=, *cursor);
613
614 /*
615 * If we're running low on space switch to using the size
616 * sorted AVL tree (best-fit).
617 */
618 if ((*cursor + size) > *extent_end) {
619
620 t = sm->sm_pp_root;
621 *cursor = *extent_end = 0;
622
623 if (max_size > 2 * SPA_MAXBLOCKSIZE)
624 rsize = MIN(metaslab_min_alloc_size, max_size);
625 offset = metaslab_block_picker(t, extent_end, rsize, 1ULL);
626 if (offset != -1)
627 *cursor = offset + size;
628 } else {
629 offset = metaslab_block_picker(t, cursor, rsize, 1ULL);
630 }
631 ASSERT3U(*cursor, <=, *extent_end);
632 return (offset);
633}
634
635static boolean_t
636metaslab_cdf_fragmented(space_map_t *sm)
637{
638 uint64_t max_size = metaslab_pp_maxsize(sm);
639
640 if (max_size > (metaslab_min_alloc_size * 10))
641 return (B_FALSE);
642 return (B_TRUE);
643}
644
645static space_map_ops_t metaslab_cdf_ops = {
646 metaslab_pp_load,
647 metaslab_pp_unload,
648 metaslab_cdf_alloc,
649 metaslab_pp_claim,
650 metaslab_pp_free,
651 metaslab_pp_maxsize,
652 metaslab_cdf_fragmented
653};
654
22c81dd8
BB
655space_map_ops_t *zfs_metaslab_ops = &metaslab_cdf_ops;
656#endif /* WITH_CDF_BLOCK_ALLOCATOR */
657
658#if defined(WITH_NDF_BLOCK_ALLOCATOR)
428870ff
BB
659uint64_t metaslab_ndf_clump_shift = 4;
660
661static uint64_t
662metaslab_ndf_alloc(space_map_t *sm, uint64_t size)
663{
664 avl_tree_t *t = &sm->sm_root;
665 avl_index_t where;
666 space_seg_t *ss, ssearch;
667 uint64_t hbit = highbit(size);
668 uint64_t *cursor = (uint64_t *)sm->sm_ppd + hbit - 1;
669 uint64_t max_size = metaslab_pp_maxsize(sm);
670
671 ASSERT(MUTEX_HELD(sm->sm_lock));
672 ASSERT3U(avl_numnodes(&sm->sm_root), ==, avl_numnodes(sm->sm_pp_root));
673
674 if (max_size < size)
675 return (-1ULL);
676
677 ssearch.ss_start = *cursor;
678 ssearch.ss_end = *cursor + size;
679
680 ss = avl_find(t, &ssearch, &where);
681 if (ss == NULL || (ss->ss_start + size > ss->ss_end)) {
682 t = sm->sm_pp_root;
683
684 ssearch.ss_start = 0;
685 ssearch.ss_end = MIN(max_size,
686 1ULL << (hbit + metaslab_ndf_clump_shift));
687 ss = avl_find(t, &ssearch, &where);
688 if (ss == NULL)
689 ss = avl_nearest(t, where, AVL_AFTER);
690 ASSERT(ss != NULL);
691 }
692
693 if (ss != NULL) {
694 if (ss->ss_start + size <= ss->ss_end) {
695 *cursor = ss->ss_start + size;
696 return (ss->ss_start);
697 }
698 }
699 return (-1ULL);
700}
701
702static boolean_t
703metaslab_ndf_fragmented(space_map_t *sm)
704{
705 uint64_t max_size = metaslab_pp_maxsize(sm);
706
707 if (max_size > (metaslab_min_alloc_size << metaslab_ndf_clump_shift))
708 return (B_FALSE);
709 return (B_TRUE);
710}
711
712
713static space_map_ops_t metaslab_ndf_ops = {
714 metaslab_pp_load,
715 metaslab_pp_unload,
716 metaslab_ndf_alloc,
717 metaslab_pp_claim,
718 metaslab_pp_free,
719 metaslab_pp_maxsize,
720 metaslab_ndf_fragmented
721};
722
723space_map_ops_t *zfs_metaslab_ops = &metaslab_ndf_ops;
22c81dd8 724#endif /* WITH_NDF_BLOCK_ALLOCATOR */
9babb374 725
34dc7c2f
BB
726/*
727 * ==========================================================================
728 * Metaslabs
729 * ==========================================================================
730 */
731metaslab_t *
732metaslab_init(metaslab_group_t *mg, space_map_obj_t *smo,
733 uint64_t start, uint64_t size, uint64_t txg)
734{
735 vdev_t *vd = mg->mg_vd;
736 metaslab_t *msp;
737
b8d06fca 738 msp = kmem_zalloc(sizeof (metaslab_t), KM_PUSHPAGE);
34dc7c2f
BB
739 mutex_init(&msp->ms_lock, NULL, MUTEX_DEFAULT, NULL);
740
741 msp->ms_smo_syncing = *smo;
742
743 /*
744 * We create the main space map here, but we don't create the
745 * allocmaps and freemaps until metaslab_sync_done(). This serves
746 * two purposes: it allows metaslab_sync_done() to detect the
747 * addition of new space; and for debugging, it ensures that we'd
748 * data fault on any attempt to use this metaslab before it's ready.
749 */
e51be066
GW
750 msp->ms_map = kmem_zalloc(sizeof (space_map_t), KM_PUSHPAGE);
751 space_map_create(msp->ms_map, start, size,
34dc7c2f
BB
752 vd->vdev_ashift, &msp->ms_lock);
753
754 metaslab_group_add(mg, msp);
755
428870ff
BB
756 if (metaslab_debug && smo->smo_object != 0) {
757 mutex_enter(&msp->ms_lock);
e51be066 758 VERIFY(space_map_load(msp->ms_map, mg->mg_class->mc_ops,
428870ff
BB
759 SM_FREE, smo, spa_meta_objset(vd->vdev_spa)) == 0);
760 mutex_exit(&msp->ms_lock);
761 }
762
34dc7c2f
BB
763 /*
764 * If we're opening an existing pool (txg == 0) or creating
765 * a new one (txg == TXG_INITIAL), all space is available now.
766 * If we're adding space to an existing pool, the new space
767 * does not become available until after this txg has synced.
768 */
769 if (txg <= TXG_INITIAL)
770 metaslab_sync_done(msp, 0);
771
772 if (txg != 0) {
34dc7c2f 773 vdev_dirty(vd, 0, NULL, txg);
428870ff 774 vdev_dirty(vd, VDD_METASLAB, msp, txg);
34dc7c2f
BB
775 }
776
777 return (msp);
778}
779
780void
781metaslab_fini(metaslab_t *msp)
782{
783 metaslab_group_t *mg = msp->ms_group;
d6320ddb 784 int t;
34dc7c2f 785
428870ff 786 vdev_space_update(mg->mg_vd,
e51be066 787 -msp->ms_smo.smo_alloc, 0, -msp->ms_map->sm_size);
34dc7c2f
BB
788
789 metaslab_group_remove(mg, msp);
790
791 mutex_enter(&msp->ms_lock);
792
e51be066
GW
793 space_map_unload(msp->ms_map);
794 space_map_destroy(msp->ms_map);
795 kmem_free(msp->ms_map, sizeof (*msp->ms_map));
34dc7c2f 796
d6320ddb 797 for (t = 0; t < TXG_SIZE; t++) {
e51be066
GW
798 space_map_destroy(msp->ms_allocmap[t]);
799 space_map_destroy(msp->ms_freemap[t]);
800 kmem_free(msp->ms_allocmap[t], sizeof (*msp->ms_allocmap[t]));
801 kmem_free(msp->ms_freemap[t], sizeof (*msp->ms_freemap[t]));
34dc7c2f
BB
802 }
803
e51be066
GW
804 for (t = 0; t < TXG_DEFER_SIZE; t++) {
805 space_map_destroy(msp->ms_defermap[t]);
806 kmem_free(msp->ms_defermap[t], sizeof (*msp->ms_defermap[t]));
807 }
428870ff 808
c99c9001 809 ASSERT0(msp->ms_deferspace);
428870ff 810
34dc7c2f
BB
811 mutex_exit(&msp->ms_lock);
812 mutex_destroy(&msp->ms_lock);
813
814 kmem_free(msp, sizeof (metaslab_t));
815}
816
817#define METASLAB_WEIGHT_PRIMARY (1ULL << 63)
818#define METASLAB_WEIGHT_SECONDARY (1ULL << 62)
819#define METASLAB_ACTIVE_MASK \
820 (METASLAB_WEIGHT_PRIMARY | METASLAB_WEIGHT_SECONDARY)
34dc7c2f
BB
821
822static uint64_t
823metaslab_weight(metaslab_t *msp)
824{
825 metaslab_group_t *mg = msp->ms_group;
e51be066 826 space_map_t *sm = msp->ms_map;
34dc7c2f
BB
827 space_map_obj_t *smo = &msp->ms_smo;
828 vdev_t *vd = mg->mg_vd;
829 uint64_t weight, space;
830
831 ASSERT(MUTEX_HELD(&msp->ms_lock));
832
833 /*
834 * The baseline weight is the metaslab's free space.
835 */
836 space = sm->sm_size - smo->smo_alloc;
837 weight = space;
838
839 /*
840 * Modern disks have uniform bit density and constant angular velocity.
841 * Therefore, the outer recording zones are faster (higher bandwidth)
842 * than the inner zones by the ratio of outer to inner track diameter,
843 * which is typically around 2:1. We account for this by assigning
844 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
845 * In effect, this means that we'll select the metaslab with the most
846 * free bandwidth rather than simply the one with the most free space.
847 */
848 weight = 2 * weight -
849 ((sm->sm_start >> vd->vdev_ms_shift) * weight) / vd->vdev_ms_count;
850 ASSERT(weight >= space && weight <= 2 * space);
851
852 /*
428870ff
BB
853 * For locality, assign higher weight to metaslabs which have
854 * a lower offset than what we've already activated.
34dc7c2f 855 */
428870ff
BB
856 if (sm->sm_start <= mg->mg_bonus_area)
857 weight *= (metaslab_smo_bonus_pct / 100);
34dc7c2f 858 ASSERT(weight >= space &&
428870ff
BB
859 weight <= 2 * (metaslab_smo_bonus_pct / 100) * space);
860
861 if (sm->sm_loaded && !sm->sm_ops->smop_fragmented(sm)) {
862 /*
863 * If this metaslab is one we're actively using, adjust its
864 * weight to make it preferable to any inactive metaslab so
865 * we'll polish it off.
866 */
867 weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
868 }
869 return (weight);
870}
871
872static void
873metaslab_prefetch(metaslab_group_t *mg)
874{
875 spa_t *spa = mg->mg_vd->vdev_spa;
876 metaslab_t *msp;
877 avl_tree_t *t = &mg->mg_metaslab_tree;
878 int m;
879
880 mutex_enter(&mg->mg_lock);
34dc7c2f
BB
881
882 /*
428870ff 883 * Prefetch the next potential metaslabs
34dc7c2f 884 */
428870ff 885 for (msp = avl_first(t), m = 0; msp; msp = AVL_NEXT(t, msp), m++) {
e51be066 886 space_map_t *sm = msp->ms_map;
428870ff 887 space_map_obj_t *smo = &msp->ms_smo;
34dc7c2f 888
428870ff
BB
889 /* If we have reached our prefetch limit then we're done */
890 if (m >= metaslab_prefetch_limit)
891 break;
892
893 if (!sm->sm_loaded && smo->smo_object != 0) {
894 mutex_exit(&mg->mg_lock);
895 dmu_prefetch(spa_meta_objset(spa), smo->smo_object,
896 0ULL, smo->smo_objsize);
897 mutex_enter(&mg->mg_lock);
898 }
899 }
900 mutex_exit(&mg->mg_lock);
34dc7c2f
BB
901}
902
903static int
6d974228 904metaslab_activate(metaslab_t *msp, uint64_t activation_weight)
34dc7c2f 905{
428870ff 906 metaslab_group_t *mg = msp->ms_group;
e51be066 907 space_map_t *sm = msp->ms_map;
9babb374 908 space_map_ops_t *sm_ops = msp->ms_group->mg_class->mc_ops;
d6320ddb 909 int t;
34dc7c2f
BB
910
911 ASSERT(MUTEX_HELD(&msp->ms_lock));
912
913 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
428870ff
BB
914 space_map_load_wait(sm);
915 if (!sm->sm_loaded) {
55d85d5a
GW
916 space_map_obj_t *smo = &msp->ms_smo;
917
918 int error = space_map_load(sm, sm_ops, SM_FREE, smo,
428870ff
BB
919 spa_meta_objset(msp->ms_group->mg_vd->vdev_spa));
920 if (error) {
921 metaslab_group_sort(msp->ms_group, msp, 0);
922 return (error);
923 }
d6320ddb 924 for (t = 0; t < TXG_DEFER_SIZE; t++)
e51be066 925 space_map_walk(msp->ms_defermap[t],
428870ff
BB
926 space_map_claim, sm);
927
928 }
929
930 /*
931 * Track the bonus area as we activate new metaslabs.
932 */
933 if (sm->sm_start > mg->mg_bonus_area) {
934 mutex_enter(&mg->mg_lock);
935 mg->mg_bonus_area = sm->sm_start;
936 mutex_exit(&mg->mg_lock);
34dc7c2f 937 }
9babb374 938
34dc7c2f
BB
939 metaslab_group_sort(msp->ms_group, msp,
940 msp->ms_weight | activation_weight);
941 }
942 ASSERT(sm->sm_loaded);
943 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
944
945 return (0);
946}
947
948static void
949metaslab_passivate(metaslab_t *msp, uint64_t size)
950{
951 /*
952 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
953 * this metaslab again. In that case, it had better be empty,
954 * or we would be leaving space on the table.
955 */
e51be066 956 ASSERT(size >= SPA_MINBLOCKSIZE || msp->ms_map->sm_space == 0);
34dc7c2f
BB
957 metaslab_group_sort(msp->ms_group, msp, MIN(msp->ms_weight, size));
958 ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
959}
960
e51be066
GW
961/*
962 * Determine if the in-core space map representation can be condensed on-disk.
963 * We would like to use the following criteria to make our decision:
964 *
965 * 1. The size of the space map object should not dramatically increase as a
966 * result of writing out our in-core free map.
967 *
968 * 2. The minimal on-disk space map representation is zfs_condense_pct/100
969 * times the size than the in-core representation (i.e. zfs_condense_pct = 110
970 * and in-core = 1MB, minimal = 1.1.MB).
971 *
972 * Checking the first condition is tricky since we don't want to walk
973 * the entire AVL tree calculating the estimated on-disk size. Instead we
974 * use the size-ordered AVL tree in the space map and calculate the
975 * size required for the largest segment in our in-core free map. If the
976 * size required to represent that segment on disk is larger than the space
977 * map object then we avoid condensing this map.
978 *
979 * To determine the second criterion we use a best-case estimate and assume
980 * each segment can be represented on-disk as a single 64-bit entry. We refer
981 * to this best-case estimate as the space map's minimal form.
982 */
983static boolean_t
984metaslab_should_condense(metaslab_t *msp)
985{
986 space_map_t *sm = msp->ms_map;
987 space_map_obj_t *smo = &msp->ms_smo_syncing;
988 space_seg_t *ss;
989 uint64_t size, entries, segsz;
990
991 ASSERT(MUTEX_HELD(&msp->ms_lock));
992 ASSERT(sm->sm_loaded);
993
994 /*
995 * Use the sm_pp_root AVL tree, which is ordered by size, to obtain
996 * the largest segment in the in-core free map. If the tree is
997 * empty then we should condense the map.
998 */
999 ss = avl_last(sm->sm_pp_root);
1000 if (ss == NULL)
1001 return (B_TRUE);
1002
1003 /*
1004 * Calculate the number of 64-bit entries this segment would
1005 * require when written to disk. If this single segment would be
1006 * larger on-disk than the entire current on-disk structure, then
1007 * clearly condensing will increase the on-disk structure size.
1008 */
1009 size = (ss->ss_end - ss->ss_start) >> sm->sm_shift;
1010 entries = size / (MIN(size, SM_RUN_MAX));
1011 segsz = entries * sizeof (uint64_t);
1012
1013 return (segsz <= smo->smo_objsize &&
1014 smo->smo_objsize >= (zfs_condense_pct *
1015 sizeof (uint64_t) * avl_numnodes(&sm->sm_root)) / 100);
1016}
1017
1018/*
1019 * Condense the on-disk space map representation to its minimized form.
1020 * The minimized form consists of a small number of allocations followed by
1021 * the in-core free map.
1022 */
1023static void
1024metaslab_condense(metaslab_t *msp, uint64_t txg, dmu_tx_t *tx)
1025{
1026 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
1027 space_map_t *freemap = msp->ms_freemap[txg & TXG_MASK];
1028 space_map_t condense_map;
1029 space_map_t *sm = msp->ms_map;
1030 objset_t *mos = spa_meta_objset(spa);
1031 space_map_obj_t *smo = &msp->ms_smo_syncing;
1032 int t;
1033
1034 ASSERT(MUTEX_HELD(&msp->ms_lock));
1035 ASSERT3U(spa_sync_pass(spa), ==, 1);
1036 ASSERT(sm->sm_loaded);
1037
1038 spa_dbgmsg(spa, "condensing: txg %llu, msp[%llu] %p, "
1039 "smo size %llu, segments %lu", txg,
1040 (msp->ms_map->sm_start / msp->ms_map->sm_size), msp,
1041 smo->smo_objsize, avl_numnodes(&sm->sm_root));
1042
1043 /*
1044 * Create an map that is a 100% allocated map. We remove segments
1045 * that have been freed in this txg, any deferred frees that exist,
1046 * and any allocation in the future. Removing segments should be
1047 * a relatively inexpensive operation since we expect these maps to
1048 * a small number of nodes.
1049 */
1050 space_map_create(&condense_map, sm->sm_start, sm->sm_size,
1051 sm->sm_shift, sm->sm_lock);
1052 space_map_add(&condense_map, condense_map.sm_start,
1053 condense_map.sm_size);
1054
1055 /*
1056 * Remove what's been freed in this txg from the condense_map.
1057 * Since we're in sync_pass 1, we know that all the frees from
1058 * this txg are in the freemap.
1059 */
1060 space_map_walk(freemap, space_map_remove, &condense_map);
1061
1062 for (t = 0; t < TXG_DEFER_SIZE; t++)
1063 space_map_walk(msp->ms_defermap[t],
1064 space_map_remove, &condense_map);
1065
1066 for (t = 1; t < TXG_CONCURRENT_STATES; t++)
1067 space_map_walk(msp->ms_allocmap[(txg + t) & TXG_MASK],
1068 space_map_remove, &condense_map);
1069
1070 /*
1071 * We're about to drop the metaslab's lock thus allowing
1072 * other consumers to change it's content. Set the
1073 * space_map's sm_condensing flag to ensure that
1074 * allocations on this metaslab do not occur while we're
1075 * in the middle of committing it to disk. This is only critical
1076 * for the ms_map as all other space_maps use per txg
1077 * views of their content.
1078 */
1079 sm->sm_condensing = B_TRUE;
1080
1081 mutex_exit(&msp->ms_lock);
1082 space_map_truncate(smo, mos, tx);
1083 mutex_enter(&msp->ms_lock);
1084
1085 /*
1086 * While we would ideally like to create a space_map representation
1087 * that consists only of allocation records, doing so can be
1088 * prohibitively expensive because the in-core free map can be
1089 * large, and therefore computationally expensive to subtract
1090 * from the condense_map. Instead we sync out two maps, a cheap
1091 * allocation only map followed by the in-core free map. While not
1092 * optimal, this is typically close to optimal, and much cheaper to
1093 * compute.
1094 */
1095 space_map_sync(&condense_map, SM_ALLOC, smo, mos, tx);
1096 space_map_vacate(&condense_map, NULL, NULL);
1097 space_map_destroy(&condense_map);
1098
1099 space_map_sync(sm, SM_FREE, smo, mos, tx);
1100 sm->sm_condensing = B_FALSE;
1101
1102 spa_dbgmsg(spa, "condensed: txg %llu, msp[%llu] %p, "
1103 "smo size %llu", txg,
1104 (msp->ms_map->sm_start / msp->ms_map->sm_size), msp,
1105 smo->smo_objsize);
1106}
1107
34dc7c2f
BB
1108/*
1109 * Write a metaslab to disk in the context of the specified transaction group.
1110 */
1111void
1112metaslab_sync(metaslab_t *msp, uint64_t txg)
1113{
1114 vdev_t *vd = msp->ms_group->mg_vd;
1115 spa_t *spa = vd->vdev_spa;
428870ff 1116 objset_t *mos = spa_meta_objset(spa);
e51be066
GW
1117 space_map_t *allocmap = msp->ms_allocmap[txg & TXG_MASK];
1118 space_map_t **freemap = &msp->ms_freemap[txg & TXG_MASK];
1119 space_map_t **freed_map = &msp->ms_freemap[TXG_CLEAN(txg) & TXG_MASK];
1120 space_map_t *sm = msp->ms_map;
34dc7c2f
BB
1121 space_map_obj_t *smo = &msp->ms_smo_syncing;
1122 dmu_buf_t *db;
1123 dmu_tx_t *tx;
34dc7c2f 1124
428870ff
BB
1125 ASSERT(!vd->vdev_ishole);
1126
e51be066
GW
1127 /*
1128 * This metaslab has just been added so there's no work to do now.
1129 */
1130 if (*freemap == NULL) {
1131 ASSERT3P(allocmap, ==, NULL);
1132 return;
1133 }
1134
1135 ASSERT3P(allocmap, !=, NULL);
1136 ASSERT3P(*freemap, !=, NULL);
1137 ASSERT3P(*freed_map, !=, NULL);
1138
1139 if (allocmap->sm_space == 0 && (*freemap)->sm_space == 0)
428870ff 1140 return;
34dc7c2f
BB
1141
1142 /*
1143 * The only state that can actually be changing concurrently with
1144 * metaslab_sync() is the metaslab's ms_map. No other thread can
1145 * be modifying this txg's allocmap, freemap, freed_map, or smo.
1146 * Therefore, we only hold ms_lock to satify space_map ASSERTs.
1147 * We drop it whenever we call into the DMU, because the DMU
1148 * can call down to us (e.g. via zio_free()) at any time.
1149 */
428870ff
BB
1150
1151 tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
34dc7c2f
BB
1152
1153 if (smo->smo_object == 0) {
1154 ASSERT(smo->smo_objsize == 0);
1155 ASSERT(smo->smo_alloc == 0);
34dc7c2f
BB
1156 smo->smo_object = dmu_object_alloc(mos,
1157 DMU_OT_SPACE_MAP, 1 << SPACE_MAP_BLOCKSHIFT,
1158 DMU_OT_SPACE_MAP_HEADER, sizeof (*smo), tx);
1159 ASSERT(smo->smo_object != 0);
1160 dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
1161 (sm->sm_start >> vd->vdev_ms_shift),
1162 sizeof (uint64_t), &smo->smo_object, tx);
34dc7c2f
BB
1163 }
1164
428870ff
BB
1165 mutex_enter(&msp->ms_lock);
1166
e51be066
GW
1167 if (sm->sm_loaded && spa_sync_pass(spa) == 1 &&
1168 metaslab_should_condense(msp)) {
1169 metaslab_condense(msp, txg, tx);
1170 } else {
1171 space_map_sync(allocmap, SM_ALLOC, smo, mos, tx);
1172 space_map_sync(*freemap, SM_FREE, smo, mos, tx);
1173 }
428870ff 1174
e51be066 1175 space_map_vacate(allocmap, NULL, NULL);
34dc7c2f 1176
e51be066
GW
1177 /*
1178 * For sync pass 1, we avoid walking the entire space map and
1179 * instead will just swap the pointers for freemap and
1180 * freed_map. We can safely do this since the freed_map is
1181 * guaranteed to be empty on the initial pass.
1182 */
1183 if (spa_sync_pass(spa) == 1) {
1184 ASSERT0((*freed_map)->sm_space);
1185 ASSERT0(avl_numnodes(&(*freed_map)->sm_root));
1186 space_map_swap(freemap, freed_map);
1187 } else {
1188 space_map_vacate(*freemap, space_map_add, *freed_map);
34dc7c2f
BB
1189 }
1190
e51be066
GW
1191 ASSERT0(msp->ms_allocmap[txg & TXG_MASK]->sm_space);
1192 ASSERT0(msp->ms_freemap[txg & TXG_MASK]->sm_space);
34dc7c2f
BB
1193
1194 mutex_exit(&msp->ms_lock);
1195
e51be066 1196 VERIFY0(dmu_bonus_hold(mos, smo->smo_object, FTAG, &db));
34dc7c2f
BB
1197 dmu_buf_will_dirty(db, tx);
1198 ASSERT3U(db->db_size, >=, sizeof (*smo));
1199 bcopy(smo, db->db_data, sizeof (*smo));
1200 dmu_buf_rele(db, FTAG);
1201
1202 dmu_tx_commit(tx);
1203}
1204
1205/*
1206 * Called after a transaction group has completely synced to mark
1207 * all of the metaslab's free space as usable.
1208 */
1209void
1210metaslab_sync_done(metaslab_t *msp, uint64_t txg)
1211{
1212 space_map_obj_t *smo = &msp->ms_smo;
1213 space_map_obj_t *smosync = &msp->ms_smo_syncing;
e51be066
GW
1214 space_map_t *sm = msp->ms_map;
1215 space_map_t *freed_map = msp->ms_freemap[TXG_CLEAN(txg) & TXG_MASK];
1216 space_map_t *defer_map = msp->ms_defermap[txg % TXG_DEFER_SIZE];
34dc7c2f
BB
1217 metaslab_group_t *mg = msp->ms_group;
1218 vdev_t *vd = mg->mg_vd;
428870ff 1219 int64_t alloc_delta, defer_delta;
d6320ddb 1220 int t;
428870ff
BB
1221
1222 ASSERT(!vd->vdev_ishole);
34dc7c2f
BB
1223
1224 mutex_enter(&msp->ms_lock);
1225
1226 /*
1227 * If this metaslab is just becoming available, initialize its
e51be066 1228 * allocmaps, freemaps, and defermap and add its capacity to the vdev.
34dc7c2f 1229 */
e51be066
GW
1230 if (freed_map == NULL) {
1231 ASSERT(defer_map == NULL);
d6320ddb 1232 for (t = 0; t < TXG_SIZE; t++) {
e51be066
GW
1233 msp->ms_allocmap[t] = kmem_zalloc(sizeof (space_map_t),
1234 KM_PUSHPAGE);
1235 space_map_create(msp->ms_allocmap[t], sm->sm_start,
34dc7c2f 1236 sm->sm_size, sm->sm_shift, sm->sm_lock);
e51be066
GW
1237 msp->ms_freemap[t] = kmem_zalloc(sizeof (space_map_t),
1238 KM_PUSHPAGE);
1239 space_map_create(msp->ms_freemap[t], sm->sm_start,
34dc7c2f
BB
1240 sm->sm_size, sm->sm_shift, sm->sm_lock);
1241 }
428870ff 1242
e51be066
GW
1243 for (t = 0; t < TXG_DEFER_SIZE; t++) {
1244 msp->ms_defermap[t] = kmem_zalloc(sizeof (space_map_t),
1245 KM_PUSHPAGE);
1246 space_map_create(msp->ms_defermap[t], sm->sm_start,
428870ff 1247 sm->sm_size, sm->sm_shift, sm->sm_lock);
e51be066
GW
1248 }
1249
1250 freed_map = msp->ms_freemap[TXG_CLEAN(txg) & TXG_MASK];
1251 defer_map = msp->ms_defermap[txg % TXG_DEFER_SIZE];
428870ff
BB
1252
1253 vdev_space_update(vd, 0, 0, sm->sm_size);
34dc7c2f
BB
1254 }
1255
428870ff
BB
1256 alloc_delta = smosync->smo_alloc - smo->smo_alloc;
1257 defer_delta = freed_map->sm_space - defer_map->sm_space;
1258
1259 vdev_space_update(vd, alloc_delta + defer_delta, defer_delta, 0);
34dc7c2f 1260
e51be066
GW
1261 ASSERT(msp->ms_allocmap[txg & TXG_MASK]->sm_space == 0);
1262 ASSERT(msp->ms_freemap[txg & TXG_MASK]->sm_space == 0);
34dc7c2f
BB
1263
1264 /*
1265 * If there's a space_map_load() in progress, wait for it to complete
1266 * so that we have a consistent view of the in-core space map.
428870ff
BB
1267 * Then, add defer_map (oldest deferred frees) to this map and
1268 * transfer freed_map (this txg's frees) to defer_map.
34dc7c2f
BB
1269 */
1270 space_map_load_wait(sm);
428870ff
BB
1271 space_map_vacate(defer_map, sm->sm_loaded ? space_map_free : NULL, sm);
1272 space_map_vacate(freed_map, space_map_add, defer_map);
34dc7c2f
BB
1273
1274 *smo = *smosync;
1275
428870ff
BB
1276 msp->ms_deferspace += defer_delta;
1277 ASSERT3S(msp->ms_deferspace, >=, 0);
1278 ASSERT3S(msp->ms_deferspace, <=, sm->sm_size);
1279 if (msp->ms_deferspace != 0) {
1280 /*
1281 * Keep syncing this metaslab until all deferred frees
1282 * are back in circulation.
1283 */
1284 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
1285 }
1286
34dc7c2f
BB
1287 /*
1288 * If the map is loaded but no longer active, evict it as soon as all
1289 * future allocations have synced. (If we unloaded it now and then
1290 * loaded a moment later, the map wouldn't reflect those allocations.)
1291 */
1292 if (sm->sm_loaded && (msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
1293 int evictable = 1;
1294
d6320ddb 1295 for (t = 1; t < TXG_CONCURRENT_STATES; t++)
e51be066 1296 if (msp->ms_allocmap[(txg + t) & TXG_MASK]->sm_space)
34dc7c2f
BB
1297 evictable = 0;
1298
428870ff 1299 if (evictable && !metaslab_debug)
34dc7c2f
BB
1300 space_map_unload(sm);
1301 }
1302
1303 metaslab_group_sort(mg, msp, metaslab_weight(msp));
1304
1305 mutex_exit(&msp->ms_lock);
1306}
1307
428870ff
BB
1308void
1309metaslab_sync_reassess(metaslab_group_t *mg)
1310{
1311 vdev_t *vd = mg->mg_vd;
6d974228 1312 int64_t failures = mg->mg_alloc_failures;
d6320ddb 1313 int m;
428870ff
BB
1314
1315 /*
1316 * Re-evaluate all metaslabs which have lower offsets than the
1317 * bonus area.
1318 */
d6320ddb 1319 for (m = 0; m < vd->vdev_ms_count; m++) {
428870ff
BB
1320 metaslab_t *msp = vd->vdev_ms[m];
1321
e51be066 1322 if (msp->ms_map->sm_start > mg->mg_bonus_area)
428870ff
BB
1323 break;
1324
1325 mutex_enter(&msp->ms_lock);
1326 metaslab_group_sort(mg, msp, metaslab_weight(msp));
1327 mutex_exit(&msp->ms_lock);
1328 }
1329
6d974228
GW
1330 atomic_add_64(&mg->mg_alloc_failures, -failures);
1331
428870ff
BB
1332 /*
1333 * Prefetch the next potential metaslabs
1334 */
1335 metaslab_prefetch(mg);
1336}
1337
34dc7c2f
BB
1338static uint64_t
1339metaslab_distance(metaslab_t *msp, dva_t *dva)
1340{
1341 uint64_t ms_shift = msp->ms_group->mg_vd->vdev_ms_shift;
1342 uint64_t offset = DVA_GET_OFFSET(dva) >> ms_shift;
e51be066 1343 uint64_t start = msp->ms_map->sm_start >> ms_shift;
34dc7c2f
BB
1344
1345 if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
1346 return (1ULL << 63);
1347
1348 if (offset < start)
1349 return ((start - offset) << ms_shift);
1350 if (offset > start)
1351 return ((offset - start) << ms_shift);
1352 return (0);
1353}
1354
1355static uint64_t
6d974228
GW
1356metaslab_group_alloc(metaslab_group_t *mg, uint64_t psize, uint64_t asize,
1357 uint64_t txg, uint64_t min_distance, dva_t *dva, int d, int flags)
34dc7c2f 1358{
6d974228 1359 spa_t *spa = mg->mg_vd->vdev_spa;
34dc7c2f
BB
1360 metaslab_t *msp = NULL;
1361 uint64_t offset = -1ULL;
1362 avl_tree_t *t = &mg->mg_metaslab_tree;
1363 uint64_t activation_weight;
1364 uint64_t target_distance;
1365 int i;
1366
1367 activation_weight = METASLAB_WEIGHT_PRIMARY;
9babb374
BB
1368 for (i = 0; i < d; i++) {
1369 if (DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
34dc7c2f 1370 activation_weight = METASLAB_WEIGHT_SECONDARY;
9babb374
BB
1371 break;
1372 }
1373 }
34dc7c2f
BB
1374
1375 for (;;) {
9babb374
BB
1376 boolean_t was_active;
1377
34dc7c2f
BB
1378 mutex_enter(&mg->mg_lock);
1379 for (msp = avl_first(t); msp; msp = AVL_NEXT(t, msp)) {
6d974228
GW
1380 if (msp->ms_weight < asize) {
1381 spa_dbgmsg(spa, "%s: failed to meet weight "
1382 "requirement: vdev %llu, txg %llu, mg %p, "
1383 "msp %p, psize %llu, asize %llu, "
1384 "failures %llu, weight %llu",
1385 spa_name(spa), mg->mg_vd->vdev_id, txg,
1386 mg, msp, psize, asize,
1387 mg->mg_alloc_failures, msp->ms_weight);
34dc7c2f
BB
1388 mutex_exit(&mg->mg_lock);
1389 return (-1ULL);
1390 }
7a614407
GW
1391
1392 /*
1393 * If the selected metaslab is condensing, skip it.
1394 */
1395 if (msp->ms_map->sm_condensing)
1396 continue;
1397
9babb374 1398 was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
34dc7c2f
BB
1399 if (activation_weight == METASLAB_WEIGHT_PRIMARY)
1400 break;
1401
1402 target_distance = min_distance +
1403 (msp->ms_smo.smo_alloc ? 0 : min_distance >> 1);
1404
1405 for (i = 0; i < d; i++)
1406 if (metaslab_distance(msp, &dva[i]) <
1407 target_distance)
1408 break;
1409 if (i == d)
1410 break;
1411 }
1412 mutex_exit(&mg->mg_lock);
1413 if (msp == NULL)
1414 return (-1ULL);
1415
6d974228
GW
1416 /*
1417 * If we've already reached the allowable number of failed
1418 * allocation attempts on this metaslab group then we
1419 * consider skipping it. We skip it only if we're allowed
1420 * to "fast" gang, the physical size is larger than
1421 * a gang block, and we're attempting to allocate from
1422 * the primary metaslab.
1423 */
1424 if (mg->mg_alloc_failures > zfs_mg_alloc_failures &&
1425 CAN_FASTGANG(flags) && psize > SPA_GANGBLOCKSIZE &&
1426 activation_weight == METASLAB_WEIGHT_PRIMARY) {
1427 spa_dbgmsg(spa, "%s: skipping metaslab group: "
1428 "vdev %llu, txg %llu, mg %p, psize %llu, "
1429 "asize %llu, failures %llu", spa_name(spa),
1430 mg->mg_vd->vdev_id, txg, mg, psize, asize,
1431 mg->mg_alloc_failures);
1432 return (-1ULL);
1433 }
1434
34dc7c2f
BB
1435 mutex_enter(&msp->ms_lock);
1436
1437 /*
1438 * Ensure that the metaslab we have selected is still
1439 * capable of handling our request. It's possible that
1440 * another thread may have changed the weight while we
1441 * were blocked on the metaslab lock.
1442 */
6d974228 1443 if (msp->ms_weight < asize || (was_active &&
9babb374
BB
1444 !(msp->ms_weight & METASLAB_ACTIVE_MASK) &&
1445 activation_weight == METASLAB_WEIGHT_PRIMARY)) {
34dc7c2f
BB
1446 mutex_exit(&msp->ms_lock);
1447 continue;
1448 }
1449
1450 if ((msp->ms_weight & METASLAB_WEIGHT_SECONDARY) &&
1451 activation_weight == METASLAB_WEIGHT_PRIMARY) {
1452 metaslab_passivate(msp,
1453 msp->ms_weight & ~METASLAB_ACTIVE_MASK);
1454 mutex_exit(&msp->ms_lock);
1455 continue;
1456 }
1457
6d974228 1458 if (metaslab_activate(msp, activation_weight) != 0) {
34dc7c2f
BB
1459 mutex_exit(&msp->ms_lock);
1460 continue;
1461 }
1462
7a614407
GW
1463 /*
1464 * If this metaslab is currently condensing then pick again as
1465 * we can't manipulate this metaslab until it's committed
1466 * to disk.
1467 */
1468 if (msp->ms_map->sm_condensing) {
1469 mutex_exit(&msp->ms_lock);
1470 continue;
1471 }
1472
e51be066 1473 if ((offset = space_map_alloc(msp->ms_map, asize)) != -1ULL)
34dc7c2f
BB
1474 break;
1475
6d974228
GW
1476 atomic_inc_64(&mg->mg_alloc_failures);
1477
e51be066 1478 metaslab_passivate(msp, space_map_maxsize(msp->ms_map));
34dc7c2f
BB
1479
1480 mutex_exit(&msp->ms_lock);
1481 }
1482
e51be066 1483 if (msp->ms_allocmap[txg & TXG_MASK]->sm_space == 0)
34dc7c2f
BB
1484 vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
1485
e51be066 1486 space_map_add(msp->ms_allocmap[txg & TXG_MASK], offset, asize);
34dc7c2f
BB
1487
1488 mutex_exit(&msp->ms_lock);
1489
1490 return (offset);
1491}
1492
1493/*
1494 * Allocate a block for the specified i/o.
1495 */
1496static int
1497metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
b128c09f 1498 dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags)
34dc7c2f 1499{
920dd524 1500 metaslab_group_t *mg, *fast_mg, *rotor;
34dc7c2f
BB
1501 vdev_t *vd;
1502 int dshift = 3;
1503 int all_zero;
fb5f0bc8
BB
1504 int zio_lock = B_FALSE;
1505 boolean_t allocatable;
34dc7c2f
BB
1506 uint64_t offset = -1ULL;
1507 uint64_t asize;
1508 uint64_t distance;
1509
1510 ASSERT(!DVA_IS_VALID(&dva[d]));
1511
1512 /*
1513 * For testing, make some blocks above a certain size be gang blocks.
1514 */
428870ff 1515 if (psize >= metaslab_gang_bang && (ddi_get_lbolt() & 3) == 0)
34dc7c2f
BB
1516 return (ENOSPC);
1517
920dd524
ED
1518 if (flags & METASLAB_FASTWRITE)
1519 mutex_enter(&mc->mc_fastwrite_lock);
1520
34dc7c2f
BB
1521 /*
1522 * Start at the rotor and loop through all mgs until we find something.
428870ff 1523 * Note that there's no locking on mc_rotor or mc_aliquot because
34dc7c2f
BB
1524 * nothing actually breaks if we miss a few updates -- we just won't
1525 * allocate quite as evenly. It all balances out over time.
1526 *
1527 * If we are doing ditto or log blocks, try to spread them across
1528 * consecutive vdevs. If we're forced to reuse a vdev before we've
1529 * allocated all of our ditto blocks, then try and spread them out on
1530 * that vdev as much as possible. If it turns out to not be possible,
1531 * gradually lower our standards until anything becomes acceptable.
1532 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
1533 * gives us hope of containing our fault domains to something we're
1534 * able to reason about. Otherwise, any two top-level vdev failures
1535 * will guarantee the loss of data. With consecutive allocation,
1536 * only two adjacent top-level vdev failures will result in data loss.
1537 *
1538 * If we are doing gang blocks (hintdva is non-NULL), try to keep
1539 * ourselves on the same vdev as our gang block header. That
1540 * way, we can hope for locality in vdev_cache, plus it makes our
1541 * fault domains something tractable.
1542 */
1543 if (hintdva) {
1544 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
428870ff
BB
1545
1546 /*
1547 * It's possible the vdev we're using as the hint no
1548 * longer exists (i.e. removed). Consult the rotor when
1549 * all else fails.
1550 */
1551 if (vd != NULL) {
34dc7c2f 1552 mg = vd->vdev_mg;
428870ff
BB
1553
1554 if (flags & METASLAB_HINTBP_AVOID &&
1555 mg->mg_next != NULL)
1556 mg = mg->mg_next;
1557 } else {
1558 mg = mc->mc_rotor;
1559 }
34dc7c2f
BB
1560 } else if (d != 0) {
1561 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
1562 mg = vd->vdev_mg->mg_next;
920dd524
ED
1563 } else if (flags & METASLAB_FASTWRITE) {
1564 mg = fast_mg = mc->mc_rotor;
1565
1566 do {
1567 if (fast_mg->mg_vd->vdev_pending_fastwrite <
1568 mg->mg_vd->vdev_pending_fastwrite)
1569 mg = fast_mg;
1570 } while ((fast_mg = fast_mg->mg_next) != mc->mc_rotor);
1571
34dc7c2f
BB
1572 } else {
1573 mg = mc->mc_rotor;
1574 }
1575
1576 /*
428870ff
BB
1577 * If the hint put us into the wrong metaslab class, or into a
1578 * metaslab group that has been passivated, just follow the rotor.
34dc7c2f 1579 */
428870ff 1580 if (mg->mg_class != mc || mg->mg_activation_count <= 0)
34dc7c2f
BB
1581 mg = mc->mc_rotor;
1582
1583 rotor = mg;
1584top:
1585 all_zero = B_TRUE;
1586 do {
428870ff
BB
1587 ASSERT(mg->mg_activation_count == 1);
1588
34dc7c2f 1589 vd = mg->mg_vd;
fb5f0bc8 1590
34dc7c2f 1591 /*
b128c09f 1592 * Don't allocate from faulted devices.
34dc7c2f 1593 */
fb5f0bc8
BB
1594 if (zio_lock) {
1595 spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
1596 allocatable = vdev_allocatable(vd);
1597 spa_config_exit(spa, SCL_ZIO, FTAG);
1598 } else {
1599 allocatable = vdev_allocatable(vd);
1600 }
1601 if (!allocatable)
34dc7c2f 1602 goto next;
fb5f0bc8 1603
34dc7c2f
BB
1604 /*
1605 * Avoid writing single-copy data to a failing vdev
1606 */
1607 if ((vd->vdev_stat.vs_write_errors > 0 ||
1608 vd->vdev_state < VDEV_STATE_HEALTHY) &&
1609 d == 0 && dshift == 3) {
1610 all_zero = B_FALSE;
1611 goto next;
1612 }
1613
1614 ASSERT(mg->mg_class == mc);
1615
1616 distance = vd->vdev_asize >> dshift;
1617 if (distance <= (1ULL << vd->vdev_ms_shift))
1618 distance = 0;
1619 else
1620 all_zero = B_FALSE;
1621
1622 asize = vdev_psize_to_asize(vd, psize);
1623 ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
1624
6d974228
GW
1625 offset = metaslab_group_alloc(mg, psize, asize, txg, distance,
1626 dva, d, flags);
34dc7c2f
BB
1627 if (offset != -1ULL) {
1628 /*
1629 * If we've just selected this metaslab group,
1630 * figure out whether the corresponding vdev is
1631 * over- or under-used relative to the pool,
1632 * and set an allocation bias to even it out.
1633 */
428870ff 1634 if (mc->mc_aliquot == 0) {
34dc7c2f 1635 vdev_stat_t *vs = &vd->vdev_stat;
428870ff 1636 int64_t vu, cu;
34dc7c2f 1637
6d974228
GW
1638 vu = (vs->vs_alloc * 100) / (vs->vs_space + 1);
1639 cu = (mc->mc_alloc * 100) / (mc->mc_space + 1);
34dc7c2f
BB
1640
1641 /*
6d974228
GW
1642 * Calculate how much more or less we should
1643 * try to allocate from this device during
1644 * this iteration around the rotor.
1645 * For example, if a device is 80% full
1646 * and the pool is 20% full then we should
1647 * reduce allocations by 60% on this device.
1648 *
1649 * mg_bias = (20 - 80) * 512K / 100 = -307K
1650 *
1651 * This reduces allocations by 307K for this
1652 * iteration.
34dc7c2f 1653 */
428870ff 1654 mg->mg_bias = ((cu - vu) *
6d974228 1655 (int64_t)mg->mg_aliquot) / 100;
34dc7c2f
BB
1656 }
1657
920dd524
ED
1658 if ((flags & METASLAB_FASTWRITE) ||
1659 atomic_add_64_nv(&mc->mc_aliquot, asize) >=
34dc7c2f
BB
1660 mg->mg_aliquot + mg->mg_bias) {
1661 mc->mc_rotor = mg->mg_next;
428870ff 1662 mc->mc_aliquot = 0;
34dc7c2f
BB
1663 }
1664
1665 DVA_SET_VDEV(&dva[d], vd->vdev_id);
1666 DVA_SET_OFFSET(&dva[d], offset);
b128c09f 1667 DVA_SET_GANG(&dva[d], !!(flags & METASLAB_GANG_HEADER));
34dc7c2f
BB
1668 DVA_SET_ASIZE(&dva[d], asize);
1669
920dd524
ED
1670 if (flags & METASLAB_FASTWRITE) {
1671 atomic_add_64(&vd->vdev_pending_fastwrite,
1672 psize);
1673 mutex_exit(&mc->mc_fastwrite_lock);
1674 }
1675
34dc7c2f
BB
1676 return (0);
1677 }
1678next:
1679 mc->mc_rotor = mg->mg_next;
428870ff 1680 mc->mc_aliquot = 0;
34dc7c2f
BB
1681 } while ((mg = mg->mg_next) != rotor);
1682
1683 if (!all_zero) {
1684 dshift++;
1685 ASSERT(dshift < 64);
1686 goto top;
1687 }
1688
9babb374 1689 if (!allocatable && !zio_lock) {
fb5f0bc8
BB
1690 dshift = 3;
1691 zio_lock = B_TRUE;
1692 goto top;
1693 }
1694
34dc7c2f
BB
1695 bzero(&dva[d], sizeof (dva_t));
1696
920dd524
ED
1697 if (flags & METASLAB_FASTWRITE)
1698 mutex_exit(&mc->mc_fastwrite_lock);
34dc7c2f
BB
1699 return (ENOSPC);
1700}
1701
1702/*
1703 * Free the block represented by DVA in the context of the specified
1704 * transaction group.
1705 */
1706static void
1707metaslab_free_dva(spa_t *spa, const dva_t *dva, uint64_t txg, boolean_t now)
1708{
1709 uint64_t vdev = DVA_GET_VDEV(dva);
1710 uint64_t offset = DVA_GET_OFFSET(dva);
1711 uint64_t size = DVA_GET_ASIZE(dva);
1712 vdev_t *vd;
1713 metaslab_t *msp;
1714
1715 ASSERT(DVA_IS_VALID(dva));
1716
1717 if (txg > spa_freeze_txg(spa))
1718 return;
1719
1720 if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
1721 (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
1722 cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
1723 (u_longlong_t)vdev, (u_longlong_t)offset);
1724 ASSERT(0);
1725 return;
1726 }
1727
1728 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1729
1730 if (DVA_GET_GANG(dva))
1731 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1732
1733 mutex_enter(&msp->ms_lock);
1734
1735 if (now) {
e51be066 1736 space_map_remove(msp->ms_allocmap[txg & TXG_MASK],
34dc7c2f 1737 offset, size);
e51be066 1738 space_map_free(msp->ms_map, offset, size);
34dc7c2f 1739 } else {
e51be066 1740 if (msp->ms_freemap[txg & TXG_MASK]->sm_space == 0)
34dc7c2f 1741 vdev_dirty(vd, VDD_METASLAB, msp, txg);
e51be066 1742 space_map_add(msp->ms_freemap[txg & TXG_MASK], offset, size);
34dc7c2f
BB
1743 }
1744
1745 mutex_exit(&msp->ms_lock);
1746}
1747
1748/*
1749 * Intent log support: upon opening the pool after a crash, notify the SPA
1750 * of blocks that the intent log has allocated for immediate write, but
1751 * which are still considered free by the SPA because the last transaction
1752 * group didn't commit yet.
1753 */
1754static int
1755metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
1756{
1757 uint64_t vdev = DVA_GET_VDEV(dva);
1758 uint64_t offset = DVA_GET_OFFSET(dva);
1759 uint64_t size = DVA_GET_ASIZE(dva);
1760 vdev_t *vd;
1761 metaslab_t *msp;
428870ff 1762 int error = 0;
34dc7c2f
BB
1763
1764 ASSERT(DVA_IS_VALID(dva));
1765
1766 if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
1767 (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
1768 return (ENXIO);
1769
1770 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1771
1772 if (DVA_GET_GANG(dva))
1773 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1774
1775 mutex_enter(&msp->ms_lock);
1776
e51be066 1777 if ((txg != 0 && spa_writeable(spa)) || !msp->ms_map->sm_loaded)
6d974228 1778 error = metaslab_activate(msp, METASLAB_WEIGHT_SECONDARY);
428870ff 1779
e51be066 1780 if (error == 0 && !space_map_contains(msp->ms_map, offset, size))
428870ff
BB
1781 error = ENOENT;
1782
b128c09f 1783 if (error || txg == 0) { /* txg == 0 indicates dry run */
34dc7c2f
BB
1784 mutex_exit(&msp->ms_lock);
1785 return (error);
1786 }
1787
e51be066 1788 space_map_claim(msp->ms_map, offset, size);
b128c09f 1789
fb5f0bc8 1790 if (spa_writeable(spa)) { /* don't dirty if we're zdb(1M) */
e51be066 1791 if (msp->ms_allocmap[txg & TXG_MASK]->sm_space == 0)
b128c09f 1792 vdev_dirty(vd, VDD_METASLAB, msp, txg);
e51be066 1793 space_map_add(msp->ms_allocmap[txg & TXG_MASK], offset, size);
b128c09f 1794 }
34dc7c2f
BB
1795
1796 mutex_exit(&msp->ms_lock);
1797
1798 return (0);
1799}
1800
1801int
1802metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
b128c09f 1803 int ndvas, uint64_t txg, blkptr_t *hintbp, int flags)
34dc7c2f
BB
1804{
1805 dva_t *dva = bp->blk_dva;
1806 dva_t *hintdva = hintbp->blk_dva;
d6320ddb 1807 int d, error = 0;
34dc7c2f 1808
b128c09f 1809 ASSERT(bp->blk_birth == 0);
428870ff 1810 ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
b128c09f
BB
1811
1812 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
1813
1814 if (mc->mc_rotor == NULL) { /* no vdevs in this class */
1815 spa_config_exit(spa, SCL_ALLOC, FTAG);
34dc7c2f 1816 return (ENOSPC);
b128c09f 1817 }
34dc7c2f
BB
1818
1819 ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
1820 ASSERT(BP_GET_NDVAS(bp) == 0);
1821 ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
1822
d6320ddb 1823 for (d = 0; d < ndvas; d++) {
34dc7c2f 1824 error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
b128c09f 1825 txg, flags);
34dc7c2f
BB
1826 if (error) {
1827 for (d--; d >= 0; d--) {
1828 metaslab_free_dva(spa, &dva[d], txg, B_TRUE);
1829 bzero(&dva[d], sizeof (dva_t));
1830 }
b128c09f 1831 spa_config_exit(spa, SCL_ALLOC, FTAG);
34dc7c2f
BB
1832 return (error);
1833 }
1834 }
1835 ASSERT(error == 0);
1836 ASSERT(BP_GET_NDVAS(bp) == ndvas);
1837
b128c09f
BB
1838 spa_config_exit(spa, SCL_ALLOC, FTAG);
1839
428870ff 1840 BP_SET_BIRTH(bp, txg, txg);
b128c09f 1841
34dc7c2f
BB
1842 return (0);
1843}
1844
1845void
1846metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
1847{
1848 const dva_t *dva = bp->blk_dva;
d6320ddb 1849 int d, ndvas = BP_GET_NDVAS(bp);
34dc7c2f
BB
1850
1851 ASSERT(!BP_IS_HOLE(bp));
428870ff 1852 ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
b128c09f
BB
1853
1854 spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
34dc7c2f 1855
d6320ddb 1856 for (d = 0; d < ndvas; d++)
34dc7c2f 1857 metaslab_free_dva(spa, &dva[d], txg, now);
b128c09f
BB
1858
1859 spa_config_exit(spa, SCL_FREE, FTAG);
34dc7c2f
BB
1860}
1861
1862int
1863metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
1864{
1865 const dva_t *dva = bp->blk_dva;
1866 int ndvas = BP_GET_NDVAS(bp);
d6320ddb 1867 int d, error = 0;
34dc7c2f
BB
1868
1869 ASSERT(!BP_IS_HOLE(bp));
1870
b128c09f
BB
1871 if (txg != 0) {
1872 /*
1873 * First do a dry run to make sure all DVAs are claimable,
1874 * so we don't have to unwind from partial failures below.
1875 */
1876 if ((error = metaslab_claim(spa, bp, 0)) != 0)
1877 return (error);
1878 }
1879
1880 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
1881
d6320ddb 1882 for (d = 0; d < ndvas; d++)
34dc7c2f 1883 if ((error = metaslab_claim_dva(spa, &dva[d], txg)) != 0)
b128c09f
BB
1884 break;
1885
1886 spa_config_exit(spa, SCL_ALLOC, FTAG);
1887
1888 ASSERT(error == 0 || txg == 0);
34dc7c2f 1889
b128c09f 1890 return (error);
34dc7c2f 1891}
920dd524
ED
1892
1893void metaslab_fastwrite_mark(spa_t *spa, const blkptr_t *bp)
1894{
1895 const dva_t *dva = bp->blk_dva;
1896 int ndvas = BP_GET_NDVAS(bp);
1897 uint64_t psize = BP_GET_PSIZE(bp);
1898 int d;
1899 vdev_t *vd;
1900
1901 ASSERT(!BP_IS_HOLE(bp));
1902 ASSERT(psize > 0);
1903
1904 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1905
1906 for (d = 0; d < ndvas; d++) {
1907 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
1908 continue;
1909 atomic_add_64(&vd->vdev_pending_fastwrite, psize);
1910 }
1911
1912 spa_config_exit(spa, SCL_VDEV, FTAG);
1913}
1914
1915void metaslab_fastwrite_unmark(spa_t *spa, const blkptr_t *bp)
1916{
1917 const dva_t *dva = bp->blk_dva;
1918 int ndvas = BP_GET_NDVAS(bp);
1919 uint64_t psize = BP_GET_PSIZE(bp);
1920 int d;
1921 vdev_t *vd;
1922
1923 ASSERT(!BP_IS_HOLE(bp));
1924 ASSERT(psize > 0);
1925
1926 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1927
1928 for (d = 0; d < ndvas; d++) {
1929 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
1930 continue;
1931 ASSERT3U(vd->vdev_pending_fastwrite, >=, psize);
1932 atomic_sub_64(&vd->vdev_pending_fastwrite, psize);
1933 }
1934
1935 spa_config_exit(spa, SCL_VDEV, FTAG);
1936}
30b92c1d 1937
13fe0198
MA
1938static void
1939checkmap(space_map_t *sm, uint64_t off, uint64_t size)
1940{
1941 space_seg_t *ss;
1942 avl_index_t where;
1943
1944 mutex_enter(sm->sm_lock);
1945 ss = space_map_find(sm, off, size, &where);
1946 if (ss != NULL)
1947 panic("freeing free block; ss=%p", (void *)ss);
1948 mutex_exit(sm->sm_lock);
1949}
1950
1951void
1952metaslab_check_free(spa_t *spa, const blkptr_t *bp)
1953{
1954 int i, j;
1955
1956 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
1957 return;
1958
1959 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1960 for (i = 0; i < BP_GET_NDVAS(bp); i++) {
1961 uint64_t vdid = DVA_GET_VDEV(&bp->blk_dva[i]);
1962 vdev_t *vd = vdev_lookup_top(spa, vdid);
1963 uint64_t off = DVA_GET_OFFSET(&bp->blk_dva[i]);
1964 uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
1965 metaslab_t *ms = vd->vdev_ms[off >> vd->vdev_ms_shift];
1966
1967 if (ms->ms_map->sm_loaded)
1968 checkmap(ms->ms_map, off, size);
1969
1970 for (j = 0; j < TXG_SIZE; j++)
1971 checkmap(ms->ms_freemap[j], off, size);
1972 for (j = 0; j < TXG_DEFER_SIZE; j++)
1973 checkmap(ms->ms_defermap[j], off, size);
1974 }
1975 spa_config_exit(spa, SCL_VDEV, FTAG);
1976}
1977
30b92c1d
BB
1978#if defined(_KERNEL) && defined(HAVE_SPL)
1979module_param(metaslab_debug, int, 0644);
1980MODULE_PARM_DESC(metaslab_debug, "keep space maps in core to verify frees");
1981#endif /* _KERNEL && HAVE_SPL */