Illumos #3552, #3564
[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) 2012 by Delphix. All rights reserved.
24  */
25
26 #include <sys/zfs_context.h>
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
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.
41  * Currently we don't allow any gang, zil, or dump device related allocations
42  * to "fast" gang.
43  */
44 #define CAN_FASTGANG(flags) \
45         (!((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER | \
46         METASLAB_GANG_AVOID)))
47
48 uint64_t metaslab_aliquot = 512ULL << 10;
49 uint64_t metaslab_gang_bang = SPA_MAXBLOCKSIZE + 1;     /* force gang blocks */
50
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  */
57 int zfs_condense_pct = 200;
58
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  */
64 int zfs_mg_alloc_failures;
65
66 /*
67  * Metaslab debugging: when set, keeps all space maps in core to verify frees.
68  */
69 int metaslab_debug = 0;
70
71 /*
72  * Minimum size which forces the dynamic allocator to change
73  * it's allocation strategy.  Once the space map cannot satisfy
74  * an allocation of this size then it switches to using more
75  * aggressive strategy (i.e search by size rather than offset).
76  */
77 uint64_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  */
85 int 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  */
91 uint64_t metaslab_min_alloc_size = DMU_MAX_ACCESS;
92
93 /*
94  * Max number of space_maps to prefetch.
95  */
96 int metaslab_prefetch_limit = SPA_DVAS_PER_BP;
97
98 /*
99  * Percentage bonus multiplier for metaslabs that are in the bonus area.
100  */
101 int metaslab_smo_bonus_pct = 150;
102
103 /*
104  * ==========================================================================
105  * Metaslab classes
106  * ==========================================================================
107  */
108 metaslab_class_t *
109 metaslab_class_create(spa_t *spa, space_map_ops_t *ops)
110 {
111         metaslab_class_t *mc;
112
113         mc = kmem_zalloc(sizeof (metaslab_class_t), KM_PUSHPAGE);
114
115         mc->mc_spa = spa;
116         mc->mc_rotor = NULL;
117         mc->mc_ops = ops;
118         mutex_init(&mc->mc_fastwrite_lock, NULL, MUTEX_DEFAULT, NULL);
119
120         return (mc);
121 }
122
123 void
124 metaslab_class_destroy(metaslab_class_t *mc)
125 {
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);
131
132         mutex_destroy(&mc->mc_fastwrite_lock);
133         kmem_free(mc, sizeof (metaslab_class_t));
134 }
135
136 int
137 metaslab_class_validate(metaslab_class_t *mc)
138 {
139         metaslab_group_t *mg;
140         vdev_t *vd;
141
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));
147
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);
160 }
161
162 void
163 metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
164     int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
165 {
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 }
171
172 uint64_t
173 metaslab_class_get_alloc(metaslab_class_t *mc)
174 {
175         return (mc->mc_alloc);
176 }
177
178 uint64_t
179 metaslab_class_get_deferred(metaslab_class_t *mc)
180 {
181         return (mc->mc_deferred);
182 }
183
184 uint64_t
185 metaslab_class_get_space(metaslab_class_t *mc)
186 {
187         return (mc->mc_space);
188 }
189
190 uint64_t
191 metaslab_class_get_dspace(metaslab_class_t *mc)
192 {
193         return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
194 }
195
196 /*
197  * ==========================================================================
198  * Metaslab groups
199  * ==========================================================================
200  */
201 static int
202 metaslab_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          */
215         if (m1->ms_map->sm_start < m2->ms_map->sm_start)
216                 return (-1);
217         if (m1->ms_map->sm_start > m2->ms_map->sm_start)
218                 return (1);
219
220         ASSERT3P(m1, ==, m2);
221
222         return (0);
223 }
224
225 metaslab_group_t *
226 metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
227 {
228         metaslab_group_t *mg;
229
230         mg = kmem_zalloc(sizeof (metaslab_group_t), KM_PUSHPAGE);
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));
234         mg->mg_vd = vd;
235         mg->mg_class = mc;
236         mg->mg_activation_count = 0;
237
238         return (mg);
239 }
240
241 void
242 metaslab_group_destroy(metaslab_group_t *mg)
243 {
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
253         avl_destroy(&mg->mg_metaslab_tree);
254         mutex_destroy(&mg->mg_lock);
255         kmem_free(mg, sizeof (metaslab_group_t));
256 }
257
258 void
259 metaslab_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
289 void
290 metaslab_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
320 static void
321 metaslab_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
331 static void
332 metaslab_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
341 static void
342 metaslab_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
359 /*
360  * ==========================================================================
361  * Common allocator routines
362  * ==========================================================================
363  */
364 static int
365 metaslab_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
385 #if defined(WITH_FF_BLOCK_ALLOCATOR) || \
386     defined(WITH_DF_BLOCK_ALLOCATOR) || \
387     defined(WITH_CDF_BLOCK_ALLOCATOR)
388 /*
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.
392  */
393 static uint64_t
394 metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
395     uint64_t align)
396 {
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;
425         return (metaslab_block_picker(t, cursor, size, align));
426 }
427 #endif /* WITH_FF/DF/CDF_BLOCK_ALLOCATOR */
428
429 static void
430 metaslab_pp_load(space_map_t *sm)
431 {
432         space_seg_t *ss;
433
434         ASSERT(sm->sm_ppd == NULL);
435         sm->sm_ppd = kmem_zalloc(64 * sizeof (uint64_t), KM_PUSHPAGE);
436
437         sm->sm_pp_root = kmem_alloc(sizeof (avl_tree_t), KM_PUSHPAGE);
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);
443 }
444
445 static void
446 metaslab_pp_unload(space_map_t *sm)
447 {
448         void *cookie = NULL;
449
450         kmem_free(sm->sm_ppd, 64 * sizeof (uint64_t));
451         sm->sm_ppd = NULL;
452
453         while (avl_destroy_nodes(sm->sm_pp_root, &cookie) != NULL) {
454                 /* tear down the tree */
455         }
456
457         avl_destroy(sm->sm_pp_root);
458         kmem_free(sm->sm_pp_root, sizeof (avl_tree_t));
459         sm->sm_pp_root = NULL;
460 }
461
462 /* ARGSUSED */
463 static void
464 metaslab_pp_claim(space_map_t *sm, uint64_t start, uint64_t size)
465 {
466         /* No need to update cursor */
467 }
468
469 /* ARGSUSED */
470 static void
471 metaslab_pp_free(space_map_t *sm, uint64_t start, uint64_t size)
472 {
473         /* No need to update cursor */
474 }
475
476 /*
477  * Return the maximum contiguous segment within the metaslab.
478  */
479 uint64_t
480 metaslab_pp_maxsize(space_map_t *sm)
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
491 #if defined(WITH_FF_BLOCK_ALLOCATOR)
492 /*
493  * ==========================================================================
494  * The first-fit block allocator
495  * ==========================================================================
496  */
497 static uint64_t
498 metaslab_ff_alloc(space_map_t *sm, uint64_t size)
499 {
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;
503
504         return (metaslab_block_picker(t, cursor, size, align));
505 }
506
507 /* ARGSUSED */
508 boolean_t
509 metaslab_ff_fragmented(space_map_t *sm)
510 {
511         return (B_TRUE);
512 }
513
514 static 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 };
523
524 space_map_ops_t *zfs_metaslab_ops = &metaslab_ff_ops;
525 #endif /* WITH_FF_BLOCK_ALLOCATOR */
526
527 #if defined(WITH_DF_BLOCK_ALLOCATOR)
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  */
536 static uint64_t
537 metaslab_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;
542         uint64_t max_size = metaslab_pp_maxsize(sm);
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
564 static boolean_t
565 metaslab_df_fragmented(space_map_t *sm)
566 {
567         uint64_t max_size = metaslab_pp_maxsize(sm);
568         int free_pct = sm->sm_space * 100 / sm->sm_size;
569
570         if (max_size >= metaslab_df_alloc_threshold &&
571             free_pct >= metaslab_df_free_pct)
572                 return (B_FALSE);
573
574         return (B_TRUE);
575 }
576
577 static space_map_ops_t metaslab_df_ops = {
578         metaslab_pp_load,
579         metaslab_pp_unload,
580         metaslab_df_alloc,
581         metaslab_pp_claim,
582         metaslab_pp_free,
583         metaslab_pp_maxsize,
584         metaslab_df_fragmented
585 };
586
587 space_map_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
588 #endif /* WITH_DF_BLOCK_ALLOCATOR */
589
590 /*
591  * ==========================================================================
592  * Other experimental allocators
593  * ==========================================================================
594  */
595 #if defined(WITH_CDF_BLOCK_ALLOCATOR)
596 static uint64_t
597 metaslab_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
635 static boolean_t
636 metaslab_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
645 static 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
655 space_map_ops_t *zfs_metaslab_ops = &metaslab_cdf_ops;
656 #endif /* WITH_CDF_BLOCK_ALLOCATOR */
657
658 #if defined(WITH_NDF_BLOCK_ALLOCATOR)
659 uint64_t metaslab_ndf_clump_shift = 4;
660
661 static uint64_t
662 metaslab_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
702 static boolean_t
703 metaslab_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
713 static 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
723 space_map_ops_t *zfs_metaslab_ops = &metaslab_ndf_ops;
724 #endif /* WITH_NDF_BLOCK_ALLOCATOR */
725
726 /*
727  * ==========================================================================
728  * Metaslabs
729  * ==========================================================================
730  */
731 metaslab_t *
732 metaslab_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
738         msp = kmem_zalloc(sizeof (metaslab_t), KM_PUSHPAGE);
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          */
750         msp->ms_map = kmem_zalloc(sizeof (space_map_t), KM_PUSHPAGE);
751         space_map_create(msp->ms_map, start, size,
752             vd->vdev_ashift, &msp->ms_lock);
753
754         metaslab_group_add(mg, msp);
755
756         if (metaslab_debug && smo->smo_object != 0) {
757                 mutex_enter(&msp->ms_lock);
758                 VERIFY(space_map_load(msp->ms_map, mg->mg_class->mc_ops,
759                     SM_FREE, smo, spa_meta_objset(vd->vdev_spa)) == 0);
760                 mutex_exit(&msp->ms_lock);
761         }
762
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) {
773                 vdev_dirty(vd, 0, NULL, txg);
774                 vdev_dirty(vd, VDD_METASLAB, msp, txg);
775         }
776
777         return (msp);
778 }
779
780 void
781 metaslab_fini(metaslab_t *msp)
782 {
783         metaslab_group_t *mg = msp->ms_group;
784         int t;
785
786         vdev_space_update(mg->mg_vd,
787             -msp->ms_smo.smo_alloc, 0, -msp->ms_map->sm_size);
788
789         metaslab_group_remove(mg, msp);
790
791         mutex_enter(&msp->ms_lock);
792
793         space_map_unload(msp->ms_map);
794         space_map_destroy(msp->ms_map);
795         kmem_free(msp->ms_map, sizeof (*msp->ms_map));
796
797         for (t = 0; t < TXG_SIZE; t++) {
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]));
802         }
803
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         }
808
809         ASSERT0(msp->ms_deferspace);
810
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)
821
822 static uint64_t
823 metaslab_weight(metaslab_t *msp)
824 {
825         metaslab_group_t *mg = msp->ms_group;
826         space_map_t *sm = msp->ms_map;
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         /*
853          * For locality, assign higher weight to metaslabs which have
854          * a lower offset than what we've already activated.
855          */
856         if (sm->sm_start <= mg->mg_bonus_area)
857                 weight *= (metaslab_smo_bonus_pct / 100);
858         ASSERT(weight >= space &&
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
872 static void
873 metaslab_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);
881
882         /*
883          * Prefetch the next potential metaslabs
884          */
885         for (msp = avl_first(t), m = 0; msp; msp = AVL_NEXT(t, msp), m++) {
886                 space_map_t *sm = msp->ms_map;
887                 space_map_obj_t *smo = &msp->ms_smo;
888
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);
901 }
902
903 static int
904 metaslab_activate(metaslab_t *msp, uint64_t activation_weight)
905 {
906         metaslab_group_t *mg = msp->ms_group;
907         space_map_t *sm = msp->ms_map;
908         space_map_ops_t *sm_ops = msp->ms_group->mg_class->mc_ops;
909         int t;
910
911         ASSERT(MUTEX_HELD(&msp->ms_lock));
912
913         if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
914                 space_map_load_wait(sm);
915                 if (!sm->sm_loaded) {
916                         space_map_obj_t *smo = &msp->ms_smo;
917
918                         int error = space_map_load(sm, sm_ops, SM_FREE, smo,
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                         }
924                         for (t = 0; t < TXG_DEFER_SIZE; t++)
925                                 space_map_walk(msp->ms_defermap[t],
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);
937                 }
938
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
948 static void
949 metaslab_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          */
956         ASSERT(size >= SPA_MINBLOCKSIZE || msp->ms_map->sm_space == 0);
957         metaslab_group_sort(msp->ms_group, msp, MIN(msp->ms_weight, size));
958         ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
959 }
960
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  */
983 static boolean_t
984 metaslab_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  */
1023 static void
1024 metaslab_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
1108 /*
1109  * Write a metaslab to disk in the context of the specified transaction group.
1110  */
1111 void
1112 metaslab_sync(metaslab_t *msp, uint64_t txg)
1113 {
1114         vdev_t *vd = msp->ms_group->mg_vd;
1115         spa_t *spa = vd->vdev_spa;
1116         objset_t *mos = spa_meta_objset(spa);
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;
1121         space_map_obj_t *smo = &msp->ms_smo_syncing;
1122         dmu_buf_t *db;
1123         dmu_tx_t *tx;
1124
1125         ASSERT(!vd->vdev_ishole);
1126
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)
1140                 return;
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          */
1150
1151         tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
1152
1153         if (smo->smo_object == 0) {
1154                 ASSERT(smo->smo_objsize == 0);
1155                 ASSERT(smo->smo_alloc == 0);
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);
1163         }
1164
1165         mutex_enter(&msp->ms_lock);
1166
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         }
1174
1175         space_map_vacate(allocmap, NULL, NULL);
1176
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);
1189         }
1190
1191         ASSERT0(msp->ms_allocmap[txg & TXG_MASK]->sm_space);
1192         ASSERT0(msp->ms_freemap[txg & TXG_MASK]->sm_space);
1193
1194         mutex_exit(&msp->ms_lock);
1195
1196         VERIFY0(dmu_bonus_hold(mos, smo->smo_object, FTAG, &db));
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  */
1209 void
1210 metaslab_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;
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];
1217         metaslab_group_t *mg = msp->ms_group;
1218         vdev_t *vd = mg->mg_vd;
1219         int64_t alloc_delta, defer_delta;
1220         int t;
1221
1222         ASSERT(!vd->vdev_ishole);
1223
1224         mutex_enter(&msp->ms_lock);
1225
1226         /*
1227          * If this metaslab is just becoming available, initialize its
1228          * allocmaps, freemaps, and defermap and add its capacity to the vdev.
1229          */
1230         if (freed_map == NULL) {
1231                 ASSERT(defer_map == NULL);
1232                 for (t = 0; t < TXG_SIZE; t++) {
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,
1236                             sm->sm_size, sm->sm_shift, sm->sm_lock);
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,
1240                             sm->sm_size, sm->sm_shift, sm->sm_lock);
1241                 }
1242
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,
1247                             sm->sm_size, sm->sm_shift, sm->sm_lock);
1248                 }
1249
1250                 freed_map = msp->ms_freemap[TXG_CLEAN(txg) & TXG_MASK];
1251                 defer_map = msp->ms_defermap[txg % TXG_DEFER_SIZE];
1252
1253                 vdev_space_update(vd, 0, 0, sm->sm_size);
1254         }
1255
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);
1260
1261         ASSERT(msp->ms_allocmap[txg & TXG_MASK]->sm_space == 0);
1262         ASSERT(msp->ms_freemap[txg & TXG_MASK]->sm_space == 0);
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.
1267          * Then, add defer_map (oldest deferred frees) to this map and
1268          * transfer freed_map (this txg's frees) to defer_map.
1269          */
1270         space_map_load_wait(sm);
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);
1273
1274         *smo = *smosync;
1275
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
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
1295                 for (t = 1; t < TXG_CONCURRENT_STATES; t++)
1296                         if (msp->ms_allocmap[(txg + t) & TXG_MASK]->sm_space)
1297                                 evictable = 0;
1298
1299                 if (evictable && !metaslab_debug)
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
1308 void
1309 metaslab_sync_reassess(metaslab_group_t *mg)
1310 {
1311         vdev_t *vd = mg->mg_vd;
1312         int64_t failures = mg->mg_alloc_failures;
1313         int m;
1314
1315         /*
1316          * Re-evaluate all metaslabs which have lower offsets than the
1317          * bonus area.
1318          */
1319         for (m = 0; m < vd->vdev_ms_count; m++) {
1320                 metaslab_t *msp = vd->vdev_ms[m];
1321
1322                 if (msp->ms_map->sm_start > mg->mg_bonus_area)
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
1330         atomic_add_64(&mg->mg_alloc_failures, -failures);
1331
1332         /*
1333          * Prefetch the next potential metaslabs
1334          */
1335         metaslab_prefetch(mg);
1336 }
1337
1338 static uint64_t
1339 metaslab_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;
1343         uint64_t start = msp->ms_map->sm_start >> ms_shift;
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
1355 static uint64_t
1356 metaslab_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)
1358 {
1359         spa_t *spa = mg->mg_vd->vdev_spa;
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;
1368         for (i = 0; i < d; i++) {
1369                 if (DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
1370                         activation_weight = METASLAB_WEIGHT_SECONDARY;
1371                         break;
1372                 }
1373         }
1374
1375         for (;;) {
1376                 boolean_t was_active;
1377
1378                 mutex_enter(&mg->mg_lock);
1379                 for (msp = avl_first(t); msp; msp = AVL_NEXT(t, msp)) {
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);
1388                                 mutex_exit(&mg->mg_lock);
1389                                 return (-1ULL);
1390                         }
1391                         was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
1392                         if (activation_weight == METASLAB_WEIGHT_PRIMARY)
1393                                 break;
1394
1395                         target_distance = min_distance +
1396                             (msp->ms_smo.smo_alloc ? 0 : min_distance >> 1);
1397
1398                         for (i = 0; i < d; i++)
1399                                 if (metaslab_distance(msp, &dva[i]) <
1400                                     target_distance)
1401                                         break;
1402                         if (i == d)
1403                                 break;
1404                 }
1405                 mutex_exit(&mg->mg_lock);
1406                 if (msp == NULL)
1407                         return (-1ULL);
1408
1409                 /*
1410                  * If we've already reached the allowable number of failed
1411                  * allocation attempts on this metaslab group then we
1412                  * consider skipping it. We skip it only if we're allowed
1413                  * to "fast" gang, the physical size is larger than
1414                  * a gang block, and we're attempting to allocate from
1415                  * the primary metaslab.
1416                  */
1417                 if (mg->mg_alloc_failures > zfs_mg_alloc_failures &&
1418                     CAN_FASTGANG(flags) && psize > SPA_GANGBLOCKSIZE &&
1419                     activation_weight == METASLAB_WEIGHT_PRIMARY) {
1420                         spa_dbgmsg(spa, "%s: skipping metaslab group: "
1421                             "vdev %llu, txg %llu, mg %p, psize %llu, "
1422                             "asize %llu, failures %llu", spa_name(spa),
1423                             mg->mg_vd->vdev_id, txg, mg, psize, asize,
1424                             mg->mg_alloc_failures);
1425                         return (-1ULL);
1426                 }
1427
1428                 mutex_enter(&msp->ms_lock);
1429
1430                 /*
1431                  * If this metaslab is currently condensing then pick again as
1432                  * we can't manipulate this metaslab until it's committed
1433                  * to disk.
1434                  */
1435                 if (msp->ms_map->sm_condensing) {
1436                         mutex_exit(&msp->ms_lock);
1437                         continue;
1438                 }
1439
1440                 /*
1441                  * Ensure that the metaslab we have selected is still
1442                  * capable of handling our request. It's possible that
1443                  * another thread may have changed the weight while we
1444                  * were blocked on the metaslab lock.
1445                  */
1446                 if (msp->ms_weight < asize || (was_active &&
1447                     !(msp->ms_weight & METASLAB_ACTIVE_MASK) &&
1448                     activation_weight == METASLAB_WEIGHT_PRIMARY)) {
1449                         mutex_exit(&msp->ms_lock);
1450                         continue;
1451                 }
1452
1453                 if ((msp->ms_weight & METASLAB_WEIGHT_SECONDARY) &&
1454                     activation_weight == METASLAB_WEIGHT_PRIMARY) {
1455                         metaslab_passivate(msp,
1456                             msp->ms_weight & ~METASLAB_ACTIVE_MASK);
1457                         mutex_exit(&msp->ms_lock);
1458                         continue;
1459                 }
1460
1461                 if (metaslab_activate(msp, activation_weight) != 0) {
1462                         mutex_exit(&msp->ms_lock);
1463                         continue;
1464                 }
1465
1466                 if ((offset = space_map_alloc(msp->ms_map, asize)) != -1ULL)
1467                         break;
1468
1469                 atomic_inc_64(&mg->mg_alloc_failures);
1470
1471                 metaslab_passivate(msp, space_map_maxsize(msp->ms_map));
1472
1473                 mutex_exit(&msp->ms_lock);
1474         }
1475
1476         if (msp->ms_allocmap[txg & TXG_MASK]->sm_space == 0)
1477                 vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
1478
1479         space_map_add(msp->ms_allocmap[txg & TXG_MASK], offset, asize);
1480
1481         mutex_exit(&msp->ms_lock);
1482
1483         return (offset);
1484 }
1485
1486 /*
1487  * Allocate a block for the specified i/o.
1488  */
1489 static int
1490 metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
1491     dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags)
1492 {
1493         metaslab_group_t *mg, *fast_mg, *rotor;
1494         vdev_t *vd;
1495         int dshift = 3;
1496         int all_zero;
1497         int zio_lock = B_FALSE;
1498         boolean_t allocatable;
1499         uint64_t offset = -1ULL;
1500         uint64_t asize;
1501         uint64_t distance;
1502
1503         ASSERT(!DVA_IS_VALID(&dva[d]));
1504
1505         /*
1506          * For testing, make some blocks above a certain size be gang blocks.
1507          */
1508         if (psize >= metaslab_gang_bang && (ddi_get_lbolt() & 3) == 0)
1509                 return (ENOSPC);
1510
1511         if (flags & METASLAB_FASTWRITE)
1512                 mutex_enter(&mc->mc_fastwrite_lock);
1513
1514         /*
1515          * Start at the rotor and loop through all mgs until we find something.
1516          * Note that there's no locking on mc_rotor or mc_aliquot because
1517          * nothing actually breaks if we miss a few updates -- we just won't
1518          * allocate quite as evenly.  It all balances out over time.
1519          *
1520          * If we are doing ditto or log blocks, try to spread them across
1521          * consecutive vdevs.  If we're forced to reuse a vdev before we've
1522          * allocated all of our ditto blocks, then try and spread them out on
1523          * that vdev as much as possible.  If it turns out to not be possible,
1524          * gradually lower our standards until anything becomes acceptable.
1525          * Also, allocating on consecutive vdevs (as opposed to random vdevs)
1526          * gives us hope of containing our fault domains to something we're
1527          * able to reason about.  Otherwise, any two top-level vdev failures
1528          * will guarantee the loss of data.  With consecutive allocation,
1529          * only two adjacent top-level vdev failures will result in data loss.
1530          *
1531          * If we are doing gang blocks (hintdva is non-NULL), try to keep
1532          * ourselves on the same vdev as our gang block header.  That
1533          * way, we can hope for locality in vdev_cache, plus it makes our
1534          * fault domains something tractable.
1535          */
1536         if (hintdva) {
1537                 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
1538
1539                 /*
1540                  * It's possible the vdev we're using as the hint no
1541                  * longer exists (i.e. removed). Consult the rotor when
1542                  * all else fails.
1543                  */
1544                 if (vd != NULL) {
1545                         mg = vd->vdev_mg;
1546
1547                         if (flags & METASLAB_HINTBP_AVOID &&
1548                             mg->mg_next != NULL)
1549                                 mg = mg->mg_next;
1550                 } else {
1551                         mg = mc->mc_rotor;
1552                 }
1553         } else if (d != 0) {
1554                 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
1555                 mg = vd->vdev_mg->mg_next;
1556         } else if (flags & METASLAB_FASTWRITE) {
1557                 mg = fast_mg = mc->mc_rotor;
1558
1559                 do {
1560                         if (fast_mg->mg_vd->vdev_pending_fastwrite <
1561                             mg->mg_vd->vdev_pending_fastwrite)
1562                                 mg = fast_mg;
1563                 } while ((fast_mg = fast_mg->mg_next) != mc->mc_rotor);
1564
1565         } else {
1566                 mg = mc->mc_rotor;
1567         }
1568
1569         /*
1570          * If the hint put us into the wrong metaslab class, or into a
1571          * metaslab group that has been passivated, just follow the rotor.
1572          */
1573         if (mg->mg_class != mc || mg->mg_activation_count <= 0)
1574                 mg = mc->mc_rotor;
1575
1576         rotor = mg;
1577 top:
1578         all_zero = B_TRUE;
1579         do {
1580                 ASSERT(mg->mg_activation_count == 1);
1581
1582                 vd = mg->mg_vd;
1583
1584                 /*
1585                  * Don't allocate from faulted devices.
1586                  */
1587                 if (zio_lock) {
1588                         spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
1589                         allocatable = vdev_allocatable(vd);
1590                         spa_config_exit(spa, SCL_ZIO, FTAG);
1591                 } else {
1592                         allocatable = vdev_allocatable(vd);
1593                 }
1594                 if (!allocatable)
1595                         goto next;
1596
1597                 /*
1598                  * Avoid writing single-copy data to a failing vdev
1599                  */
1600                 if ((vd->vdev_stat.vs_write_errors > 0 ||
1601                     vd->vdev_state < VDEV_STATE_HEALTHY) &&
1602                     d == 0 && dshift == 3) {
1603                         all_zero = B_FALSE;
1604                         goto next;
1605                 }
1606
1607                 ASSERT(mg->mg_class == mc);
1608
1609                 distance = vd->vdev_asize >> dshift;
1610                 if (distance <= (1ULL << vd->vdev_ms_shift))
1611                         distance = 0;
1612                 else
1613                         all_zero = B_FALSE;
1614
1615                 asize = vdev_psize_to_asize(vd, psize);
1616                 ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
1617
1618                 offset = metaslab_group_alloc(mg, psize, asize, txg, distance,
1619                     dva, d, flags);
1620                 if (offset != -1ULL) {
1621                         /*
1622                          * If we've just selected this metaslab group,
1623                          * figure out whether the corresponding vdev is
1624                          * over- or under-used relative to the pool,
1625                          * and set an allocation bias to even it out.
1626                          */
1627                         if (mc->mc_aliquot == 0) {
1628                                 vdev_stat_t *vs = &vd->vdev_stat;
1629                                 int64_t vu, cu;
1630
1631                                 vu = (vs->vs_alloc * 100) / (vs->vs_space + 1);
1632                                 cu = (mc->mc_alloc * 100) / (mc->mc_space + 1);
1633
1634                                 /*
1635                                  * Calculate how much more or less we should
1636                                  * try to allocate from this device during
1637                                  * this iteration around the rotor.
1638                                  * For example, if a device is 80% full
1639                                  * and the pool is 20% full then we should
1640                                  * reduce allocations by 60% on this device.
1641                                  *
1642                                  * mg_bias = (20 - 80) * 512K / 100 = -307K
1643                                  *
1644                                  * This reduces allocations by 307K for this
1645                                  * iteration.
1646                                  */
1647                                 mg->mg_bias = ((cu - vu) *
1648                                     (int64_t)mg->mg_aliquot) / 100;
1649                         }
1650
1651                         if ((flags & METASLAB_FASTWRITE) ||
1652                             atomic_add_64_nv(&mc->mc_aliquot, asize) >=
1653                             mg->mg_aliquot + mg->mg_bias) {
1654                                 mc->mc_rotor = mg->mg_next;
1655                                 mc->mc_aliquot = 0;
1656                         }
1657
1658                         DVA_SET_VDEV(&dva[d], vd->vdev_id);
1659                         DVA_SET_OFFSET(&dva[d], offset);
1660                         DVA_SET_GANG(&dva[d], !!(flags & METASLAB_GANG_HEADER));
1661                         DVA_SET_ASIZE(&dva[d], asize);
1662
1663                         if (flags & METASLAB_FASTWRITE) {
1664                                 atomic_add_64(&vd->vdev_pending_fastwrite,
1665                                     psize);
1666                                 mutex_exit(&mc->mc_fastwrite_lock);
1667                         }
1668
1669                         return (0);
1670                 }
1671 next:
1672                 mc->mc_rotor = mg->mg_next;
1673                 mc->mc_aliquot = 0;
1674         } while ((mg = mg->mg_next) != rotor);
1675
1676         if (!all_zero) {
1677                 dshift++;
1678                 ASSERT(dshift < 64);
1679                 goto top;
1680         }
1681
1682         if (!allocatable && !zio_lock) {
1683                 dshift = 3;
1684                 zio_lock = B_TRUE;
1685                 goto top;
1686         }
1687
1688         bzero(&dva[d], sizeof (dva_t));
1689
1690         if (flags & METASLAB_FASTWRITE)
1691                 mutex_exit(&mc->mc_fastwrite_lock);
1692         return (ENOSPC);
1693 }
1694
1695 /*
1696  * Free the block represented by DVA in the context of the specified
1697  * transaction group.
1698  */
1699 static void
1700 metaslab_free_dva(spa_t *spa, const dva_t *dva, uint64_t txg, boolean_t now)
1701 {
1702         uint64_t vdev = DVA_GET_VDEV(dva);
1703         uint64_t offset = DVA_GET_OFFSET(dva);
1704         uint64_t size = DVA_GET_ASIZE(dva);
1705         vdev_t *vd;
1706         metaslab_t *msp;
1707
1708         ASSERT(DVA_IS_VALID(dva));
1709
1710         if (txg > spa_freeze_txg(spa))
1711                 return;
1712
1713         if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
1714             (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
1715                 cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
1716                     (u_longlong_t)vdev, (u_longlong_t)offset);
1717                 ASSERT(0);
1718                 return;
1719         }
1720
1721         msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1722
1723         if (DVA_GET_GANG(dva))
1724                 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1725
1726         mutex_enter(&msp->ms_lock);
1727
1728         if (now) {
1729                 space_map_remove(msp->ms_allocmap[txg & TXG_MASK],
1730                     offset, size);
1731                 space_map_free(msp->ms_map, offset, size);
1732         } else {
1733                 if (msp->ms_freemap[txg & TXG_MASK]->sm_space == 0)
1734                         vdev_dirty(vd, VDD_METASLAB, msp, txg);
1735                 space_map_add(msp->ms_freemap[txg & TXG_MASK], offset, size);
1736         }
1737
1738         mutex_exit(&msp->ms_lock);
1739 }
1740
1741 /*
1742  * Intent log support: upon opening the pool after a crash, notify the SPA
1743  * of blocks that the intent log has allocated for immediate write, but
1744  * which are still considered free by the SPA because the last transaction
1745  * group didn't commit yet.
1746  */
1747 static int
1748 metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
1749 {
1750         uint64_t vdev = DVA_GET_VDEV(dva);
1751         uint64_t offset = DVA_GET_OFFSET(dva);
1752         uint64_t size = DVA_GET_ASIZE(dva);
1753         vdev_t *vd;
1754         metaslab_t *msp;
1755         int error = 0;
1756
1757         ASSERT(DVA_IS_VALID(dva));
1758
1759         if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
1760             (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
1761                 return (ENXIO);
1762
1763         msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1764
1765         if (DVA_GET_GANG(dva))
1766                 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1767
1768         mutex_enter(&msp->ms_lock);
1769
1770         if ((txg != 0 && spa_writeable(spa)) || !msp->ms_map->sm_loaded)
1771                 error = metaslab_activate(msp, METASLAB_WEIGHT_SECONDARY);
1772
1773         if (error == 0 && !space_map_contains(msp->ms_map, offset, size))
1774                 error = ENOENT;
1775
1776         if (error || txg == 0) {        /* txg == 0 indicates dry run */
1777                 mutex_exit(&msp->ms_lock);
1778                 return (error);
1779         }
1780
1781         space_map_claim(msp->ms_map, offset, size);
1782
1783         if (spa_writeable(spa)) {       /* don't dirty if we're zdb(1M) */
1784                 if (msp->ms_allocmap[txg & TXG_MASK]->sm_space == 0)
1785                         vdev_dirty(vd, VDD_METASLAB, msp, txg);
1786                 space_map_add(msp->ms_allocmap[txg & TXG_MASK], offset, size);
1787         }
1788
1789         mutex_exit(&msp->ms_lock);
1790
1791         return (0);
1792 }
1793
1794 int
1795 metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
1796     int ndvas, uint64_t txg, blkptr_t *hintbp, int flags)
1797 {
1798         dva_t *dva = bp->blk_dva;
1799         dva_t *hintdva = hintbp->blk_dva;
1800         int d, error = 0;
1801
1802         ASSERT(bp->blk_birth == 0);
1803         ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
1804
1805         spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
1806
1807         if (mc->mc_rotor == NULL) {     /* no vdevs in this class */
1808                 spa_config_exit(spa, SCL_ALLOC, FTAG);
1809                 return (ENOSPC);
1810         }
1811
1812         ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
1813         ASSERT(BP_GET_NDVAS(bp) == 0);
1814         ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
1815
1816         for (d = 0; d < ndvas; d++) {
1817                 error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
1818                     txg, flags);
1819                 if (error) {
1820                         for (d--; d >= 0; d--) {
1821                                 metaslab_free_dva(spa, &dva[d], txg, B_TRUE);
1822                                 bzero(&dva[d], sizeof (dva_t));
1823                         }
1824                         spa_config_exit(spa, SCL_ALLOC, FTAG);
1825                         return (error);
1826                 }
1827         }
1828         ASSERT(error == 0);
1829         ASSERT(BP_GET_NDVAS(bp) == ndvas);
1830
1831         spa_config_exit(spa, SCL_ALLOC, FTAG);
1832
1833         BP_SET_BIRTH(bp, txg, txg);
1834
1835         return (0);
1836 }
1837
1838 void
1839 metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
1840 {
1841         const dva_t *dva = bp->blk_dva;
1842         int d, ndvas = BP_GET_NDVAS(bp);
1843
1844         ASSERT(!BP_IS_HOLE(bp));
1845         ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
1846
1847         spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
1848
1849         for (d = 0; d < ndvas; d++)
1850                 metaslab_free_dva(spa, &dva[d], txg, now);
1851
1852         spa_config_exit(spa, SCL_FREE, FTAG);
1853 }
1854
1855 int
1856 metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
1857 {
1858         const dva_t *dva = bp->blk_dva;
1859         int ndvas = BP_GET_NDVAS(bp);
1860         int d, error = 0;
1861
1862         ASSERT(!BP_IS_HOLE(bp));
1863
1864         if (txg != 0) {
1865                 /*
1866                  * First do a dry run to make sure all DVAs are claimable,
1867                  * so we don't have to unwind from partial failures below.
1868                  */
1869                 if ((error = metaslab_claim(spa, bp, 0)) != 0)
1870                         return (error);
1871         }
1872
1873         spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
1874
1875         for (d = 0; d < ndvas; d++)
1876                 if ((error = metaslab_claim_dva(spa, &dva[d], txg)) != 0)
1877                         break;
1878
1879         spa_config_exit(spa, SCL_ALLOC, FTAG);
1880
1881         ASSERT(error == 0 || txg == 0);
1882
1883         return (error);
1884 }
1885
1886 void metaslab_fastwrite_mark(spa_t *spa, const blkptr_t *bp)
1887 {
1888         const dva_t *dva = bp->blk_dva;
1889         int ndvas = BP_GET_NDVAS(bp);
1890         uint64_t psize = BP_GET_PSIZE(bp);
1891         int d;
1892         vdev_t *vd;
1893
1894         ASSERT(!BP_IS_HOLE(bp));
1895         ASSERT(psize > 0);
1896
1897         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1898
1899         for (d = 0; d < ndvas; d++) {
1900                 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
1901                         continue;
1902                 atomic_add_64(&vd->vdev_pending_fastwrite, psize);
1903         }
1904
1905         spa_config_exit(spa, SCL_VDEV, FTAG);
1906 }
1907
1908 void metaslab_fastwrite_unmark(spa_t *spa, const blkptr_t *bp)
1909 {
1910         const dva_t *dva = bp->blk_dva;
1911         int ndvas = BP_GET_NDVAS(bp);
1912         uint64_t psize = BP_GET_PSIZE(bp);
1913         int d;
1914         vdev_t *vd;
1915
1916         ASSERT(!BP_IS_HOLE(bp));
1917         ASSERT(psize > 0);
1918
1919         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1920
1921         for (d = 0; d < ndvas; d++) {
1922                 if ((vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d]))) == NULL)
1923                         continue;
1924                 ASSERT3U(vd->vdev_pending_fastwrite, >=, psize);
1925                 atomic_sub_64(&vd->vdev_pending_fastwrite, psize);
1926         }
1927
1928         spa_config_exit(spa, SCL_VDEV, FTAG);
1929 }
1930
1931 #if defined(_KERNEL) && defined(HAVE_SPL)
1932 module_param(metaslab_debug, int, 0644);
1933 MODULE_PARM_DESC(metaslab_debug, "keep space maps in core to verify frees");
1934 #endif /* _KERNEL && HAVE_SPL */