Fix metaslab
[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  */
24
25 #include <sys/zfs_context.h>
26 #include <sys/dmu.h>
27 #include <sys/dmu_tx.h>
28 #include <sys/space_map.h>
29 #include <sys/metaslab_impl.h>
30 #include <sys/vdev_impl.h>
31 #include <sys/zio.h>
32
33 #define WITH_NDF_BLOCK_ALLOCATOR
34
35 uint64_t metaslab_aliquot = 512ULL << 10;
36 uint64_t metaslab_gang_bang = SPA_MAXBLOCKSIZE + 1;     /* force gang blocks */
37
38 /*
39  * Metaslab debugging: when set, keeps all space maps in core to verify frees.
40  */
41 static int metaslab_debug = 0;
42
43 /*
44  * Minimum size which forces the dynamic allocator to change
45  * it's allocation strategy.  Once the space map cannot satisfy
46  * an allocation of this size then it switches to using more
47  * aggressive strategy (i.e search by size rather than offset).
48  */
49 uint64_t metaslab_df_alloc_threshold = SPA_MAXBLOCKSIZE;
50
51 /*
52  * The minimum free space, in percent, which must be available
53  * in a space map to continue allocations in a first-fit fashion.
54  * Once the space_map's free space drops below this level we dynamically
55  * switch to using best-fit allocations.
56  */
57 int metaslab_df_free_pct = 4;
58
59 /*
60  * A metaslab is considered "free" if it contains a contiguous
61  * segment which is greater than metaslab_min_alloc_size.
62  */
63 uint64_t metaslab_min_alloc_size = DMU_MAX_ACCESS;
64
65 /*
66  * Max number of space_maps to prefetch.
67  */
68 int metaslab_prefetch_limit = SPA_DVAS_PER_BP;
69
70 /*
71  * Percentage bonus multiplier for metaslabs that are in the bonus area.
72  */
73 int metaslab_smo_bonus_pct = 150;
74
75 /*
76  * ==========================================================================
77  * Metaslab classes
78  * ==========================================================================
79  */
80 metaslab_class_t *
81 metaslab_class_create(spa_t *spa, space_map_ops_t *ops)
82 {
83         metaslab_class_t *mc;
84
85         mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
86
87         mc->mc_spa = spa;
88         mc->mc_rotor = NULL;
89         mc->mc_ops = ops;
90
91         return (mc);
92 }
93
94 void
95 metaslab_class_destroy(metaslab_class_t *mc)
96 {
97         ASSERT(mc->mc_rotor == NULL);
98         ASSERT(mc->mc_alloc == 0);
99         ASSERT(mc->mc_deferred == 0);
100         ASSERT(mc->mc_space == 0);
101         ASSERT(mc->mc_dspace == 0);
102
103         kmem_free(mc, sizeof (metaslab_class_t));
104 }
105
106 int
107 metaslab_class_validate(metaslab_class_t *mc)
108 {
109         metaslab_group_t *mg;
110         vdev_t *vd;
111
112         /*
113          * Must hold one of the spa_config locks.
114          */
115         ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
116             spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
117
118         if ((mg = mc->mc_rotor) == NULL)
119                 return (0);
120
121         do {
122                 vd = mg->mg_vd;
123                 ASSERT(vd->vdev_mg != NULL);
124                 ASSERT3P(vd->vdev_top, ==, vd);
125                 ASSERT3P(mg->mg_class, ==, mc);
126                 ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
127         } while ((mg = mg->mg_next) != mc->mc_rotor);
128
129         return (0);
130 }
131
132 void
133 metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
134     int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
135 {
136         atomic_add_64(&mc->mc_alloc, alloc_delta);
137         atomic_add_64(&mc->mc_deferred, defer_delta);
138         atomic_add_64(&mc->mc_space, space_delta);
139         atomic_add_64(&mc->mc_dspace, dspace_delta);
140 }
141
142 uint64_t
143 metaslab_class_get_alloc(metaslab_class_t *mc)
144 {
145         return (mc->mc_alloc);
146 }
147
148 uint64_t
149 metaslab_class_get_deferred(metaslab_class_t *mc)
150 {
151         return (mc->mc_deferred);
152 }
153
154 uint64_t
155 metaslab_class_get_space(metaslab_class_t *mc)
156 {
157         return (mc->mc_space);
158 }
159
160 uint64_t
161 metaslab_class_get_dspace(metaslab_class_t *mc)
162 {
163         return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
164 }
165
166 /*
167  * ==========================================================================
168  * Metaslab groups
169  * ==========================================================================
170  */
171 static int
172 metaslab_compare(const void *x1, const void *x2)
173 {
174         const metaslab_t *m1 = x1;
175         const metaslab_t *m2 = x2;
176
177         if (m1->ms_weight < m2->ms_weight)
178                 return (1);
179         if (m1->ms_weight > m2->ms_weight)
180                 return (-1);
181
182         /*
183          * If the weights are identical, use the offset to force uniqueness.
184          */
185         if (m1->ms_map.sm_start < m2->ms_map.sm_start)
186                 return (-1);
187         if (m1->ms_map.sm_start > m2->ms_map.sm_start)
188                 return (1);
189
190         ASSERT3P(m1, ==, m2);
191
192         return (0);
193 }
194
195 metaslab_group_t *
196 metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
197 {
198         metaslab_group_t *mg;
199
200         mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
201         mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
202         avl_create(&mg->mg_metaslab_tree, metaslab_compare,
203             sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
204         mg->mg_vd = vd;
205         mg->mg_class = mc;
206         mg->mg_activation_count = 0;
207
208         return (mg);
209 }
210
211 void
212 metaslab_group_destroy(metaslab_group_t *mg)
213 {
214         ASSERT(mg->mg_prev == NULL);
215         ASSERT(mg->mg_next == NULL);
216         /*
217          * We may have gone below zero with the activation count
218          * either because we never activated in the first place or
219          * because we're done, and possibly removing the vdev.
220          */
221         ASSERT(mg->mg_activation_count <= 0);
222
223         avl_destroy(&mg->mg_metaslab_tree);
224         mutex_destroy(&mg->mg_lock);
225         kmem_free(mg, sizeof (metaslab_group_t));
226 }
227
228 void
229 metaslab_group_activate(metaslab_group_t *mg)
230 {
231         metaslab_class_t *mc = mg->mg_class;
232         metaslab_group_t *mgprev, *mgnext;
233
234         ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
235
236         ASSERT(mc->mc_rotor != mg);
237         ASSERT(mg->mg_prev == NULL);
238         ASSERT(mg->mg_next == NULL);
239         ASSERT(mg->mg_activation_count <= 0);
240
241         if (++mg->mg_activation_count <= 0)
242                 return;
243
244         mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
245
246         if ((mgprev = mc->mc_rotor) == NULL) {
247                 mg->mg_prev = mg;
248                 mg->mg_next = mg;
249         } else {
250                 mgnext = mgprev->mg_next;
251                 mg->mg_prev = mgprev;
252                 mg->mg_next = mgnext;
253                 mgprev->mg_next = mg;
254                 mgnext->mg_prev = mg;
255         }
256         mc->mc_rotor = mg;
257 }
258
259 void
260 metaslab_group_passivate(metaslab_group_t *mg)
261 {
262         metaslab_class_t *mc = mg->mg_class;
263         metaslab_group_t *mgprev, *mgnext;
264
265         ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
266
267         if (--mg->mg_activation_count != 0) {
268                 ASSERT(mc->mc_rotor != mg);
269                 ASSERT(mg->mg_prev == NULL);
270                 ASSERT(mg->mg_next == NULL);
271                 ASSERT(mg->mg_activation_count < 0);
272                 return;
273         }
274
275         mgprev = mg->mg_prev;
276         mgnext = mg->mg_next;
277
278         if (mg == mgnext) {
279                 mc->mc_rotor = NULL;
280         } else {
281                 mc->mc_rotor = mgnext;
282                 mgprev->mg_next = mgnext;
283                 mgnext->mg_prev = mgprev;
284         }
285
286         mg->mg_prev = NULL;
287         mg->mg_next = NULL;
288 }
289
290 static void
291 metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
292 {
293         mutex_enter(&mg->mg_lock);
294         ASSERT(msp->ms_group == NULL);
295         msp->ms_group = mg;
296         msp->ms_weight = 0;
297         avl_add(&mg->mg_metaslab_tree, msp);
298         mutex_exit(&mg->mg_lock);
299 }
300
301 static void
302 metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
303 {
304         mutex_enter(&mg->mg_lock);
305         ASSERT(msp->ms_group == mg);
306         avl_remove(&mg->mg_metaslab_tree, msp);
307         msp->ms_group = NULL;
308         mutex_exit(&mg->mg_lock);
309 }
310
311 static void
312 metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
313 {
314         /*
315          * Although in principle the weight can be any value, in
316          * practice we do not use values in the range [1, 510].
317          */
318         ASSERT(weight >= SPA_MINBLOCKSIZE-1 || weight == 0);
319         ASSERT(MUTEX_HELD(&msp->ms_lock));
320
321         mutex_enter(&mg->mg_lock);
322         ASSERT(msp->ms_group == mg);
323         avl_remove(&mg->mg_metaslab_tree, msp);
324         msp->ms_weight = weight;
325         avl_add(&mg->mg_metaslab_tree, msp);
326         mutex_exit(&mg->mg_lock);
327 }
328
329 /*
330  * ==========================================================================
331  * Common allocator routines
332  * ==========================================================================
333  */
334 static int
335 metaslab_segsize_compare(const void *x1, const void *x2)
336 {
337         const space_seg_t *s1 = x1;
338         const space_seg_t *s2 = x2;
339         uint64_t ss_size1 = s1->ss_end - s1->ss_start;
340         uint64_t ss_size2 = s2->ss_end - s2->ss_start;
341
342         if (ss_size1 < ss_size2)
343                 return (-1);
344         if (ss_size1 > ss_size2)
345                 return (1);
346
347         if (s1->ss_start < s2->ss_start)
348                 return (-1);
349         if (s1->ss_start > s2->ss_start)
350                 return (1);
351
352         return (0);
353 }
354
355 #if defined(WITH_FF_BLOCK_ALLOCATOR) || \
356     defined(WITH_DF_BLOCK_ALLOCATOR) || \
357     defined(WITH_CDF_BLOCK_ALLOCATOR)
358 /*
359  * This is a helper function that can be used by the allocator to find
360  * a suitable block to allocate. This will search the specified AVL
361  * tree looking for a block that matches the specified criteria.
362  */
363 static uint64_t
364 metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
365     uint64_t align)
366 {
367         space_seg_t *ss, ssearch;
368         avl_index_t where;
369
370         ssearch.ss_start = *cursor;
371         ssearch.ss_end = *cursor + size;
372
373         ss = avl_find(t, &ssearch, &where);
374         if (ss == NULL)
375                 ss = avl_nearest(t, where, AVL_AFTER);
376
377         while (ss != NULL) {
378                 uint64_t offset = P2ROUNDUP(ss->ss_start, align);
379
380                 if (offset + size <= ss->ss_end) {
381                         *cursor = offset + size;
382                         return (offset);
383                 }
384                 ss = AVL_NEXT(t, ss);
385         }
386
387         /*
388          * If we know we've searched the whole map (*cursor == 0), give up.
389          * Otherwise, reset the cursor to the beginning and try again.
390          */
391         if (*cursor == 0)
392                 return (-1ULL);
393
394         *cursor = 0;
395         return (metaslab_block_picker(t, cursor, size, align));
396 }
397 #endif /* WITH_FF/DF/CDF_BLOCK_ALLOCATOR */
398
399 static void
400 metaslab_pp_load(space_map_t *sm)
401 {
402         space_seg_t *ss;
403
404         ASSERT(sm->sm_ppd == NULL);
405         sm->sm_ppd = kmem_zalloc(64 * sizeof (uint64_t), KM_SLEEP);
406
407         sm->sm_pp_root = kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
408         avl_create(sm->sm_pp_root, metaslab_segsize_compare,
409             sizeof (space_seg_t), offsetof(struct space_seg, ss_pp_node));
410
411         for (ss = avl_first(&sm->sm_root); ss; ss = AVL_NEXT(&sm->sm_root, ss))
412                 avl_add(sm->sm_pp_root, ss);
413 }
414
415 static void
416 metaslab_pp_unload(space_map_t *sm)
417 {
418         void *cookie = NULL;
419
420         kmem_free(sm->sm_ppd, 64 * sizeof (uint64_t));
421         sm->sm_ppd = NULL;
422
423         while (avl_destroy_nodes(sm->sm_pp_root, &cookie) != NULL) {
424                 /* tear down the tree */
425         }
426
427         avl_destroy(sm->sm_pp_root);
428         kmem_free(sm->sm_pp_root, sizeof (avl_tree_t));
429         sm->sm_pp_root = NULL;
430 }
431
432 /* ARGSUSED */
433 static void
434 metaslab_pp_claim(space_map_t *sm, uint64_t start, uint64_t size)
435 {
436         /* No need to update cursor */
437 }
438
439 /* ARGSUSED */
440 static void
441 metaslab_pp_free(space_map_t *sm, uint64_t start, uint64_t size)
442 {
443         /* No need to update cursor */
444 }
445
446 /*
447  * Return the maximum contiguous segment within the metaslab.
448  */
449 uint64_t
450 metaslab_pp_maxsize(space_map_t *sm)
451 {
452         avl_tree_t *t = sm->sm_pp_root;
453         space_seg_t *ss;
454
455         if (t == NULL || (ss = avl_last(t)) == NULL)
456                 return (0ULL);
457
458         return (ss->ss_end - ss->ss_start);
459 }
460
461 #if defined(WITH_FF_BLOCK_ALLOCATOR)
462 /*
463  * ==========================================================================
464  * The first-fit block allocator
465  * ==========================================================================
466  */
467 static uint64_t
468 metaslab_ff_alloc(space_map_t *sm, uint64_t size)
469 {
470         avl_tree_t *t = &sm->sm_root;
471         uint64_t align = size & -size;
472         uint64_t *cursor = (uint64_t *)sm->sm_ppd + highbit(align) - 1;
473
474         return (metaslab_block_picker(t, cursor, size, align));
475 }
476
477 /* ARGSUSED */
478 boolean_t
479 metaslab_ff_fragmented(space_map_t *sm)
480 {
481         return (B_TRUE);
482 }
483
484 static space_map_ops_t metaslab_ff_ops = {
485         metaslab_pp_load,
486         metaslab_pp_unload,
487         metaslab_ff_alloc,
488         metaslab_pp_claim,
489         metaslab_pp_free,
490         metaslab_pp_maxsize,
491         metaslab_ff_fragmented
492 };
493
494 space_map_ops_t *zfs_metaslab_ops = &metaslab_ff_ops;
495 #endif /* WITH_FF_BLOCK_ALLOCATOR */
496
497 #if defined(WITH_DF_BLOCK_ALLOCATOR)
498 /*
499  * ==========================================================================
500  * Dynamic block allocator -
501  * Uses the first fit allocation scheme until space get low and then
502  * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
503  * and metaslab_df_free_pct to determine when to switch the allocation scheme.
504  * ==========================================================================
505  */
506 static uint64_t
507 metaslab_df_alloc(space_map_t *sm, uint64_t size)
508 {
509         avl_tree_t *t = &sm->sm_root;
510         uint64_t align = size & -size;
511         uint64_t *cursor = (uint64_t *)sm->sm_ppd + highbit(align) - 1;
512         uint64_t max_size = metaslab_pp_maxsize(sm);
513         int free_pct = sm->sm_space * 100 / sm->sm_size;
514
515         ASSERT(MUTEX_HELD(sm->sm_lock));
516         ASSERT3U(avl_numnodes(&sm->sm_root), ==, avl_numnodes(sm->sm_pp_root));
517
518         if (max_size < size)
519                 return (-1ULL);
520
521         /*
522          * If we're running low on space switch to using the size
523          * sorted AVL tree (best-fit).
524          */
525         if (max_size < metaslab_df_alloc_threshold ||
526             free_pct < metaslab_df_free_pct) {
527                 t = sm->sm_pp_root;
528                 *cursor = 0;
529         }
530
531         return (metaslab_block_picker(t, cursor, size, 1ULL));
532 }
533
534 static boolean_t
535 metaslab_df_fragmented(space_map_t *sm)
536 {
537         uint64_t max_size = metaslab_pp_maxsize(sm);
538         int free_pct = sm->sm_space * 100 / sm->sm_size;
539
540         if (max_size >= metaslab_df_alloc_threshold &&
541             free_pct >= metaslab_df_free_pct)
542                 return (B_FALSE);
543
544         return (B_TRUE);
545 }
546
547 static space_map_ops_t metaslab_df_ops = {
548         metaslab_pp_load,
549         metaslab_pp_unload,
550         metaslab_df_alloc,
551         metaslab_pp_claim,
552         metaslab_pp_free,
553         metaslab_pp_maxsize,
554         metaslab_df_fragmented
555 };
556
557 space_map_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
558 #endif /* WITH_DF_BLOCK_ALLOCATOR */
559
560 /*
561  * ==========================================================================
562  * Other experimental allocators
563  * ==========================================================================
564  */
565 #if defined(WITH_CDF_BLOCK_ALLOCATOR)
566 static uint64_t
567 metaslab_cdf_alloc(space_map_t *sm, uint64_t size)
568 {
569         avl_tree_t *t = &sm->sm_root;
570         uint64_t *cursor = (uint64_t *)sm->sm_ppd;
571         uint64_t *extent_end = (uint64_t *)sm->sm_ppd + 1;
572         uint64_t max_size = metaslab_pp_maxsize(sm);
573         uint64_t rsize = size;
574         uint64_t offset = 0;
575
576         ASSERT(MUTEX_HELD(sm->sm_lock));
577         ASSERT3U(avl_numnodes(&sm->sm_root), ==, avl_numnodes(sm->sm_pp_root));
578
579         if (max_size < size)
580                 return (-1ULL);
581
582         ASSERT3U(*extent_end, >=, *cursor);
583
584         /*
585          * If we're running low on space switch to using the size
586          * sorted AVL tree (best-fit).
587          */
588         if ((*cursor + size) > *extent_end) {
589
590                 t = sm->sm_pp_root;
591                 *cursor = *extent_end = 0;
592
593                 if (max_size > 2 * SPA_MAXBLOCKSIZE)
594                         rsize = MIN(metaslab_min_alloc_size, max_size);
595                 offset = metaslab_block_picker(t, extent_end, rsize, 1ULL);
596                 if (offset != -1)
597                         *cursor = offset + size;
598         } else {
599                 offset = metaslab_block_picker(t, cursor, rsize, 1ULL);
600         }
601         ASSERT3U(*cursor, <=, *extent_end);
602         return (offset);
603 }
604
605 static boolean_t
606 metaslab_cdf_fragmented(space_map_t *sm)
607 {
608         uint64_t max_size = metaslab_pp_maxsize(sm);
609
610         if (max_size > (metaslab_min_alloc_size * 10))
611                 return (B_FALSE);
612         return (B_TRUE);
613 }
614
615 static space_map_ops_t metaslab_cdf_ops = {
616         metaslab_pp_load,
617         metaslab_pp_unload,
618         metaslab_cdf_alloc,
619         metaslab_pp_claim,
620         metaslab_pp_free,
621         metaslab_pp_maxsize,
622         metaslab_cdf_fragmented
623 };
624
625 space_map_ops_t *zfs_metaslab_ops = &metaslab_cdf_ops;
626 #endif /* WITH_CDF_BLOCK_ALLOCATOR */
627
628 #if defined(WITH_NDF_BLOCK_ALLOCATOR)
629 uint64_t metaslab_ndf_clump_shift = 4;
630
631 static uint64_t
632 metaslab_ndf_alloc(space_map_t *sm, uint64_t size)
633 {
634         avl_tree_t *t = &sm->sm_root;
635         avl_index_t where;
636         space_seg_t *ss, ssearch;
637         uint64_t hbit = highbit(size);
638         uint64_t *cursor = (uint64_t *)sm->sm_ppd + hbit - 1;
639         uint64_t max_size = metaslab_pp_maxsize(sm);
640
641         ASSERT(MUTEX_HELD(sm->sm_lock));
642         ASSERT3U(avl_numnodes(&sm->sm_root), ==, avl_numnodes(sm->sm_pp_root));
643
644         if (max_size < size)
645                 return (-1ULL);
646
647         ssearch.ss_start = *cursor;
648         ssearch.ss_end = *cursor + size;
649
650         ss = avl_find(t, &ssearch, &where);
651         if (ss == NULL || (ss->ss_start + size > ss->ss_end)) {
652                 t = sm->sm_pp_root;
653
654                 ssearch.ss_start = 0;
655                 ssearch.ss_end = MIN(max_size,
656                     1ULL << (hbit + metaslab_ndf_clump_shift));
657                 ss = avl_find(t, &ssearch, &where);
658                 if (ss == NULL)
659                         ss = avl_nearest(t, where, AVL_AFTER);
660                 ASSERT(ss != NULL);
661         }
662
663         if (ss != NULL) {
664                 if (ss->ss_start + size <= ss->ss_end) {
665                         *cursor = ss->ss_start + size;
666                         return (ss->ss_start);
667                 }
668         }
669         return (-1ULL);
670 }
671
672 static boolean_t
673 metaslab_ndf_fragmented(space_map_t *sm)
674 {
675         uint64_t max_size = metaslab_pp_maxsize(sm);
676
677         if (max_size > (metaslab_min_alloc_size << metaslab_ndf_clump_shift))
678                 return (B_FALSE);
679         return (B_TRUE);
680 }
681
682
683 static space_map_ops_t metaslab_ndf_ops = {
684         metaslab_pp_load,
685         metaslab_pp_unload,
686         metaslab_ndf_alloc,
687         metaslab_pp_claim,
688         metaslab_pp_free,
689         metaslab_pp_maxsize,
690         metaslab_ndf_fragmented
691 };
692
693 space_map_ops_t *zfs_metaslab_ops = &metaslab_ndf_ops;
694 #endif /* WITH_NDF_BLOCK_ALLOCATOR */
695
696 /*
697  * ==========================================================================
698  * Metaslabs
699  * ==========================================================================
700  */
701 metaslab_t *
702 metaslab_init(metaslab_group_t *mg, space_map_obj_t *smo,
703         uint64_t start, uint64_t size, uint64_t txg)
704 {
705         vdev_t *vd = mg->mg_vd;
706         metaslab_t *msp;
707
708         msp = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
709         mutex_init(&msp->ms_lock, NULL, MUTEX_DEFAULT, NULL);
710
711         msp->ms_smo_syncing = *smo;
712
713         /*
714          * We create the main space map here, but we don't create the
715          * allocmaps and freemaps until metaslab_sync_done().  This serves
716          * two purposes: it allows metaslab_sync_done() to detect the
717          * addition of new space; and for debugging, it ensures that we'd
718          * data fault on any attempt to use this metaslab before it's ready.
719          */
720         space_map_create(&msp->ms_map, start, size,
721             vd->vdev_ashift, &msp->ms_lock);
722
723         metaslab_group_add(mg, msp);
724
725         if (metaslab_debug && smo->smo_object != 0) {
726                 mutex_enter(&msp->ms_lock);
727                 VERIFY(space_map_load(&msp->ms_map, mg->mg_class->mc_ops,
728                     SM_FREE, smo, spa_meta_objset(vd->vdev_spa)) == 0);
729                 mutex_exit(&msp->ms_lock);
730         }
731
732         /*
733          * If we're opening an existing pool (txg == 0) or creating
734          * a new one (txg == TXG_INITIAL), all space is available now.
735          * If we're adding space to an existing pool, the new space
736          * does not become available until after this txg has synced.
737          */
738         if (txg <= TXG_INITIAL)
739                 metaslab_sync_done(msp, 0);
740
741         if (txg != 0) {
742                 vdev_dirty(vd, 0, NULL, txg);
743                 vdev_dirty(vd, VDD_METASLAB, msp, txg);
744         }
745
746         return (msp);
747 }
748
749 void
750 metaslab_fini(metaslab_t *msp)
751 {
752         metaslab_group_t *mg = msp->ms_group;
753         int t;
754
755         vdev_space_update(mg->mg_vd,
756             -msp->ms_smo.smo_alloc, 0, -msp->ms_map.sm_size);
757
758         metaslab_group_remove(mg, msp);
759
760         mutex_enter(&msp->ms_lock);
761
762         space_map_unload(&msp->ms_map);
763         space_map_destroy(&msp->ms_map);
764
765         for (t = 0; t < TXG_SIZE; t++) {
766                 space_map_destroy(&msp->ms_allocmap[t]);
767                 space_map_destroy(&msp->ms_freemap[t]);
768         }
769
770         for (t = 0; t < TXG_DEFER_SIZE; t++)
771                 space_map_destroy(&msp->ms_defermap[t]);
772
773         ASSERT3S(msp->ms_deferspace, ==, 0);
774
775         mutex_exit(&msp->ms_lock);
776         mutex_destroy(&msp->ms_lock);
777
778         kmem_free(msp, sizeof (metaslab_t));
779 }
780
781 #define METASLAB_WEIGHT_PRIMARY         (1ULL << 63)
782 #define METASLAB_WEIGHT_SECONDARY       (1ULL << 62)
783 #define METASLAB_ACTIVE_MASK            \
784         (METASLAB_WEIGHT_PRIMARY | METASLAB_WEIGHT_SECONDARY)
785
786 static uint64_t
787 metaslab_weight(metaslab_t *msp)
788 {
789         metaslab_group_t *mg = msp->ms_group;
790         space_map_t *sm = &msp->ms_map;
791         space_map_obj_t *smo = &msp->ms_smo;
792         vdev_t *vd = mg->mg_vd;
793         uint64_t weight, space;
794
795         ASSERT(MUTEX_HELD(&msp->ms_lock));
796
797         /*
798          * The baseline weight is the metaslab's free space.
799          */
800         space = sm->sm_size - smo->smo_alloc;
801         weight = space;
802
803         /*
804          * Modern disks have uniform bit density and constant angular velocity.
805          * Therefore, the outer recording zones are faster (higher bandwidth)
806          * than the inner zones by the ratio of outer to inner track diameter,
807          * which is typically around 2:1.  We account for this by assigning
808          * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
809          * In effect, this means that we'll select the metaslab with the most
810          * free bandwidth rather than simply the one with the most free space.
811          */
812         weight = 2 * weight -
813             ((sm->sm_start >> vd->vdev_ms_shift) * weight) / vd->vdev_ms_count;
814         ASSERT(weight >= space && weight <= 2 * space);
815
816         /*
817          * For locality, assign higher weight to metaslabs which have
818          * a lower offset than what we've already activated.
819          */
820         if (sm->sm_start <= mg->mg_bonus_area)
821                 weight *= (metaslab_smo_bonus_pct / 100);
822         ASSERT(weight >= space &&
823             weight <= 2 * (metaslab_smo_bonus_pct / 100) * space);
824
825         if (sm->sm_loaded && !sm->sm_ops->smop_fragmented(sm)) {
826                 /*
827                  * If this metaslab is one we're actively using, adjust its
828                  * weight to make it preferable to any inactive metaslab so
829                  * we'll polish it off.
830                  */
831                 weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
832         }
833         return (weight);
834 }
835
836 static void
837 metaslab_prefetch(metaslab_group_t *mg)
838 {
839         spa_t *spa = mg->mg_vd->vdev_spa;
840         metaslab_t *msp;
841         avl_tree_t *t = &mg->mg_metaslab_tree;
842         int m;
843
844         mutex_enter(&mg->mg_lock);
845
846         /*
847          * Prefetch the next potential metaslabs
848          */
849         for (msp = avl_first(t), m = 0; msp; msp = AVL_NEXT(t, msp), m++) {
850                 space_map_t *sm = &msp->ms_map;
851                 space_map_obj_t *smo = &msp->ms_smo;
852
853                 /* If we have reached our prefetch limit then we're done */
854                 if (m >= metaslab_prefetch_limit)
855                         break;
856
857                 if (!sm->sm_loaded && smo->smo_object != 0) {
858                         mutex_exit(&mg->mg_lock);
859                         dmu_prefetch(spa_meta_objset(spa), smo->smo_object,
860                             0ULL, smo->smo_objsize);
861                         mutex_enter(&mg->mg_lock);
862                 }
863         }
864         mutex_exit(&mg->mg_lock);
865 }
866
867 static int
868 metaslab_activate(metaslab_t *msp, uint64_t activation_weight, uint64_t size)
869 {
870         metaslab_group_t *mg = msp->ms_group;
871         space_map_t *sm = &msp->ms_map;
872         space_map_ops_t *sm_ops = msp->ms_group->mg_class->mc_ops;
873         int t;
874
875         ASSERT(MUTEX_HELD(&msp->ms_lock));
876
877         if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
878                 space_map_load_wait(sm);
879                 if (!sm->sm_loaded) {
880                         int error = space_map_load(sm, sm_ops, SM_FREE,
881                             &msp->ms_smo,
882                             spa_meta_objset(msp->ms_group->mg_vd->vdev_spa));
883                         if (error)  {
884                                 metaslab_group_sort(msp->ms_group, msp, 0);
885                                 return (error);
886                         }
887                         for (t = 0; t < TXG_DEFER_SIZE; t++)
888                                 space_map_walk(&msp->ms_defermap[t],
889                                     space_map_claim, sm);
890
891                 }
892
893                 /*
894                  * Track the bonus area as we activate new metaslabs.
895                  */
896                 if (sm->sm_start > mg->mg_bonus_area) {
897                         mutex_enter(&mg->mg_lock);
898                         mg->mg_bonus_area = sm->sm_start;
899                         mutex_exit(&mg->mg_lock);
900                 }
901
902                 /*
903                  * If we were able to load the map then make sure
904                  * that this map is still able to satisfy our request.
905                  */
906                 if (msp->ms_weight < size)
907                         return (ENOSPC);
908
909                 metaslab_group_sort(msp->ms_group, msp,
910                     msp->ms_weight | activation_weight);
911         }
912         ASSERT(sm->sm_loaded);
913         ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
914
915         return (0);
916 }
917
918 static void
919 metaslab_passivate(metaslab_t *msp, uint64_t size)
920 {
921         /*
922          * If size < SPA_MINBLOCKSIZE, then we will not allocate from
923          * this metaslab again.  In that case, it had better be empty,
924          * or we would be leaving space on the table.
925          */
926         ASSERT(size >= SPA_MINBLOCKSIZE || msp->ms_map.sm_space == 0);
927         metaslab_group_sort(msp->ms_group, msp, MIN(msp->ms_weight, size));
928         ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
929 }
930
931 /*
932  * Write a metaslab to disk in the context of the specified transaction group.
933  */
934 void
935 metaslab_sync(metaslab_t *msp, uint64_t txg)
936 {
937         vdev_t *vd = msp->ms_group->mg_vd;
938         spa_t *spa = vd->vdev_spa;
939         objset_t *mos = spa_meta_objset(spa);
940         space_map_t *allocmap = &msp->ms_allocmap[txg & TXG_MASK];
941         space_map_t *freemap = &msp->ms_freemap[txg & TXG_MASK];
942         space_map_t *freed_map = &msp->ms_freemap[TXG_CLEAN(txg) & TXG_MASK];
943         space_map_t *sm = &msp->ms_map;
944         space_map_obj_t *smo = &msp->ms_smo_syncing;
945         dmu_buf_t *db;
946         dmu_tx_t *tx;
947         int t;
948
949         ASSERT(!vd->vdev_ishole);
950
951         if (allocmap->sm_space == 0 && freemap->sm_space == 0)
952                 return;
953
954         /*
955          * The only state that can actually be changing concurrently with
956          * metaslab_sync() is the metaslab's ms_map.  No other thread can
957          * be modifying this txg's allocmap, freemap, freed_map, or smo.
958          * Therefore, we only hold ms_lock to satify space_map ASSERTs.
959          * We drop it whenever we call into the DMU, because the DMU
960          * can call down to us (e.g. via zio_free()) at any time.
961          */
962
963         tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
964
965         if (smo->smo_object == 0) {
966                 ASSERT(smo->smo_objsize == 0);
967                 ASSERT(smo->smo_alloc == 0);
968                 smo->smo_object = dmu_object_alloc(mos,
969                     DMU_OT_SPACE_MAP, 1 << SPACE_MAP_BLOCKSHIFT,
970                     DMU_OT_SPACE_MAP_HEADER, sizeof (*smo), tx);
971                 ASSERT(smo->smo_object != 0);
972                 dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
973                     (sm->sm_start >> vd->vdev_ms_shift),
974                     sizeof (uint64_t), &smo->smo_object, tx);
975         }
976
977         mutex_enter(&msp->ms_lock);
978
979         space_map_walk(freemap, space_map_add, freed_map);
980
981         if (sm->sm_loaded && spa_sync_pass(spa) == 1 && smo->smo_objsize >=
982             2 * sizeof (uint64_t) * avl_numnodes(&sm->sm_root)) {
983                 /*
984                  * The in-core space map representation is twice as compact
985                  * as the on-disk one, so it's time to condense the latter
986                  * by generating a pure allocmap from first principles.
987                  *
988                  * This metaslab is 100% allocated,
989                  * minus the content of the in-core map (sm),
990                  * minus what's been freed this txg (freed_map),
991                  * minus deferred frees (ms_defermap[]),
992                  * minus allocations from txgs in the future
993                  * (because they haven't been committed yet).
994                  */
995                 space_map_vacate(allocmap, NULL, NULL);
996                 space_map_vacate(freemap, NULL, NULL);
997
998                 space_map_add(allocmap, allocmap->sm_start, allocmap->sm_size);
999
1000                 space_map_walk(sm, space_map_remove, allocmap);
1001                 space_map_walk(freed_map, space_map_remove, allocmap);
1002
1003                 for (t = 0; t < TXG_DEFER_SIZE; t++)
1004                         space_map_walk(&msp->ms_defermap[t],
1005                             space_map_remove, allocmap);
1006
1007                 for (t = 1; t < TXG_CONCURRENT_STATES; t++)
1008                         space_map_walk(&msp->ms_allocmap[(txg + t) & TXG_MASK],
1009                             space_map_remove, allocmap);
1010
1011                 mutex_exit(&msp->ms_lock);
1012                 space_map_truncate(smo, mos, tx);
1013                 mutex_enter(&msp->ms_lock);
1014         }
1015
1016         space_map_sync(allocmap, SM_ALLOC, smo, mos, tx);
1017         space_map_sync(freemap, SM_FREE, smo, mos, tx);
1018
1019         mutex_exit(&msp->ms_lock);
1020
1021         VERIFY(0 == dmu_bonus_hold(mos, smo->smo_object, FTAG, &db));
1022         dmu_buf_will_dirty(db, tx);
1023         ASSERT3U(db->db_size, >=, sizeof (*smo));
1024         bcopy(smo, db->db_data, sizeof (*smo));
1025         dmu_buf_rele(db, FTAG);
1026
1027         dmu_tx_commit(tx);
1028 }
1029
1030 /*
1031  * Called after a transaction group has completely synced to mark
1032  * all of the metaslab's free space as usable.
1033  */
1034 void
1035 metaslab_sync_done(metaslab_t *msp, uint64_t txg)
1036 {
1037         space_map_obj_t *smo = &msp->ms_smo;
1038         space_map_obj_t *smosync = &msp->ms_smo_syncing;
1039         space_map_t *sm = &msp->ms_map;
1040         space_map_t *freed_map = &msp->ms_freemap[TXG_CLEAN(txg) & TXG_MASK];
1041         space_map_t *defer_map = &msp->ms_defermap[txg % TXG_DEFER_SIZE];
1042         metaslab_group_t *mg = msp->ms_group;
1043         vdev_t *vd = mg->mg_vd;
1044         int64_t alloc_delta, defer_delta;
1045         int t;
1046
1047         ASSERT(!vd->vdev_ishole);
1048
1049         mutex_enter(&msp->ms_lock);
1050
1051         /*
1052          * If this metaslab is just becoming available, initialize its
1053          * allocmaps and freemaps and add its capacity to the vdev.
1054          */
1055         if (freed_map->sm_size == 0) {
1056                 for (t = 0; t < TXG_SIZE; t++) {
1057                         space_map_create(&msp->ms_allocmap[t], sm->sm_start,
1058                             sm->sm_size, sm->sm_shift, sm->sm_lock);
1059                         space_map_create(&msp->ms_freemap[t], sm->sm_start,
1060                             sm->sm_size, sm->sm_shift, sm->sm_lock);
1061                 }
1062
1063                 for (t = 0; t < TXG_DEFER_SIZE; t++)
1064                         space_map_create(&msp->ms_defermap[t], sm->sm_start,
1065                             sm->sm_size, sm->sm_shift, sm->sm_lock);
1066
1067                 vdev_space_update(vd, 0, 0, sm->sm_size);
1068         }
1069
1070         alloc_delta = smosync->smo_alloc - smo->smo_alloc;
1071         defer_delta = freed_map->sm_space - defer_map->sm_space;
1072
1073         vdev_space_update(vd, alloc_delta + defer_delta, defer_delta, 0);
1074
1075         ASSERT(msp->ms_allocmap[txg & TXG_MASK].sm_space == 0);
1076         ASSERT(msp->ms_freemap[txg & TXG_MASK].sm_space == 0);
1077
1078         /*
1079          * If there's a space_map_load() in progress, wait for it to complete
1080          * so that we have a consistent view of the in-core space map.
1081          * Then, add defer_map (oldest deferred frees) to this map and
1082          * transfer freed_map (this txg's frees) to defer_map.
1083          */
1084         space_map_load_wait(sm);
1085         space_map_vacate(defer_map, sm->sm_loaded ? space_map_free : NULL, sm);
1086         space_map_vacate(freed_map, space_map_add, defer_map);
1087
1088         *smo = *smosync;
1089
1090         msp->ms_deferspace += defer_delta;
1091         ASSERT3S(msp->ms_deferspace, >=, 0);
1092         ASSERT3S(msp->ms_deferspace, <=, sm->sm_size);
1093         if (msp->ms_deferspace != 0) {
1094                 /*
1095                  * Keep syncing this metaslab until all deferred frees
1096                  * are back in circulation.
1097                  */
1098                 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
1099         }
1100
1101         /*
1102          * If the map is loaded but no longer active, evict it as soon as all
1103          * future allocations have synced.  (If we unloaded it now and then
1104          * loaded a moment later, the map wouldn't reflect those allocations.)
1105          */
1106         if (sm->sm_loaded && (msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
1107                 int evictable = 1;
1108
1109                 for (t = 1; t < TXG_CONCURRENT_STATES; t++)
1110                         if (msp->ms_allocmap[(txg + t) & TXG_MASK].sm_space)
1111                                 evictable = 0;
1112
1113                 if (evictable && !metaslab_debug)
1114                         space_map_unload(sm);
1115         }
1116
1117         metaslab_group_sort(mg, msp, metaslab_weight(msp));
1118
1119         mutex_exit(&msp->ms_lock);
1120 }
1121
1122 void
1123 metaslab_sync_reassess(metaslab_group_t *mg)
1124 {
1125         vdev_t *vd = mg->mg_vd;
1126         int m;
1127
1128         /*
1129          * Re-evaluate all metaslabs which have lower offsets than the
1130          * bonus area.
1131          */
1132         for (m = 0; m < vd->vdev_ms_count; m++) {
1133                 metaslab_t *msp = vd->vdev_ms[m];
1134
1135                 if (msp->ms_map.sm_start > mg->mg_bonus_area)
1136                         break;
1137
1138                 mutex_enter(&msp->ms_lock);
1139                 metaslab_group_sort(mg, msp, metaslab_weight(msp));
1140                 mutex_exit(&msp->ms_lock);
1141         }
1142
1143         /*
1144          * Prefetch the next potential metaslabs
1145          */
1146         metaslab_prefetch(mg);
1147 }
1148
1149 static uint64_t
1150 metaslab_distance(metaslab_t *msp, dva_t *dva)
1151 {
1152         uint64_t ms_shift = msp->ms_group->mg_vd->vdev_ms_shift;
1153         uint64_t offset = DVA_GET_OFFSET(dva) >> ms_shift;
1154         uint64_t start = msp->ms_map.sm_start >> ms_shift;
1155
1156         if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
1157                 return (1ULL << 63);
1158
1159         if (offset < start)
1160                 return ((start - offset) << ms_shift);
1161         if (offset > start)
1162                 return ((offset - start) << ms_shift);
1163         return (0);
1164 }
1165
1166 static uint64_t
1167 metaslab_group_alloc(metaslab_group_t *mg, uint64_t size, uint64_t txg,
1168     uint64_t min_distance, dva_t *dva, int d)
1169 {
1170         metaslab_t *msp = NULL;
1171         uint64_t offset = -1ULL;
1172         avl_tree_t *t = &mg->mg_metaslab_tree;
1173         uint64_t activation_weight;
1174         uint64_t target_distance;
1175         int i;
1176
1177         activation_weight = METASLAB_WEIGHT_PRIMARY;
1178         for (i = 0; i < d; i++) {
1179                 if (DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
1180                         activation_weight = METASLAB_WEIGHT_SECONDARY;
1181                         break;
1182                 }
1183         }
1184
1185         for (;;) {
1186                 boolean_t was_active;
1187
1188                 mutex_enter(&mg->mg_lock);
1189                 for (msp = avl_first(t); msp; msp = AVL_NEXT(t, msp)) {
1190                         if (msp->ms_weight < size) {
1191                                 mutex_exit(&mg->mg_lock);
1192                                 return (-1ULL);
1193                         }
1194
1195                         was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
1196                         if (activation_weight == METASLAB_WEIGHT_PRIMARY)
1197                                 break;
1198
1199                         target_distance = min_distance +
1200                             (msp->ms_smo.smo_alloc ? 0 : min_distance >> 1);
1201
1202                         for (i = 0; i < d; i++)
1203                                 if (metaslab_distance(msp, &dva[i]) <
1204                                     target_distance)
1205                                         break;
1206                         if (i == d)
1207                                 break;
1208                 }
1209                 mutex_exit(&mg->mg_lock);
1210                 if (msp == NULL)
1211                         return (-1ULL);
1212
1213                 mutex_enter(&msp->ms_lock);
1214
1215                 /*
1216                  * Ensure that the metaslab we have selected is still
1217                  * capable of handling our request. It's possible that
1218                  * another thread may have changed the weight while we
1219                  * were blocked on the metaslab lock.
1220                  */
1221                 if (msp->ms_weight < size || (was_active &&
1222                     !(msp->ms_weight & METASLAB_ACTIVE_MASK) &&
1223                     activation_weight == METASLAB_WEIGHT_PRIMARY)) {
1224                         mutex_exit(&msp->ms_lock);
1225                         continue;
1226                 }
1227
1228                 if ((msp->ms_weight & METASLAB_WEIGHT_SECONDARY) &&
1229                     activation_weight == METASLAB_WEIGHT_PRIMARY) {
1230                         metaslab_passivate(msp,
1231                             msp->ms_weight & ~METASLAB_ACTIVE_MASK);
1232                         mutex_exit(&msp->ms_lock);
1233                         continue;
1234                 }
1235
1236                 if (metaslab_activate(msp, activation_weight, size) != 0) {
1237                         mutex_exit(&msp->ms_lock);
1238                         continue;
1239                 }
1240
1241                 if ((offset = space_map_alloc(&msp->ms_map, size)) != -1ULL)
1242                         break;
1243
1244                 metaslab_passivate(msp, space_map_maxsize(&msp->ms_map));
1245
1246                 mutex_exit(&msp->ms_lock);
1247         }
1248
1249         if (msp->ms_allocmap[txg & TXG_MASK].sm_space == 0)
1250                 vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
1251
1252         space_map_add(&msp->ms_allocmap[txg & TXG_MASK], offset, size);
1253
1254         mutex_exit(&msp->ms_lock);
1255
1256         return (offset);
1257 }
1258
1259 /*
1260  * Allocate a block for the specified i/o.
1261  */
1262 static int
1263 metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
1264     dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags)
1265 {
1266         metaslab_group_t *mg, *rotor;
1267         vdev_t *vd;
1268         int dshift = 3;
1269         int all_zero;
1270         int zio_lock = B_FALSE;
1271         boolean_t allocatable;
1272         uint64_t offset = -1ULL;
1273         uint64_t asize;
1274         uint64_t distance;
1275
1276         ASSERT(!DVA_IS_VALID(&dva[d]));
1277
1278         /*
1279          * For testing, make some blocks above a certain size be gang blocks.
1280          */
1281         if (psize >= metaslab_gang_bang && (ddi_get_lbolt() & 3) == 0)
1282                 return (ENOSPC);
1283
1284         /*
1285          * Start at the rotor and loop through all mgs until we find something.
1286          * Note that there's no locking on mc_rotor or mc_aliquot because
1287          * nothing actually breaks if we miss a few updates -- we just won't
1288          * allocate quite as evenly.  It all balances out over time.
1289          *
1290          * If we are doing ditto or log blocks, try to spread them across
1291          * consecutive vdevs.  If we're forced to reuse a vdev before we've
1292          * allocated all of our ditto blocks, then try and spread them out on
1293          * that vdev as much as possible.  If it turns out to not be possible,
1294          * gradually lower our standards until anything becomes acceptable.
1295          * Also, allocating on consecutive vdevs (as opposed to random vdevs)
1296          * gives us hope of containing our fault domains to something we're
1297          * able to reason about.  Otherwise, any two top-level vdev failures
1298          * will guarantee the loss of data.  With consecutive allocation,
1299          * only two adjacent top-level vdev failures will result in data loss.
1300          *
1301          * If we are doing gang blocks (hintdva is non-NULL), try to keep
1302          * ourselves on the same vdev as our gang block header.  That
1303          * way, we can hope for locality in vdev_cache, plus it makes our
1304          * fault domains something tractable.
1305          */
1306         if (hintdva) {
1307                 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
1308
1309                 /*
1310                  * It's possible the vdev we're using as the hint no
1311                  * longer exists (i.e. removed). Consult the rotor when
1312                  * all else fails.
1313                  */
1314                 if (vd != NULL) {
1315                         mg = vd->vdev_mg;
1316
1317                         if (flags & METASLAB_HINTBP_AVOID &&
1318                             mg->mg_next != NULL)
1319                                 mg = mg->mg_next;
1320                 } else {
1321                         mg = mc->mc_rotor;
1322                 }
1323         } else if (d != 0) {
1324                 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
1325                 mg = vd->vdev_mg->mg_next;
1326         } else {
1327                 mg = mc->mc_rotor;
1328         }
1329
1330         /*
1331          * If the hint put us into the wrong metaslab class, or into a
1332          * metaslab group that has been passivated, just follow the rotor.
1333          */
1334         if (mg->mg_class != mc || mg->mg_activation_count <= 0)
1335                 mg = mc->mc_rotor;
1336
1337         rotor = mg;
1338 top:
1339         all_zero = B_TRUE;
1340         do {
1341                 ASSERT(mg->mg_activation_count == 1);
1342
1343                 vd = mg->mg_vd;
1344
1345                 /*
1346                  * Don't allocate from faulted devices.
1347                  */
1348                 if (zio_lock) {
1349                         spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
1350                         allocatable = vdev_allocatable(vd);
1351                         spa_config_exit(spa, SCL_ZIO, FTAG);
1352                 } else {
1353                         allocatable = vdev_allocatable(vd);
1354                 }
1355                 if (!allocatable)
1356                         goto next;
1357
1358                 /*
1359                  * Avoid writing single-copy data to a failing vdev
1360                  */
1361                 if ((vd->vdev_stat.vs_write_errors > 0 ||
1362                     vd->vdev_state < VDEV_STATE_HEALTHY) &&
1363                     d == 0 && dshift == 3) {
1364                         all_zero = B_FALSE;
1365                         goto next;
1366                 }
1367
1368                 ASSERT(mg->mg_class == mc);
1369
1370                 distance = vd->vdev_asize >> dshift;
1371                 if (distance <= (1ULL << vd->vdev_ms_shift))
1372                         distance = 0;
1373                 else
1374                         all_zero = B_FALSE;
1375
1376                 asize = vdev_psize_to_asize(vd, psize);
1377                 ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
1378
1379                 offset = metaslab_group_alloc(mg, asize, txg, distance, dva, d);
1380                 if (offset != -1ULL) {
1381                         /*
1382                          * If we've just selected this metaslab group,
1383                          * figure out whether the corresponding vdev is
1384                          * over- or under-used relative to the pool,
1385                          * and set an allocation bias to even it out.
1386                          */
1387                         if (mc->mc_aliquot == 0) {
1388                                 vdev_stat_t *vs = &vd->vdev_stat;
1389                                 int64_t vu, cu;
1390
1391                                 /*
1392                                  * Determine percent used in units of 0..1024.
1393                                  * (This is just to avoid floating point.)
1394                                  */
1395                                 vu = (vs->vs_alloc << 10) / (vs->vs_space + 1);
1396                                 cu = (mc->mc_alloc << 10) / (mc->mc_space + 1);
1397
1398                                 /*
1399                                  * Bias by at most +/- 25% of the aliquot.
1400                                  */
1401                                 mg->mg_bias = ((cu - vu) *
1402                                     (int64_t)mg->mg_aliquot) / (1024 * 4);
1403                         }
1404
1405                         if (atomic_add_64_nv(&mc->mc_aliquot, asize) >=
1406                             mg->mg_aliquot + mg->mg_bias) {
1407                                 mc->mc_rotor = mg->mg_next;
1408                                 mc->mc_aliquot = 0;
1409                         }
1410
1411                         DVA_SET_VDEV(&dva[d], vd->vdev_id);
1412                         DVA_SET_OFFSET(&dva[d], offset);
1413                         DVA_SET_GANG(&dva[d], !!(flags & METASLAB_GANG_HEADER));
1414                         DVA_SET_ASIZE(&dva[d], asize);
1415
1416                         return (0);
1417                 }
1418 next:
1419                 mc->mc_rotor = mg->mg_next;
1420                 mc->mc_aliquot = 0;
1421         } while ((mg = mg->mg_next) != rotor);
1422
1423         if (!all_zero) {
1424                 dshift++;
1425                 ASSERT(dshift < 64);
1426                 goto top;
1427         }
1428
1429         if (!allocatable && !zio_lock) {
1430                 dshift = 3;
1431                 zio_lock = B_TRUE;
1432                 goto top;
1433         }
1434
1435         bzero(&dva[d], sizeof (dva_t));
1436
1437         return (ENOSPC);
1438 }
1439
1440 /*
1441  * Free the block represented by DVA in the context of the specified
1442  * transaction group.
1443  */
1444 static void
1445 metaslab_free_dva(spa_t *spa, const dva_t *dva, uint64_t txg, boolean_t now)
1446 {
1447         uint64_t vdev = DVA_GET_VDEV(dva);
1448         uint64_t offset = DVA_GET_OFFSET(dva);
1449         uint64_t size = DVA_GET_ASIZE(dva);
1450         vdev_t *vd;
1451         metaslab_t *msp;
1452
1453         ASSERT(DVA_IS_VALID(dva));
1454
1455         if (txg > spa_freeze_txg(spa))
1456                 return;
1457
1458         if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
1459             (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
1460                 cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
1461                     (u_longlong_t)vdev, (u_longlong_t)offset);
1462                 ASSERT(0);
1463                 return;
1464         }
1465
1466         msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1467
1468         if (DVA_GET_GANG(dva))
1469                 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1470
1471         mutex_enter(&msp->ms_lock);
1472
1473         if (now) {
1474                 space_map_remove(&msp->ms_allocmap[txg & TXG_MASK],
1475                     offset, size);
1476                 space_map_free(&msp->ms_map, offset, size);
1477         } else {
1478                 if (msp->ms_freemap[txg & TXG_MASK].sm_space == 0)
1479                         vdev_dirty(vd, VDD_METASLAB, msp, txg);
1480                 space_map_add(&msp->ms_freemap[txg & TXG_MASK], offset, size);
1481         }
1482
1483         mutex_exit(&msp->ms_lock);
1484 }
1485
1486 /*
1487  * Intent log support: upon opening the pool after a crash, notify the SPA
1488  * of blocks that the intent log has allocated for immediate write, but
1489  * which are still considered free by the SPA because the last transaction
1490  * group didn't commit yet.
1491  */
1492 static int
1493 metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
1494 {
1495         uint64_t vdev = DVA_GET_VDEV(dva);
1496         uint64_t offset = DVA_GET_OFFSET(dva);
1497         uint64_t size = DVA_GET_ASIZE(dva);
1498         vdev_t *vd;
1499         metaslab_t *msp;
1500         int error = 0;
1501
1502         ASSERT(DVA_IS_VALID(dva));
1503
1504         if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
1505             (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
1506                 return (ENXIO);
1507
1508         msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
1509
1510         if (DVA_GET_GANG(dva))
1511                 size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
1512
1513         mutex_enter(&msp->ms_lock);
1514
1515         if ((txg != 0 && spa_writeable(spa)) || !msp->ms_map.sm_loaded)
1516                 error = metaslab_activate(msp, METASLAB_WEIGHT_SECONDARY, 0);
1517
1518         if (error == 0 && !space_map_contains(&msp->ms_map, offset, size))
1519                 error = ENOENT;
1520
1521         if (error || txg == 0) {        /* txg == 0 indicates dry run */
1522                 mutex_exit(&msp->ms_lock);
1523                 return (error);
1524         }
1525
1526         space_map_claim(&msp->ms_map, offset, size);
1527
1528         if (spa_writeable(spa)) {       /* don't dirty if we're zdb(1M) */
1529                 if (msp->ms_allocmap[txg & TXG_MASK].sm_space == 0)
1530                         vdev_dirty(vd, VDD_METASLAB, msp, txg);
1531                 space_map_add(&msp->ms_allocmap[txg & TXG_MASK], offset, size);
1532         }
1533
1534         mutex_exit(&msp->ms_lock);
1535
1536         return (0);
1537 }
1538
1539 int
1540 metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
1541     int ndvas, uint64_t txg, blkptr_t *hintbp, int flags)
1542 {
1543         dva_t *dva = bp->blk_dva;
1544         dva_t *hintdva = hintbp->blk_dva;
1545         int d, error = 0;
1546
1547         ASSERT(bp->blk_birth == 0);
1548         ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
1549
1550         spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
1551
1552         if (mc->mc_rotor == NULL) {     /* no vdevs in this class */
1553                 spa_config_exit(spa, SCL_ALLOC, FTAG);
1554                 return (ENOSPC);
1555         }
1556
1557         ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
1558         ASSERT(BP_GET_NDVAS(bp) == 0);
1559         ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
1560
1561         for (d = 0; d < ndvas; d++) {
1562                 error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
1563                     txg, flags);
1564                 if (error) {
1565                         for (d--; d >= 0; d--) {
1566                                 metaslab_free_dva(spa, &dva[d], txg, B_TRUE);
1567                                 bzero(&dva[d], sizeof (dva_t));
1568                         }
1569                         spa_config_exit(spa, SCL_ALLOC, FTAG);
1570                         return (error);
1571                 }
1572         }
1573         ASSERT(error == 0);
1574         ASSERT(BP_GET_NDVAS(bp) == ndvas);
1575
1576         spa_config_exit(spa, SCL_ALLOC, FTAG);
1577
1578         BP_SET_BIRTH(bp, txg, txg);
1579
1580         return (0);
1581 }
1582
1583 void
1584 metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
1585 {
1586         const dva_t *dva = bp->blk_dva;
1587         int d, ndvas = BP_GET_NDVAS(bp);
1588
1589         ASSERT(!BP_IS_HOLE(bp));
1590         ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
1591
1592         spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
1593
1594         for (d = 0; d < ndvas; d++)
1595                 metaslab_free_dva(spa, &dva[d], txg, now);
1596
1597         spa_config_exit(spa, SCL_FREE, FTAG);
1598 }
1599
1600 int
1601 metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
1602 {
1603         const dva_t *dva = bp->blk_dva;
1604         int ndvas = BP_GET_NDVAS(bp);
1605         int d, error = 0;
1606
1607         ASSERT(!BP_IS_HOLE(bp));
1608
1609         if (txg != 0) {
1610                 /*
1611                  * First do a dry run to make sure all DVAs are claimable,
1612                  * so we don't have to unwind from partial failures below.
1613                  */
1614                 if ((error = metaslab_claim(spa, bp, 0)) != 0)
1615                         return (error);
1616         }
1617
1618         spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
1619
1620         for (d = 0; d < ndvas; d++)
1621                 if ((error = metaslab_claim_dva(spa, &dva[d], txg)) != 0)
1622                         break;
1623
1624         spa_config_exit(spa, SCL_ALLOC, FTAG);
1625
1626         ASSERT(error == 0 || txg == 0);
1627
1628         return (error);
1629 }