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