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